<?php
/**
 * File: api/cash/dashboard_summary.php
 * v2 (2026-06-05): PDO-তে রূপান্তর + সঠিক হিসাব
 *
 * হিসাব:
 *   total_cash_balance = SUM(current_balance) FROM cash_accounts
 *   today_income       = SUM(amount) WHERE direction='IN' AND DATE=today
 *   today_expense      = SUM(amount) WHERE direction='OUT' AND DATE=today
 */

ini_set('display_errors', 0);
error_reporting(E_ALL);
date_default_timezone_set('Asia/Dhaka');

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 (function_exists('is_logged_in') && !is_logged_in()) {
    http_response_code(401);
    echo json_encode(["ok" => false, "message" => "লগইন প্রয়োজন"], JSON_UNESCAPED_UNICODE);
    exit;
}

$today = trim((string)($_GET['date'] ?? date("Y-m-d")));
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $today)) {
    $today = date("Y-m-d");
}

try {

    // ── 1) মোট ক্যাশ ব্যালেন্স ──
    $totalCashBalance = (float)$pdo
        ->query("SELECT COALESCE(SUM(current_balance),0) FROM cash_accounts WHERE is_active = 1")
        ->fetchColumn();

    // ── 2) আজকের আয় (direction = IN) ──
    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(amount), 0)
        FROM cash_transactions
        WHERE direction   = 'IN'
          AND is_deleted  = 0
          AND is_reversed = 0
          AND DATE(transaction_date) = ?
    ");
    $stmt->execute([$today]);
    $todayIncome = (float)$stmt->fetchColumn();

    // ── 3) আজকের ব্যয় (direction = OUT) ──
    $stmt = $pdo->prepare("
        SELECT COALESCE(SUM(amount), 0)
        FROM cash_transactions
        WHERE direction   = 'OUT'
          AND is_deleted  = 0
          AND is_reversed = 0
          AND DATE(transaction_date) = ?
    ");
    $stmt->execute([$today]);
    $todayExpense = (float)$stmt->fetchColumn();

    $netToday = $todayIncome - $todayExpense;

    echo json_encode([
        "ok"                  => true,
        "success"             => true,
        "status"              => true,
        "date"                => $today,
        "total_cash_balance"  => round($totalCashBalance, 2),
        "today_income"        => round($todayIncome, 2),
        "today_expense"       => round($todayExpense, 2),
        "net_today"           => round($netToday, 2)
    ], JSON_UNESCAPED_UNICODE);

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