<?php
// api/recent_purchases.php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../../config.php';

try {
    // Limit can be passed as ?limit=10 (default 10, max 50)
    $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
    if ($limit <= 0) $limit = 10;
    if ($limit > 50) $limit = 50;

    $sql = "
        SELECT
            cc.Id,
            cc.CreatedAt,
            cc.Status,
            c.FullName AS ClientName,
            pl.Code    AS PlotCode
        FROM ClientContracts cc
        INNER JOIN Clients c ON c.Id  = cc.ClientId
        INNER JOIN Plots   pl ON pl.Id = cc.PlotId
        ORDER BY cc.CreatedAt DESC, cc.Id DESC
        LIMIT :limit
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $stmt->execute();
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $result = [];
    foreach ($rows as $r) {
        $result[] = [
            'Id'         => (int)$r['Id'],
            'CreatedAt'  => $r['CreatedAt'],   // JS will format if needed
            'Status'     => $r['Status'],
            'ClientName' => $r['ClientName'],
            'PlotCode'   => $r['PlotCode'],
        ];
    }

    echo json_encode($result);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error'   => 'Failed to load recent purchases',
        'details' => $e->getMessage()
    ]);
}
