<?php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/../../config/db.php';

function out($ok,$msg='',$data=[],$code=200){
    http_response_code($code);
    echo json_encode(['success'=>$ok,'message'=>$msg,'data'=>$data],JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    $from = trim($_GET['from_date'] ?? date('Y-m-01'));
    $to   = trim($_GET['to_date']   ?? date('Y-m-d'));

    // ── সামারি ──
    $sum = $pdo->prepare("
        SELECT
            COUNT(*) AS total,
            SUM(CASE WHEN status!='CLOSED' AND holding_status!='LOCKER' THEN 1 ELSE 0 END) AS open_count,
            SUM(CASE WHEN status!='CLOSED' AND holding_status='LOCKER'  THEN 1 ELSE 0 END) AS locker_count,
            SUM(CASE WHEN status='CLOSED' THEN 1 ELSE 0 END) AS closed_count,
            SUM(loan_amount) AS total_loan,
            SUM(outstanding_principal) AS total_outstanding,
            SUM(gold_value) AS total_gold_value
        FROM pawn_pledges
        WHERE pledge_date BETWEEN ? AND ?
    ");
    $sum->execute([$from, $to]);
    $summary = $sum->fetch(PDO::FETCH_ASSOC);

    // ── পেমেন্ট সামারি ──
    $pay = $pdo->prepare("
        SELECT
            COUNT(*) AS payment_count,
            SUM(COALESCE(amount,0)) AS total_received,
            SUM(COALESCE(principal_paid,0)) AS total_principal,
            SUM(COALESCE(interest_paid,0)) AS total_interest
        FROM pawn_payments pp
        INNER JOIN pawn_pledges pl ON pl.id = pp.pledge_id
        WHERE pp.payment_date BETWEEN ? AND ?
    ");
    $pay->execute([$from, $to]);
    $payments = $pay->fetch(PDO::FETCH_ASSOC);

    // ── মাসওয়ারি ব্রেকডাউন ──
    $monthly = $pdo->prepare("
        SELECT
            DATE_FORMAT(pledge_date,'%Y-%m') AS month,
            COUNT(*) AS count,
            SUM(loan_amount) AS loan,
            SUM(gold_value) AS gold_value,
            SUM(outstanding_principal) AS outstanding
        FROM pawn_pledges
        WHERE pledge_date BETWEEN ? AND ?
        GROUP BY DATE_FORMAT(pledge_date,'%Y-%m')
        ORDER BY month ASC
    ");
    $monthly->execute([$from, $to]);
    $monthly_data = $monthly->fetchAll(PDO::FETCH_ASSOC);

    // ── শীর্ষ গ্রাহক ──
    $top = $pdo->prepare("
        SELECT
            pa.name AS party_name,
            pa.phone AS party_phone,
            COUNT(pl.id) AS pledge_count,
            SUM(pl.loan_amount) AS total_loan,
            SUM(pl.outstanding_principal) AS total_outstanding
        FROM pawn_pledges pl
        LEFT JOIN parties pa ON pa.id = pl.party_id
        WHERE pl.pledge_date BETWEEN ? AND ?
        GROUP BY pl.party_id
        ORDER BY total_loan DESC
        LIMIT 10
    ");
    $top->execute([$from, $to]);
    $top_customers = $top->fetchAll(PDO::FETCH_ASSOC);

    out(true,'OK',[
        'from_date'     => $from,
        'to_date'       => $to,
        'summary'       => $summary,
        'payments'      => $payments,
        'monthly'       => $monthly_data,
        'top_customers' => $top_customers
    ]);

} catch(Throwable $e){
    out(false,'Server error: '.$e->getMessage(),[],500);
}
?>