<?php
// api/get_client_summary_report.php?clientId=6
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';

$clientId = isset($_GET['clientId']) ? (int)$_GET['clientId'] : 0;
if ($clientId <= 0) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing or invalid clientId']);
    exit;
}

try {
    // 1) Load client
    $stmt = $pdo->prepare("
        SELECT
            Id,
            ClientId,
            FullName,
            Phone,
            Email,
            CreatedAt
        FROM Clients
        WHERE Id = :id
        LIMIT 1
    ");
    $stmt->execute([':id' => $clientId]);
    $client = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$client) {
        http_response_code(404);
        echo json_encode(['error' => 'Client not found']);
        exit;
    }

    $clientPkId  = (int)$client['Id'];
    $clientCode  = $client['ClientId'];
    if (!$clientCode) {
        $clientCode = sprintf('CLI-%06d', $clientPkId);
    }
    $clientName  = $client['FullName'];
    $clientPhone = $client['Phone'];
    $clientEmail = $client['Email'];
    $createdAt   = $client['CreatedAt'];
    $registered  = $createdAt ? date('d F Y', strtotime($createdAt)) : 'N/A';

    // 2) Load all contracts for this client
    $contractsStmt = $pdo->prepare("
        SELECT
            Id,
            PlotId,
            FinalPrice,
            PlanType,
            PlanMonths,
            MonthlyAmount,
            Status
        FROM ClientContracts
        WHERE ClientId = :clientId
    ");
    $contractsStmt->execute([':clientId' => $clientPkId]);
    $contracts = $contractsStmt->fetchAll(PDO::FETCH_ASSOC);

    if (!$contracts) {
        // No contracts: return a mostly empty report
        $payload = [
            'reportId'       => 'REP-' . date('Ymd') . '-' . random_int(1000, 9999),
            'generatedDate'  => date('d F Y, h:i A'),
            'clientId'       => $clientCode,
            'clientName'     => $clientName,
            'clientPhone'    => $clientPhone,
            'clientEmail'    => $clientEmail,
            'registeredDate' => $registered,

            'totalPlots'     => 0,
            'totalValue'     => '0.00',
            'amountPaid'     => '0.00',
            'outstanding'    => '0.00',

            'planType'       => 'Full',
            'planDuration'   => 'N/A',
            'monthlyAmount'  => '0.00',

            'plots'          => [],
            'payments'       => []
        ];
        echo json_encode($payload);
        exit;
    }

    $contractIds = array_column($contracts, 'Id');
    $plotIds     = array_column($contracts, 'PlotId');

    // 3) Aggregate payments per contract
    $totalPaidByContract = [];
    $payments = [];

    if ($contractIds) {
        $inContracts = implode(',', array_fill(0, count($contractIds), '?'));

        // all payments for these contracts
        $payStmt = $pdo->prepare("
            SELECT
                Id,
                ContractId,
                PaymentDate,
                Amount,
                Method,
                Reference
            FROM ClientPayments
            WHERE ContractId IN ($inContracts)
              AND (IsDeleted IS NULL OR IsDeleted = 0)
            ORDER BY PaymentDate ASC, Id ASC
        ");
        $payStmt->execute($contractIds);
        $paymentRows = $payStmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($paymentRows as $p) {
            $cid = (int)$p['ContractId'];
            $amt = (float)$p['Amount'];

            if (!isset($totalPaidByContract[$cid])) {
                $totalPaidByContract[$cid] = 0.0;
            }
            $totalPaidByContract[$cid] += $amt;

            // map to summary.html payments[]
            $payments[] = [
                'date'      => $p['PaymentDate'] ? date('d M Y', strtotime($p['PaymentDate'])) : '',
                'amount'    => number_format($amt, 2, '.', ','),
                'method'    => $p['Method'] ?? '',
                'reference' => $p['Reference'] ?? ''
            ];
        }
    }

    // 4) Load plots + areas
    $plotsById = [];
    if ($plotIds) {
        $inPlots = implode(',', array_fill(0, count($plotIds), '?'));
        $plotsStmt = $pdo->prepare("
            SELECT
                pl.Id,
                pl.AreaId,
                pl.Code,
                pl.FullPrice,
                pl.Status,
                a.Name AS AreaName
            FROM Plots pl
            INNER JOIN Areas a ON a.Id = pl.AreaId
            WHERE pl.Id IN ($inPlots)
        ");
        $plotsStmt->execute($plotIds);
        $plotRows = $plotsStmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($plotRows as $p) {
            $plotsById[(int)$p['Id']] = $p;
        }
    }

    // 5) Build plots array + compute totals and derived plan summary
    $plots       = [];
    $totalValue  = 0.0;
    $totalPaid   = 0.0;

    // plan summary: use latest contract as in desktop (GetLatestActiveContractIdForClient)
    usort($contracts, function ($a, $b) {
        return $b['Id'] <=> $a['Id']; // descending by Id
    });
    $latestContract = $contracts[0];

    $planType   = $latestContract['PlanType'] ?? 'Full';
    $planMonths = (int)($latestContract['PlanMonths'] ?? 0);
    $monthlyAmt = (float)($latestContract['MonthlyAmount'] ?? 0);

    foreach ($contracts as $c) {
        $cid       = (int)$c['Id'];
        $plotId    = (int)$c['PlotId'];
        $final     = (float)$c['FinalPrice'];
        $rawStatus = $c['Status'] ?? 'Active'; // text: "Active" / "Completed" etc.

        // Normalize status for the report (string-based)
        $statusText = strtolower(trim((string)$rawStatus));
        if ($statusText === 'completed' || $statusText === '2') {
            $statusLabel = 'Completed';
            $statusType  = 'completed';
        } else {
            $statusLabel = 'Active';
            $statusType  = 'active';
        }

        $paidHere = $totalPaidByContract[$cid] ?? 0.0;

        $totalValue += $final;
        $totalPaid  += $paidHere;

        $plot = $plotsById[$plotId] ?? null;
        if ($plot) {
            $plots[] = [
                'area'       => $plot['AreaName'] ?? '',
                'code'       => $plot['Code'] ?? '',
                'price'      => number_format($final, 2, '.', ','),
                'status'     => $statusLabel,   // text that will be shown
                'statusType' => $statusType     // helper for CSS
            ];
        }
    }

    $outstanding = max($totalValue - $totalPaid, 0);

    $formatMoney = function (float $v): string {
        return number_format($v, 2, '.', ',');
    };

    $planDurationText = $planMonths > 0 ? $planMonths . ' months' : 'N/A';
    $monthlyText      = $planMonths > 0 ? $formatMoney($monthlyAmt) : '0.00';

    // 6) Build payload for summary.html
    $payload = [
        'reportId'       => 'REP-' . date('Ymd') . '-' . random_int(1000, 9999),
        'generatedDate'  => date('d F Y, h:i A'),

        'clientId'       => $clientCode,
        'clientName'     => $clientName,
        'clientPhone'    => $clientPhone,
        'clientEmail'    => $clientEmail,
        'registeredDate' => $registered,

        'totalPlots'     => count($contracts),
        'totalValue'     => $formatMoney($totalValue),
        'amountPaid'     => $formatMoney($totalPaid),
        'outstanding'    => $formatMoney($outstanding),

        'planType'       => $planType,
        'planDuration'   => $planDurationText,
        'monthlyAmount'  => $monthlyText,

        'plots'          => $plots,
        'payments'       => $payments
    ];

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