<?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 {
    $today = date('Y-m-d');

    // লকারে আছে এমন সব বন্ধক
    $st = $pdo->prepare("
        SELECT
            p.id, p.pledge_code, p.pledge_date, p.loan_amount,
            p.outstanding_principal, p.interest_rate, p.gold_value,
            p.note, p.manual_barcode,
            COALESCE(pa.name,'') AS party_name,
            COALESCE(pa.phone,'') AS party_phone,
            COALESCE(
                (SELECT MAX(ct.transaction_date)
                 FROM cash_transactions ct
                 WHERE ct.reference_id = p.id
                 AND ct.reference_type = 'LOCKER_MOVE'),
                p.pledge_date
            ) AS locker_since
        FROM pawn_pledges p
        LEFT JOIN parties pa ON pa.id = p.party_id
        WHERE p.status != 'CLOSED'
        AND p.holding_status = 'LOCKER'
        ORDER BY p.id ASC
    ");
    $st->execute();
    $pledges = $st->fetchAll(PDO::FETCH_ASSOC);

    $total_monthly_rent  = 0;
    $total_due_rent      = 0;
    $total_outstanding   = 0;

    foreach($pledges as &$row){
        $rate        = (float)($row['interest_rate'] ?? 0);
        $loan        = (float)($row['loan_amount'] ?? 0);
        $outstanding = (float)($row['outstanding_principal'] ?? 0);
        $locker_since= $row['locker_since'] ?? $row['pledge_date'];

        // মাস হিসাব — ১ দিন = ১ মাস
        $d1 = new DateTime($locker_since);
        $d2 = new DateTime($today);

        $year_diff  = (int)$d2->format('Y') - (int)$d1->format('Y');
        $month_diff = (int)$d2->format('m') - (int)$d1->format('m');
        $total_months = $year_diff * 12 + $month_diff;

        // একই মাসে হলেও ১ মাস, আর দিন বাকি থাকলে +১
        if($total_months <= 0) $total_months = 1;
        else {
            $day1 = (int)$d1->format('d');
            $day2 = (int)$d2->format('d');
            if($day2 >= $day1) $total_months += 1;
            else $total_months += 1; // যেকোনো দিন = পূর্ণ মাস
        }

        // মাসিক ভাড়া
        $monthly_rent = round($outstanding * $rate / 100, 2);
        // মোট বকেয়া ভাড়া
        $due_rent = round($monthly_rent * $total_months, 2);

        $row['locker_since']   = $locker_since;
        $row['total_months']   = $total_months;
        $row['monthly_rent']   = $monthly_rent;
        $row['due_rent']       = $due_rent;
        $row['outstanding']    = $outstanding;

        $total_monthly_rent  += $monthly_rent;
        $total_due_rent      += $due_rent;
        $total_outstanding   += $outstanding;
    }
    unset($row);

    out(true,'OK',[
        'today'              => $today,
        'pledges'            => $pledges,
        'total_count'        => count($pledges),
        'total_monthly_rent' => round($total_monthly_rent,2),
        'total_due_rent'     => round($total_due_rent,2),
        'total_outstanding'  => round($total_outstanding,2),
    ]);

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