<?php
/**
 * locker_summary.php — প্রতি লকারের (investor) সামারি
 * - মোট ক্যাশ/মাল দেওয়া, ফেরত, বর্তমানে আছে
 * - Auto profit/ভাড়া হিসাব (rate × amount × মাস) — locker_pledge_moves থেকে
 * - মোট পেইড — locker_profit_payments থেকে
 * - বাকি আছে
 */

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

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

if (function_exists('session_start_if_not_started')) session_start_if_not_started();
if (function_exists('is_logged_in') && !is_logged_in()) send(false, 'লগইন প্রয়োজন', [], 401);

try {
    // সব লকার (party হিসেবে) — lockers টেবিল থেকে
    $hasPartyId = gs_column_exists($pdo, 'lockers', 'party_id');
    $partyCol = $hasPartyId ? 'COALESCE(party_id, id)' : 'id';

    $lockers = $pdo->query("
        SELECT id AS locker_id, name, phone, status, {$partyCol} AS locker_party_id
        FROM lockers
        ORDER BY status='active' DESC, name ASC
    ")->fetchAll(PDO::FETCH_ASSOC);

    $result = [];

    foreach ($lockers as $lk) {
        $partyId = (int)$lk['locker_party_id'];

        // --- active pledge moves (এখনো লকারে আছে) ---
        $st = $pdo->prepare("
            SELECT id, pledge_id, move_date, locker_amount, customer_rate, locker_rate, profit_rate, status
            FROM locker_pledge_moves
            WHERE locker_party_id = ?
            ORDER BY move_date ASC
        ");
        $st->execute([$partyId]);
        $moves = $st->fetchAll(PDO::FETCH_ASSOC);

        $totalSent      = 0.0; // মোট মাল/টাকা দেওয়া (সব move যোগ)
        $totalReturned  = 0.0; // মোট ফেরত আসা (status='returned' গুলোর amount)
        $currentHolding = 0.0; // বর্তমানে লকারে আছে
        $piecesActive   = 0;
        $piecesReturned = 0;
        $profitDue      = 0.0; // auto-calculated মোট প্রফিট পাওনা

        $today = new DateTime();

        foreach ($moves as $m) {
            $amt = (float)$m['locker_amount'];
            $totalSent += $amt;

            if ($m['status'] === 'returned') {
                $totalReturned += $amt;
                $piecesReturned++;
                continue;
            }

            // active move — এখনো লকারে আছে
            $currentHolding += $amt;
            $piecesActive++;

            // মাস সংখ্যা হিসাব (move_date থেকে আজ পর্যন্ত)
            $moveDate = new DateTime($m['move_date']);
            $diffDays = $today->diff($moveDate)->days;
            $months = $diffDays / 30; // আংশিক মাস হিসাব
            if ($months < 0) $months = 0;

            $rate = (float)$m['profit_rate']; // প্রতি মাসে %
            $profitDue += $amt * ($rate / 100) * $months;
        }

        // --- profit payments (পেইড) ---
        $pp = $pdo->prepare("
            SELECT COALESCE(SUM(amount),0) AS total_paid
            FROM locker_profit_payments
            WHERE locker_party_id = ?
        ");
        $pp->execute([$partyId]);
        $totalPaid = (float)$pp->fetchColumn();

        $balanceDue = $profitDue - $totalPaid;

        $result[] = [
            'locker_id'        => (int)$lk['locker_id'],
            'locker_party_id'  => $partyId,
            'name'             => $lk['name'],
            'phone'            => $lk['phone'],
            'status'           => $lk['status'],
            'total_sent'       => round($totalSent, 2),
            'total_returned'   => round($totalReturned, 2),
            'current_holding'  => round($currentHolding, 2),
            'pieces_active'    => $piecesActive,
            'pieces_returned'  => $piecesReturned,
            'profit_due'       => round($profitDue, 2),
            'profit_paid'      => round($totalPaid, 2),
            'balance_due'      => round($balanceDue, 2),
        ];
    }

    send(true, 'OK', $result);

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