<?php
// api/get_client_summary.php?id=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';

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

try {
    // 1) Load client
    $stmt = $pdo->prepare("
        SELECT Id, ClientId, FullName, Phone, Email
        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;
    }

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

    if (!$contracts) {
        echo json_encode([
            'client'   => $client,
            'summary'  => [
                'totalPlots'    => 0,
                'totalPaid'     => 0,
                'balance'       => 0,
                // extra fields for WPF, null/zero so web stays fine
                'planType'      => null,
                'planMonths'    => null,
                'monthlyAmount' => null
            ],
            'plots'    => [],
            'payments' => []
        ]);
        exit;
    }

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

    // 3) Payments totals per contract
    $paidByContract = [];
    if ($contractIds) {
        $inContract = implode(',', array_fill(0, count($contractIds), '?'));
        $payStmt = $pdo->prepare("
            SELECT ContractId, IFNULL(SUM(Amount), 0) AS TotalPaid
            FROM ClientPayments
            WHERE ContractId IN ($inContract)
            GROUP BY ContractId
        ");
        $payStmt->execute($contractIds);
        $paymentsTotals = $payStmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($paymentsTotals as $p) {
            $paidByContract[(int)$p['ContractId']] = (float)$p['TotalPaid'];
        }
    }

    // 4) Detailed payments list for history (web + WPF both use this)
    $paymentsDetail = [];
    if ($contractIds) {
        $inContract2 = implode(',', array_fill(0, count($contractIds), '?'));
        $payDetailStmt = $pdo->prepare("
            SELECT 
                Id,
                ContractId,
                InvoiceNumber,
                PaymentDate,
                Amount,
                Method,
                Reference
            FROM ClientPayments
            WHERE ContractId IN ($inContract2)
            ORDER BY PaymentDate ASC, Id ASC
        ");
        $payDetailStmt->execute($contractIds);
        $paymentsDetail = $payDetailStmt->fetchAll(PDO::FETCH_ASSOC);

        // Ensure Amount is numeric for JSON
        foreach ($paymentsDetail as &$pay) {
            $pay['Amount'] = isset($pay['Amount']) ? (float)$pay['Amount'] : 0.0;
        }
        unset($pay);
    }

    // 5) Load plots (with AreaId)
    $plotById = [];
    $areaIds  = [];
    if ($plotIds) {
        $inPlots = implode(',', array_fill(0, count($plotIds), '?'));
        $plotsStmt = $pdo->prepare("
            SELECT Id, AreaId, Code
            FROM Plots
            WHERE Id IN ($inPlots)
        ");
        $plotsStmt->execute($plotIds);
        $plots = $plotsStmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($plots as $p) {
            $pid = (int)$p['Id'];
            $plotById[$pid] = $p;
            if (!empty($p['AreaId'])) {
                $areaIds[] = (int)$p['AreaId'];
            }
        }
    }

    // 6) Load areas for those plots
    $areaById = [];
    if ($areaIds) {
        $areaIds = array_values(array_unique($areaIds));
        $inAreas = implode(',', array_fill(0, count($areaIds), '?'));
        $areasStmt = $pdo->prepare("
            SELECT Id, Name
            FROM Areas
            WHERE Id IN ($inAreas)
        ");
        $areasStmt->execute($areaIds);
        $areas = $areasStmt->fetchAll(PDO::FETCH_ASSOC);

        foreach ($areas as $a) {
            $areaById[(int)$a['Id']] = $a['Name'];
        }
    }

    // 7) Build plots payload and totals
    $plotsPayload = [];
    $totalFinal   = 0.0;
    $totalPaidAll = 0.0;

    foreach ($contracts as $c) {
        $cid    = (int)$c['Id'];
        $plotId = (int)$c['PlotId'];

        $finalPrice = isset($c['FinalPrice']) ? (float)$c['FinalPrice'] : 0.0;
        $paid       = $paidByContract[$cid] ?? 0.0;

        $totalFinal   += $finalPrice;
        $totalPaidAll += $paid;

        $plot = $plotById[$plotId] ?? null;
        if ($plot) {
            $areaId   = (int)$plot['AreaId'];
            $areaName = $areaById[$areaId] ?? 'Unknown Area';

            // Keep old field FinalPrice for web, and add Price + Status for WPF
            $plotsPayload[] = [
                'AreaName'   => $areaName,
                'PlotCode'   => $plot['Code'],
                'FinalPrice' => $finalPrice,                // existing web field
                'Price'      => $finalPrice,                // for WPF ClientPlotDto.Price
                'Status'     => $c['Status'] ?? 'Active'    // for WPF ClientPlotDto.Status
            ];
        }
    }

    $balance = $totalFinal - $totalPaidAll;
    if ($balance < 0) {
        $balance = 0.0;
    }

    // Derive plan info from the latest contract (by Id desc)
    usort($contracts, function($a, $b) {
        return (int)$b['Id'] <=> (int)$a['Id'];
    });
    $latest = $contracts[0];

    $planType      = $latest['PlanType']      ?? 'Full';
    $planMonths    = isset($latest['PlanMonths'])    ? (int)$latest['PlanMonths']    : null;
    $monthlyAmount = isset($latest['MonthlyAmount']) ? (float)$latest['MonthlyAmount'] : null;

    echo json_encode([
        'client'  => $client,
        'summary' => [
            'totalPlots'    => count($contracts),
            'totalPaid'     => $totalPaidAll,
            'balance'       => $balance,
            // new fields for WPF, web JS can ignore them
            'planType'      => $planType,
            'planMonths'    => $planMonths,
            'monthlyAmount' => $monthlyAmount
        ],
        'plots'    => $plotsPayload,
        'payments' => $paymentsDetail
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error'   => 'Failed to load client summary',
        'details' => $e->getMessage()
    ]);
}
