<?php
// api/get_client_full.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', '*');

if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

require_once __DIR__ . '/../../config.php';

$clientId = isset($_GET['client_id']) ? (int)$_GET['client_id'] : 0;
if ($clientId <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'client_id is required']);
    exit;
}

try {
    // 1) Load basic 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(['success' => false, 'message' => 'Client not found']);
        exit;
    }

    // 2) Financial summary: totals + plan → from ClientContracts + ClientPayments
    $summarySql = "
        SELECT 
            COUNT(DISTINCT cc.Id)                AS TotalPlots,
            COALESCE(SUM(cc.FinalPrice), 0)      AS TotalValue,
            COALESCE((
                SELECT SUM(cp.Amount)
                FROM ClientPayments cp
                WHERE cp.ContractId = cc.Id AND (cp.IsDeleted IS NULL OR cp.IsDeleted = 0)
            ), 0)                                AS AmountPaid,
            COALESCE(SUM(cc.FinalPrice), 0) - COALESCE((
                SELECT SUM(cp.Amount)
                FROM ClientPayments cp
                WHERE cp.ContractId = cc.Id AND (cp.IsDeleted IS NULL OR cp.IsDeleted = 0)
            ), 0)                                AS Outstanding,
            -- Assume latest contract defines the plan
            (SELECT PlanType FROM ClientContracts 
             WHERE ClientId = :ClientId 
             ORDER BY CreatedAt DESC LIMIT 1)    AS PlanType,
            (SELECT PlanMonths FROM ClientContracts 
             WHERE ClientId = :ClientId 
             ORDER BY CreatedAt DESC LIMIT 1)    AS PlanMonths,
            (SELECT MonthlyAmount FROM ClientContracts 
             WHERE ClientId = :ClientId 
             ORDER BY CreatedAt DESC LIMIT 1)    AS MonthlyAmount
        FROM ClientContracts cc
        WHERE cc.ClientId = :ClientId
    ";
    $stmt = $pdo->prepare($summarySql);
    $stmt->execute([':ClientId' => $clientId]);
    $summary = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$summary) {
        $summary = [
            'TotalPlots'    => 0,
            'TotalValue'    => 0,
            'AmountPaid'    => 0,
            'Outstanding'   => 0,
            'PlanType'      => 'Full',
            'PlanMonths'    => null,
            'MonthlyAmount' => null,
        ];
    }

    // 3) Plots for this client (join ClientContracts + Plots + Areas)
    $plotsSql = "
        SELECT 
            cc.Id                  AS Id,
            a.Name                 AS AreaName,
            p.Code                 AS PlotCode,
            cc.FinalPrice          AS Price,
            cc.Status              AS Status
        FROM ClientContracts cc
        JOIN Plots p   ON p.Id = cc.PlotId
        JOIN Areas a   ON a.Id = p.AreaId
        WHERE cc.ClientId = :ClientId
    ";
    $stmt = $pdo->prepare($plotsSql);
    $stmt->execute([':ClientId' => $clientId]);
    $plots = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 4) Payments for this client (all contracts)
    $paymentsSql = "
        SELECT 
            cp.Id,
            cp.ContractId,
            cp.PaymentDate,
            cp.Amount,
            cp.Method,
            cp.Reference,
            cp.Notes,
            cp.InvoiceNumber
        FROM ClientPayments cp
        JOIN ClientContracts cc ON cc.Id = cp.ContractId
        WHERE cc.ClientId = :ClientId
          AND (cp.IsDeleted IS NULL OR cp.IsDeleted = 0)
        ORDER BY cp.PaymentDate DESC, cp.Id DESC
    ";
    $stmt = $pdo->prepare($paymentsSql);
    $stmt->execute([':ClientId' => $clientId]);
    $payments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // 5) Latest active contract
    $latestSql = "
        SELECT Id AS ContractId
        FROM ClientContracts
        WHERE ClientId = :ClientId
          AND Status = 'ACTIVE'
        ORDER BY CreatedAt DESC
        LIMIT 1
    ";
    $stmt = $pdo->prepare($latestSql);
    $stmt->execute([':ClientId' => $clientId]);
    $latest = $stmt->fetch(PDO::FETCH_ASSOC);

    $latestContract = [
        'hasActive'  => $latest ? true : false,
        'contractId' => $latest ? (int)$latest['ContractId'] : null,
    ];

    echo json_encode([
        'success'       => true,
        'client'        => $client,
        'summary'       => $summary,
        'plots'         => $plots,
        'payments'      => $payments,
        'latestContract'=> $latestContract,
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'message' => 'Failed to load client data.',
        'details' => $e->getMessage()
    ]);
}
