<?php
// File 6/6
// Path: api/pawn/active_summary.php
// Table: pawn_pledges
// column: status='OPEN', loan_amount, outstanding_principal

header('Content-Type: application/json');
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../auth/check_session.php';

try {
    $stmt = $pdo->query("
        SELECT
            COUNT(*)                                 AS active_count,
            COALESCE(SUM(loan_amount), 0)            AS total_amount,
            COALESCE(SUM(outstanding_principal), 0)  AS total_outstanding
        FROM pawn_pledges
        WHERE status = 'OPEN'
    ");
    $row = $stmt->fetch();

    echo json_encode([
        'ok'   => true,
        'data' => [
            'active_count'      => (int)   $row['active_count'],
            'total_amount'      => (float) $row['total_amount'],
            'total_outstanding' => (float) $row['total_outstanding'],
        ]
    ]);

} catch (PDOException $e) {
    // table সমস্যা হলেও dashboard ভাঙবে না
    echo json_encode([
        'ok'   => true,
        'data' => [
            'active_count'      => 0,
            'total_amount'      => 0,
            'total_outstanding' => 0,
        ]
    ]);
}
