<?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: *');

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

function parseDateOrNull($s) {
    if (!$s) return null;
    $t = strtotime($s);
    return $t ? date('Y-m-d', $t) : null;
}

$start    = isset($_GET['start'])    ? parseDateOrNull($_GET['start'])    : null;
$end      = isset($_GET['end'])      ? parseDateOrNull($_GET['end'])      : null;
$status   = isset($_GET['status'])   ? $_GET['status']   : 'ALL';
$planType = isset($_GET['planType']) ? $_GET['planType'] : 'ALL';
$search   = isset($_GET['search'])   ? trim($_GET['search']) : '';

try {
    $where  = [];
    $params = [];

    if ($start) {
        $where[] = 'cc.CreatedAt >= :start';
        $params[':start'] = $start . ' 00:00:00';
    }
    if ($end) {
        $where[] = 'cc.CreatedAt <= :end';
        $params[':end'] = $end . ' 23:59:59';
    }
    if ($status && $status !== 'ALL') {
        $where[] = 'cc.Status = :status';
        $params[':status'] = $status;
    }
    if ($planType && $planType !== 'ALL') {
        $where[] = 'cc.PlanType = :planType';
        $params[':planType'] = $planType;
    }
    if ($search !== '') {
        $where[] = '(c.FullName LIKE :search OR c.ClientId LIKE :search OR a.Name LIKE :search OR pl.Code LIKE :search)';
        $params[':search'] = '%' . $search . '%';
    }

    $whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

    // Main contracts + client/area/plot
    $sql = "
        SELECT
            cc.Id,
            cc.CreatedAt,
            c.FullName      AS ClientName,
            c.ClientId      AS ClientCode,
            a.Name          AS AreaName,
            pl.Code         AS PlotCode,
            cc.PlanType,
            IFNULL(cc.PlanMonths, 0)   AS PlanMonths,
            cc.FinalPrice,
            IFNULL(paid.TotalPaid, 0)  AS AmountPaid,
            cc.Status
        FROM ClientContracts cc
        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
        LEFT JOIN (
            SELECT ContractId, SUM(Amount) AS TotalPaid
            FROM ClientPayments
            WHERE IsDeleted IS NULL OR IsDeleted = 0
            GROUP BY ContractId
        ) AS paid ON paid.ContractId = cc.Id
        $whereSql
        ORDER BY cc.CreatedAt DESC, cc.Id DESC
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $contracts = [];
    $totalContracts   = 0;
    $totalValue       = 0.0;
    $totalPaid        = 0.0;
    $totalOutstanding = 0.0;

    foreach ($rows as $r) {
        $final      = (float)$r['FinalPrice'];
        $paid       = (float)$r['AmountPaid'];
        $outstanding = max($final - $paid, 0);

        $totalContracts++;
        $totalValue       += $final;
        $totalPaid        += $paid;
        $totalOutstanding += $outstanding;

        $contracts[] = [
            'Id'          => (int)$r['Id'],
            'CreatedAt'   => $r['CreatedAt'],
            'ClientName'  => $r['ClientName'],
            'AreaName'    => $r['AreaName'],
            'PlotCode'    => $r['PlotCode'],
            'PlanType'    => $r['PlanType'],
            'PlanMonths'  => (int)$r['PlanMonths'],
            'FinalPrice'  => $final,
            'AmountPaid'  => $paid,
            'Outstanding' => $outstanding,
            'Status'      => $r['Status']
        ];
    }

    echo json_encode([
        'summary' => [
            'totalContracts'   => $totalContracts,
            'totalValue'       => $totalValue,
            'totalPaid'        => $totalPaid,
            'totalOutstanding' => $totalOutstanding
        ],
        'contracts' => $contracts
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'error'   => 'Failed to load sales summary',
        'details' => $e->getMessage()
    ]);
}
