<?php
// api/get_contract_details.php?id=15 OR ?id=CT-000043
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 internal Id or textual ContractId from a single 'id' parameter
$raw = isset($_GET['id']) ? trim($_GET['id']) : '';

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

$isNumeric = ctype_digit($raw);
$numericId = $isNumeric ? (int)$raw : 0;

try {
    // 1) Load contract + client + plot + area
    $sql = "
        SELECT 
            c.Id               AS ContractDbId,
            c.ContractId       AS ContractCode,
            c.ClientId         AS ClientDbId,
            c.PlotId           AS PlotDbId,
            c.OriginalPrice,
            c.DiscountCode,
            c.DiscountType,
            c.DiscountValue,
            c.DiscountAmount,
            c.FinalPrice,
            c.PlanType,
            c.PlanMonths,
            c.MonthlyAmount,
            c.Status,
            c.CreatedAt        AS ContractCreatedAt,
            c.LastModified     AS ContractLastModified,

            cl.Id              AS ClientId,
            cl.ClientId        AS ClientCode,
            cl.FullName        AS ClientFullName,
            cl.Phone           AS ClientPhone,
            cl.Email           AS ClientEmail,

            p.Id               AS PlotId,
            p.Code             AS PlotCode,
            a.Id               AS AreaId,
            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;
    }

    // Cast numeric money fields
    $finalPrice     = isset($row['FinalPrice'])     ? (float)$row['FinalPrice']     : 0.0;
    $originalPrice  = isset($row['OriginalPrice'])  ? (float)$row['OriginalPrice']  : 0.0;
    $discountValue  = isset($row['DiscountValue'])  ? (float)$row['DiscountValue']  : 0.0;
    $discountAmount = isset($row['DiscountAmount']) ? (float)$row['DiscountAmount'] : 0.0;
    $monthlyAmount  = isset($row['MonthlyAmount'])  ? (float)$row['MonthlyAmount']  : 0.0;
    $planMonths     = isset($row['PlanMonths'])     ? (int)$row['PlanMonths']       : 0;

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

    // 3) Compute outstanding
    $outstanding = max($finalPrice - $totalPaid, 0.0);

    // 4) Shape response for record_payment.js
    $client = [
        'Id'        => (int)$row['ClientId'],
        'ClientId'  => $row['ClientCode'],
        'FullName'  => $row['ClientFullName'],
        'Phone'     => $row['ClientPhone'],
        'Email'     => $row['ClientEmail'],
    ];

    $contract = [
        'Id'             => (int)$row['ContractDbId'],
        'ContractId'     => $row['ContractCode'],
        'ClientId'       => (int)$row['ClientDbId'],
        'PlotId'         => (int)$row['PlotDbId'],
        'OriginalPrice'  => $originalPrice,
        'DiscountCode'   => $row['DiscountCode'],
        'DiscountType'   => $row['DiscountType'],
        'DiscountValue'  => $discountValue,
        'DiscountAmount' => $discountAmount,
        'FinalPrice'     => $finalPrice,
        'PlanType'       => $row['PlanType'],
        'PlanMonths'     => $planMonths,
        'MonthlyAmount'  => $monthlyAmount,
        'Status'         => $row['Status'],
        'CreatedAt'      => $row['ContractCreatedAt'],
        'LastModified'   => $row['ContractLastModified'],
    ];

    $plot = [
        'Id'       => (int)$row['PlotId'],
        'PlotCode' => $row['PlotCode'],
        'AreaId'   => (int)$row['AreaId'],
        'AreaName' => $row['AreaName'],
    ];

    $totals = [
        'totalPaid'   => $totalPaid,
        'outstanding' => $outstanding,
    ];

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