<?php
// DEBUG (optional - tone down in production)
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: *");

// Same config/connection as sync.php
require_once __DIR__ . '/../../config.php';

try {
    // Total revenue = sum of FinalPrice from contracts
    $stmt = $pdo->query("SELECT IFNULL(SUM(FinalPrice), 0) AS TotalRevenue FROM ClientContracts");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalRevenue = (float)$row['TotalRevenue'];

    // Active plots = count of Plots
    $stmt = $pdo->query("SELECT COUNT(*) AS ActivePlots FROM Plots");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $activePlots = (int)$row['ActivePlots'];

    // Total clients
    $stmt = $pdo->query("SELECT COUNT(*) AS TotalClients FROM Clients");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $totalClients = (int)$row['TotalClients'];

    // Outstanding balance = sum(FinalPrice) - sum(Payments.Amount)
    $stmt = $pdo->query("
        SELECT
            IFNULL((SELECT SUM(FinalPrice) FROM ClientContracts), 0)
            -
            IFNULL((SELECT SUM(Amount) FROM ClientPayments WHERE IsDeleted = 0), 0)
            AS OutstandingBalance
    ");
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $outstandingBalance = (float)$row['OutstandingBalance'];

    echo json_encode([
        "status" => "ok",
        "totalRevenue" => $totalRevenue,
        "activePlots" => $activePlots,
        "totalClients" => $totalClients,
        "outstandingBalance" => $outstandingBalance
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        "status" => "error",
        "message" => "Dashboard query failed",
        "details" => $e->getMessage()
    ]);
}
