<?php
// File: /public_html/erp.jewellersbd.com/api/cash/cash_dashboard_data.php
// Cash Module 2.0 — Dashboard data (direction-based schema)
// Uses $pdo (from config/db.php). NEW FILE — overwrites nothing.

header("Content-Type: application/json; charset=UTF-8");

require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (
    (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) &&
    (!function_exists('is_logged_in') || !is_logged_in())
) {
    echo json_encode(["success" => false, "message" => "লগইন প্রয়োজন", "data" => null], JSON_UNESCAPED_UNICODE);
    exit;
}

try {
    // ---- Accounts + total balance ----
    $accStmt = $pdo->query("
        SELECT id, account_name, account_name_bn, account_type, current_balance
        FROM cash_accounts
        WHERE is_active = 1 AND deleted_at IS NULL
        ORDER BY sort_order ASC, id ASC
    ");
    $accountsRaw = $accStmt->fetchAll();

    $accounts = [];
    $total_balance = 0.0;
    foreach ($accountsRaw as $a) {
        $bal = round((float)$a['current_balance'], 2);
        $name = (!empty($a['account_name_bn'])) ? $a['account_name_bn'] : $a['account_name'];
        $accounts[] = [
            "id"              => (int)$a['id'],
            "account_name"    => (string)$name,
            "account_type"    => (string)$a['account_type'],
            "current_balance" => $bal
        ];
        $total_balance += $bal;
    }

    // ---- helper: IN/OUT/net for a date condition ----
    $sumFor = function (string $where, array $params) use ($pdo) {
        $sql = "SELECT
                    COALESCE(SUM(CASE WHEN direction='IN'  THEN amount ELSE 0 END),0) AS total_in,
                    COALESCE(SUM(CASE WHEN direction='OUT' THEN amount ELSE 0 END),0) AS total_out
                FROM cash_transactions
                WHERE is_deleted = 0 AND is_reversed = 0 AND $where";
        $st = $pdo->prepare($sql);
        $st->execute($params);
        $r = $st->fetch() ?: ['total_in' => 0, 'total_out' => 0];
        $in  = round((float)$r['total_in'], 2);
        $out = round((float)$r['total_out'], 2);
        return ["in" => $in, "out" => $out, "net" => round($in - $out, 2)];
    };

    $today = $sumFor("transaction_date = CURDATE()", []);
    $month = $sumFor("YEAR(transaction_date) = YEAR(CURDATE()) AND MONTH(transaction_date) = MONTH(CURDATE())", []);

    // ---- recent transactions ----
    $recStmt = $pdo->query("
        SELECT ct.id, ct.voucher_no, ct.transaction_date, ct.direction, ct.amount, ct.note,
               cc.category_name, cc.category_name_bn, cc.icon,
               ca.account_name, ca.account_name_bn
        FROM cash_transactions ct
        LEFT JOIN cash_categories cc ON cc.id = ct.category_id
        LEFT JOIN cash_accounts   ca ON ca.id = ct.cash_account_id
        WHERE ct.is_deleted = 0
        ORDER BY ct.id DESC
        LIMIT 15
    ");
    $recentRaw = $recStmt->fetchAll();

    $recent = [];
    foreach ($recentRaw as $r) {
        $catName = (!empty($r['category_name_bn'])) ? $r['category_name_bn'] : ($r['category_name'] ?? '—');
        $accName = (!empty($r['account_name_bn'])) ? $r['account_name_bn'] : ($r['account_name'] ?? '—');
        $recent[] = [
            "id"         => (int)$r['id'],
            "voucher_no" => (string)($r['voucher_no'] ?? ''),
            "date"       => (string)$r['transaction_date'],
            "direction"  => (string)$r['direction'],
            "amount"     => round((float)$r['amount'], 2),
            "category"   => (string)$catName,
            "icon"       => (string)($r['icon'] ?? ''),
            "account"    => (string)$accName,
            "note"       => (string)($r['note'] ?? '')
        ];
    }

    echo json_encode([
        "success" => true,
        "message" => "ড্যাশবোর্ড লোড হয়েছে",
        "data"    => [
            "total_balance" => round($total_balance, 2),
            "accounts"      => $accounts,
            "today"         => $today,
            "month"         => $month,
            "recent"        => $recent
        ]
    ], JSON_UNESCAPED_UNICODE);

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(["success" => false, "message" => "সার্ভার সমস্যা: " . $e->getMessage(), "data" => null], JSON_UNESCAPED_UNICODE);
}

exit;
?>