<?php
// api/get_payments_summary.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';

function parseDateOrNull($s) {
    if (!$s) return null;
    $t = strtotime($s);
    return $t ? date('Y-m-d', $t) : null;
}

$start  = isset($_GET['start'])  ? parseDateOrNull($_GET['start'])  : null;
$end    = isset($_GET['end'])    ? parseDateOrNull($_GET['end'])    : null;
$search = isset($_GET['search']) ? trim($_GET['search'])            : '';

try {
    // ========== 1) WHERE for payments list ==========
    $where  = ['(p.IsDeleted IS NULL OR p.IsDeleted = 0)'];
    $params = [];

    if ($start) {
        $where[] = 'p.PaymentDate >= :start';
        $params[':start'] = $start;
    }
    if ($end) {
        $where[] = 'p.PaymentDate <= :end';
        $params[':end'] = $end;
    }
    if ($search !== '') {
        $where[] = '(c.FullName LIKE :search 
                 OR c.ClientId LIKE :search 
                 OR p.InvoiceNumber LIKE :search 
                 OR p.Reference LIKE :search 
                 OR a.Name LIKE :search 
                 OR pl.Code LIKE :search)';
        $params[':search'] = '%' . $search . '%';
    }

    $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

    // ========== 2) Payments list (now includes ProofFilePath) ==========
    $sql = "
        SELECT
            p.Id,
            p.PaymentDate,
            p.InvoiceNumber,
            p.Amount,
            p.Method,
            p.Reference,
            p.ProofFilePath,

            c.FullName    AS ClientName,
            a.Name        AS AreaName,
            pl.Code       AS PlotCode,
            cc.Id         AS ContractId,
            cc.FinalPrice AS ContractFinalPrice,
            cc.Status     AS ContractStatus
        FROM ClientPayments p
        INNER JOIN ClientContracts cc ON cc.Id = p.ContractId
        INNER JOIN Clients c          ON c.Id  = cc.ClientId
        INNER JOIN Plots pl           ON pl.Id = cc.PlotId
        INNER JOIN Areas a            ON a.Id  = pl.AreaId
        $whereSql
        ORDER BY p.PaymentDate DESC, p.Id DESC
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $payments      = [];
    $totalReceived = 0.0;

    // For contract-level summary
    $contractTotals = []; // [contractId => ['finalPrice' => x, 'totalPaid' => y, 'status' => 'Active']]

    foreach ($rows as $r) {
        $amount = (float)$r['Amount'];
        $totalReceived += $amount;

        $contractId   = (int)$r['ContractId'];
        $finalPrice   = (float)$r['ContractFinalPrice'];
        $contractStat = $r['ContractStatus'];

        if (!isset($contractTotals[$contractId])) {
            $contractTotals[$contractId] = [
                'finalPrice' => $finalPrice,
                'totalPaid'  => 0.0,
                'status'     => $contractStat,
            ];
        }

        $contractTotals[$contractId]['totalPaid'] += $amount;

        $date = $r['PaymentDate'] ? date('d M Y', strtotime($r['PaymentDate'])) : '';

        $payments[] = [
            'Id'                    => (int)$r['Id'],
            'PaymentDate'           => $r['PaymentDate'],
            'PaymentDateFormatted'  => $date,
            'InvoiceNumber'         => $r['InvoiceNumber'],
            'Amount'                => $amount,
            'Method'                => $r['Method'],
            'Reference'             => $r['Reference'],
            'ProofFilePath'         => $r['ProofFilePath'],  // new field
            'ClientName'            => $r['ClientName'],
            'AreaName'              => $r['AreaName'],
            'PlotCode'              => $r['PlotCode'],
        ];
    }

    // ========== 3) Compute Expected & Outstanding by contract ==========
    $totalExpected    = 0.0;
    $totalOutstanding = 0.0;

    foreach ($contractTotals as $ct) {
        $finalPrice = $ct['finalPrice'];
        $paid       = $ct['totalPaid'];
        $status     = $ct['status'];

        // Only count contracts that are not cancelled
        if ($status === 'Cancelled') {
            continue;
        }

        $totalExpected += $finalPrice;

        // Outstanding is zero for fully paid / completed
        $outstanding = max($finalPrice - $paid, 0.0);
        if ($status === 'Completed') {
            $outstanding = 0.0;
        }

        $totalOutstanding += $outstanding;
    }

    $payload = [
        'summary' => [
            'totalReceived'    => $totalReceived,
            'totalExpected'    => $totalExpected,
            'totalOutstanding' => $totalOutstanding,
        ],
        'payments' => $payments,
    ];

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