<?php
// api/get_contract_payment_info.php?contract=CT-000043 OR ?contract=123
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';

// accept either numeric id or text code from a single 'contract' parameter
$raw = isset($_GET['contract']) ? trim($_GET['contract']) : '';

if ($raw === '') {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing contract']);
    exit;
}

// decide how to search
$isNumeric = ctype_digit($raw);
$numericId = $isNumeric ? (int)$raw : 0;

try {
    $sql = "
    SELECT 
        c.Id         AS ContractDbId,
        c.FinalPrice,
        c.Status,
        c.ContractId AS ContractCode,
        cl.ClientId  AS ClientCode,
        cl.FullName  AS ClientFullName,   -- NEW
        cl.Email     AS ClientEmail,
        cl.Phone     AS ClientPhone,
        p.Code       AS PlotCode,
        a.Name       AS AreaName
    FROM ClientContracts c
    JOIN Clients cl ON c.ClientId = cl.Id
    JOIN Plots   p  ON c.PlotId   = p.Id
    JOIN Areas   a  ON p.AreaId   = a.Id
    WHERE (c.Id = :id)
       OR (c.ContractId IS NOT NULL AND c.ContractId = :code)
    LIMIT 1
";


    $stmt = $pdo->prepare($sql);
    $stmt->execute([
        ':id'   => $numericId,   // 0 if not numeric
        ':code' => $raw
    ]);
    $row = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$row) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Contract not found']);
        exit;
    }

    // numeric fields
    $row['FinalPrice'] = isset($row['FinalPrice']) ? (float)$row['FinalPrice'] : 0.0;

    // total paid
    $sqlPaid = "
        SELECT IFNULL(SUM(Amount), 0) AS TotalPaid
        FROM ClientPayments
        WHERE ContractId = :id
    ";
    $stmt2 = $pdo->prepare($sqlPaid);
    $stmt2->execute([':id' => (int)$row['ContractDbId']]);
    $paidRow = $stmt2->fetch(PDO::FETCH_ASSOC);
    $totalPaid = $paidRow ? (float)$paidRow['TotalPaid'] : 0.0;

    $row['TotalPaid'] = $totalPaid;

    // compute outstanding here
    $row['Outstanding'] = max($row['FinalPrice'] - $totalPaid, 0.0);

    echo json_encode([
        'success' => true,
        'data'    => $row
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load contract payment info',
        'details' => $e->getMessage()
    ]);
}
