<?php
/**
 * GET /api/financial/ledger_summary.php
 * Admin only - ledger balance + account breakdown
 */
require_once __DIR__ . '/../../config.php';
require_once __DIR__ . '/../../engine/Kernel.php';
Kernel::handle(['auth' => 'admin', 'public' => false]);
require_once __DIR__ . '/../../engine/Logger.php';
require_once __DIR__ . '/../../engine/FinancialAgent.php';

// session_start() removed — Kernel::handle manages sessions

if (empty($_SESSION['admin'])) { http_response_code(401); die(json_encode(['error'=>'unauthorized'])); }

try {
    $balance  = FinancialAgent::verifyLedger();
    $wallets  = FinancialAgent::verifyWallets();
    $invoices = FinancialAgent::verifyInvoices();

    // Account breakdown
    $accounts = db()->query(
        "SELECT a.code, a.name, a.type,
                COALESCE(SUM(l.debit),0)  AS total_debit,
                COALESCE(SUM(l.credit),0) AS total_credit,
                COALESCE(SUM(l.credit-l.debit),0) AS net
         FROM accounts a
         LEFT JOIN ledger l ON l.account_id = a.id
         GROUP BY a.id ORDER BY a.code"
    )->fetchAll(PDO::FETCH_ASSOC);

    // Recent entries
    $recent = db()->query(
        "SELECT l.*, a.code, a.name as account_name
         FROM ledger l JOIN accounts a ON a.id=l.account_id
         ORDER BY l.id DESC LIMIT 20"
    )->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(compact('balance','wallets','invoices','accounts','recent'), JSON_UNESCAPED_UNICODE);
} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['error' => 'server_error', 'message' => 'خطأ مؤقت — حاول مرة أخرى'], JSON_UNESCAPED_UNICODE);
}
