<?php
// api/get_payment_receipt.php?paymentId=10
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';

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

try {
    // 1) Load payment + contract + client + plot + area
    $sql = "
        SELECT
            p.Id                  AS PaymentId,
            p.ContractId          AS ContractId,
            p.PaymentDate,
            p.Amount,
            p.Method,
            p.Reference,
            p.Notes,
            p.InvoiceNumber,

            c.Id                  AS ClientId,
            c.ClientId            AS ClientCode,
            c.FullName            AS ClientName,
            c.Phone               AS ClientPhone,
            c.Email               AS ClientEmail,

            cc.FinalPrice         AS ContractFinalPrice,
            cc.Status             AS ContractStatus,

            pl.Code               AS PlotCode,
            a.Name                AS AreaName
        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
        WHERE p.Id = :paymentId
        LIMIT 1
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute([':paymentId' => $paymentId]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

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

    $contractId = (int)$row['ContractId'];

    // 2) Compute totals for this contract
    // 2a) Total paid BEFORE this payment
    $sumBeforeStmt = $pdo->prepare("
        SELECT IFNULL(SUM(Amount), 0) AS TotalPaidBefore
        FROM ClientPayments
        WHERE ContractId = :contractId
          AND Id < :paymentId
          AND (IsDeleted IS NULL OR IsDeleted = 0)
    ");
    $sumBeforeStmt->execute([
        ':contractId' => $contractId,
        ':paymentId'  => $paymentId
    ]);
    $beforeRow = $sumBeforeStmt->fetch(PDO::FETCH_ASSOC);
    $totalPaidBefore = (float)($beforeRow['TotalPaidBefore'] ?? 0);

    // 2b) Total paid INCLUDING this payment
    $sumAllStmt = $pdo->prepare("
        SELECT IFNULL(SUM(Amount), 0) AS TotalPaidAll
        FROM ClientPayments
        WHERE ContractId = :contractId
          AND (IsDeleted IS NULL OR IsDeleted = 0)
    ");
    $sumAllStmt->execute([':contractId' => $contractId]);
    $allRow = $sumAllStmt->fetch(PDO::FETCH_ASSOC);
    $totalPaidAll = (float)($allRow['TotalPaidAll'] ?? 0);

    $contractValue = (float)$row['ContractFinalPrice'];
    $outstanding   = max($contractValue - $totalPaidAll, 0);

    // 3) Build formatted fields for receipt.html
    $paymentDate = $row['PaymentDate']; // raw DB value
    $issueDate   = date('d M Y, h:i A');

    // Prefer InvoiceNumber if set
    $receiptNumber = $row['InvoiceNumber'];
    if (!$receiptNumber) {
        $receiptNumber = sprintf(
            'REC-%s-%04d',
            date('Ymd', strtotime($paymentDate)),
            (int)$row['PaymentId']
        );
    }

    $clientCode = $row['ClientCode'];
    if (!$clientCode) {
        // fallback like desktop: CL-000001 style
        $clientCode = sprintf('CL-%06d', (int)$row['ClientId']);
    }

    $contractCode = sprintf('CT-%06d', $contractId);

    $amountPaid      = (float)$row['Amount'];
    $totalValue      = $contractValue;
    $totalPaidBefore = $totalPaidBefore;

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

    // Normalize status from ClientContracts.Status
    // Default in schema is 'Active', can also be 'Completed'
    $rawContractStatus = $row['ContractStatus'] ?? '';
    $statusNorm = strtolower(trim((string)$rawContractStatus));

    if ($statusNorm === 'completed') {
        $plotStatusText = 'Completed';
    } else {
        // treat anything else (Active, Pending, etc.) as its own label
        // but keep the original casing for display
        $plotStatusText = $rawContractStatus !== '' ? $rawContractStatus : 'Active';
    }

    // Single-plot contract -> expose as plots array for Purchased Plot section
    $plots = [
        [
            'area'   => $row['AreaName'],
            'code'   => $row['PlotCode'],
            'price'  => $formatMoney($contractValue),
            'status' => $plotStatusText
        ]
    ];

    $payload = [
        // header/meta
        'receiptNumber'   => $receiptNumber,
        'issueDate'       => $issueDate,

        // client
        'clientId'        => $clientCode,
        'contractId'      => $contractCode,
        'clientName'      => $row['ClientName'],
        'clientPhone'     => $row['ClientPhone'],
        'clientEmail'     => $row['ClientEmail'],

        // payment
        'paymentDate'     => date('d M Y', strtotime($paymentDate)),
        'paymentMethod'   => $row['Method'],
        'paymentReference'=> $row['Reference'],
        'paymentNotes'    => $row['Notes'] ?: 'None',

        // amounts
        'amountPaid'      => $formatMoney($amountPaid),
        'totalValue'      => $formatMoney($totalValue),
        'totalPaidBefore' => $formatMoney($totalPaidBefore),
        'outstanding'     => $formatMoney($outstanding),

        // extra context
        'areaName'        => $row['AreaName'],
        'plotCode'        => $row['PlotCode'],

        // Purchased Plot section
        'plots'           => $plots,
    ];

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