<?php
require_once '../../config/db.php';
require_once '../../config/session.php';
require_once '../../config/response.php';

session_start_if_not_started();

if (!is_logged_in()) {
    send_response(401, false, 'অনুমতি নেই');
}

$cash_account_id = $_GET['cash_account_id'] ?? null;
$from_date       = $_GET['from_date'] ?? date('Y-m-d');
$to_date         = $_GET['to_date'] ?? date('Y-m-d');
$limit           = (int)($_GET['limit'] ?? 50);

if ($limit <= 0)   $limit = 50;
if ($limit > 200)  $limit = 200;

try {
    $where  = "WHERE ct.deleted_at IS NULL
               AND ct.transaction_date BETWEEN ? AND ?";
    $params = [$from_date, $to_date];

    if (!empty($cash_account_id)) {
        $where .= " AND ct.cash_account_id = ?";
        $params[] = $cash_account_id;
    }

    // ✅ FIXED: ct.note → ct.description AS note
    $sql = "
        SELECT
            ct.id,
            ct.transaction_date,
            ct.transaction_type,
            ct.amount,
            ct.description  AS note,
            ct.reference_type,
            ct.reference_id,
            ct.is_reversal,
            ct.created_at,
            ca.account_name,
            ctt.type_name
        FROM cash_transactions ct
        JOIN cash_accounts ca
            ON ct.cash_account_id = ca.id
        LEFT JOIN cash_transaction_types ctt
            ON ct.transaction_type_id = ctt.id
        $where
        ORDER BY ct.id DESC
        LIMIT $limit
    ";

    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $transactions = $stmt->fetchAll(PDO::FETCH_ASSOC);

    $total_in  = 0;
    $total_out = 0;

    foreach ($transactions as &$t) {
        $amount = (float)($t['amount'] ?? 0);
        $type   = strtoupper((string)($t['transaction_type'] ?? ''));

        if ($amount < 0) {
            $direction      = 'OUT';
            $display_amount = abs($amount);
        } else {
            if (in_array($type, ['OUT', 'EXPENSE', 'DEBIT', 'CASH_OUT', 'WITHDRAW'], true)) {
                $direction      = 'OUT';
                $display_amount = abs($amount);
            } else {
                $direction      = 'IN';
                $display_amount = abs($amount);
            }
        }

        $t['direction']      = $direction;
        $t['display_amount'] = round($display_amount, 2);

        if ($direction === 'IN') {
            $total_in  += $display_amount;
        } else {
            $total_out += $display_amount;
        }
    }
    unset($t);

    send_response(200, true, 'সফল', [
        'transactions' => $transactions,
        'total_in'     => round($total_in, 2),
        'total_out'    => round($total_out, 2),
        'balance'      => round($total_in - $total_out, 2)
    ]);

} catch (Exception $e) {
    send_response(500, false, 'সার্ভার সমস্যা: ' . $e->getMessage());
}
?>
