<?php
// api/recent_payments.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
            p.Id,
            p.PaymentDate,
            p.Amount,
            p.Method,
            c.FullName AS ClientName
        FROM ClientPayments p
        INNER JOIN ClientContracts cc ON cc.Id = p.ContractId
        INNER JOIN Clients c         ON c.Id  = cc.ClientId
        WHERE (p.IsDeleted IS NULL OR p.IsDeleted = 0)
        ORDER BY p.PaymentDate DESC, p.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'],
            'PaymentDate' => $r['PaymentDate'], // JS will format if needed
            'Amount'      => (float)$r['Amount'],
            'Method'      => $r['Method'],
            'ClientName'  => $r['ClientName'],
        ];
    }

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