<?php
require_once __DIR__ . '/../core/init.php';
header('Content-Type: application/json; charset=utf-8');

// Hàm trợ giúp để bind_param động
function bind_dynamic_params($stmt, $types, &$params) {
    if (empty($types) || empty($params)) return;
    $refs = [];
    foreach ($params as $key => $value) {
        $refs[$key] = &$params[$key];
    }
    call_user_func_array([$stmt, 'bind_param'], array_merge([$types], $refs));
}

// Hàm để dừng và báo lỗi SQL cụ thể
function terminate_with_sql_error($conn, $context) {
    die(json_encode([
        'error' => "SQL Prepare Error ({$context}): " . $conn->error,
        'data' => [], 'draw' => intval($_POST['draw'] ?? 0),
        'recordsTotal' => 0, 'recordsFiltered' => 0
    ]));
}

$draw = intval($_POST['draw'] ?? 0);
$start_row = intval($_POST['start'] ?? 0);
$length = intval($_POST['length'] ?? 25);
$user_id = intval($_POST['user_id'] ?? 0);
$store_id = intval($_POST['store_id'] ?? 0);
$start_date = $_POST['start_date'] ?? date('Y-m-01');
$end_date = $_POST['end_date'] ?? date('Y-m-d');

// --- 1. TÍNH TỒN ĐẦU KỲ ---
$opening_balance = 0;
$params_before = [$start_date . ' 00:00:00'];
$types_before = 's';
$store_filter_sql = '';
if ($store_id > 0) {
    $store_filter_sql = ' AND store_id = ?';
    $params_before[] = $store_id;
    $types_before .= 'i';
}

$sql_receipt_before = "SELECT SUM(total_money) FROM cms_receipt WHERE deleted = 0 AND receipt_date < ? " . $store_filter_sql;
$stmt_r = $conn->prepare($sql_receipt_before);
if ($stmt_r === false) { terminate_with_sql_error($conn, "Opening Receipts"); }
bind_dynamic_params($stmt_r, $types_before, $params_before);
$stmt_r->execute();
$receipt_total_before = $stmt_r->get_result()->fetch_row()[0] ?? 0;
$stmt_r->close();

$sql_payment_before = "SELECT SUM(total_money) FROM cms_payment WHERE deleted = 0 AND payment_date < ? " . $store_filter_sql;
$stmt_p = $conn->prepare($sql_payment_before);
if ($stmt_p === false) { terminate_with_sql_error($conn, "Opening Payments"); }
bind_dynamic_params($stmt_p, $types_before, $params_before);
$stmt_p->execute();
$payment_total_before = $stmt_p->get_result()->fetch_row()[0] ?? 0;
$stmt_p->close();

$opening_balance = $receipt_total_before - $payment_total_before;

// --- 2. XÂY DỰNG BỘ LỌC CHO GIAO DỊCH TRONG KỲ ---
$whereClauses = [];
$params_in_period = [];
$types_in_period = '';

if ($user_id > 0) { $whereClauses[] = "user_init = ?"; $params_in_period[] = $user_id; $types_in_period .= 'i'; }
if ($store_id > 0) { $whereClauses[] = "store_id = ?"; $params_in_period[] = $store_id; $types_in_period .= 'i'; }
if ($start_date) { $whereClauses[] = "transaction_date >= ?"; $params_in_period[] = $start_date . ' 00:00:00'; $types_in_period .= 's'; }
if ($end_date) { $whereClauses[] = "transaction_date <= ?"; $params_in_period[] = $end_date . ' 23:59:59'; $types_in_period .= 's'; }

// --- 3. LẤY PHIẾU THU VÀ PHIẾU CHI RIÊNG BIỆT ---
$transactions = [];
$whereSqlReceipt = str_replace('transaction_date', 'receipt_date', implode(' AND ', $whereClauses));
$whereSqlPayment = str_replace('transaction_date', 'payment_date', implode(' AND ', $whereClauses));

// Lấy phiếu thu
$sql_receipts = "SELECT r.ID, 'receipt' as type, r.receipt_code as code, r.receipt_date as transaction_date, r.notes, r.user_init, r.store_id, r.total_money as thu, 0 as chi, u.display_name 
                 FROM cms_receipt r LEFT JOIN cms_users u ON r.user_init = u.ID
                 WHERE r.deleted = 0 " . (!empty($whereSqlReceipt) ? "AND {$whereSqlReceipt}" : "");
$stmt_receipts = $conn->prepare($sql_receipts);
if ($stmt_receipts === false) { terminate_with_sql_error($conn, "Get Receipts"); }
bind_dynamic_params($stmt_receipts, $types_in_period, $params_in_period);
$stmt_receipts->execute();
$receipts_result = $stmt_receipts->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_receipts->close();
$transactions = array_merge($transactions, $receipts_result);

// Lấy phiếu chi
$sql_payments = "SELECT p.ID, 'payment' as type, p.payment_code as code, p.payment_date as transaction_date, p.notes, p.user_init, p.store_id, 0 as thu, p.total_money as chi, u.display_name 
                 FROM cms_payment p LEFT JOIN cms_users u ON p.user_init = u.ID
                 WHERE p.deleted = 0 " . (!empty($whereSqlPayment) ? "AND {$whereSqlPayment}" : "");
$stmt_payments = $conn->prepare($sql_payments);
if ($stmt_payments === false) { terminate_with_sql_error($conn, "Get Payments"); }
bind_dynamic_params($stmt_payments, $types_in_period, $params_in_period);
$stmt_payments->execute();
$payments_result = $stmt_payments->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_payments->close();
$transactions = array_merge($transactions, $payments_result);

// --- 4. XỬ LÝ DỮ LIỆU BẰNG PHP ---
// Sắp xếp lại mảng theo ngày
usort($transactions, function($a, $b) {
    return strtotime($a['transaction_date']) - strtotime($b['transaction_date']);
});

$recordsFiltered = count($transactions);
$totalRecords = $conn->query("SELECT (SELECT COUNT(*) FROM cms_receipt WHERE deleted = 0) + (SELECT COUNT(*) FROM cms_payment WHERE deleted = 0)")->fetch_row()[0];

// Tính toán tóm tắt
$total_thu = array_sum(array_column($transactions, 'thu'));
$total_chi = array_sum(array_column($transactions, 'chi'));
$closing_balance = $opening_balance + $total_thu - $total_chi;

// Phân trang
$data_for_page = array_slice($transactions, $start_row, $length);

// Tính số tồn liên tục cho trang hiện tại
$running_balance = $opening_balance;
// Để tính tồn đúng cho trang 2, 3... ta phải tính tổng thu chi của các trang trước đó
$offset_thu = array_sum(array_column(array_slice($transactions, 0, $start_row), 'thu'));
$offset_chi = array_sum(array_column(array_slice($transactions, 0, $start_row), 'chi'));
$running_balance += $offset_thu - $offset_chi;

$data = [];
foreach($data_for_page as $row) {
    $running_balance += $row['thu'] - $row['chi'];
    $row['ton'] = $running_balance;
    $data[] = $row;
}

// --- 5. TRẢ VỀ JSON ---
echo json_encode([
    "draw" => $draw,
    "recordsTotal" => intval($totalRecords),
    "recordsFiltered" => intval($recordsFiltered),
    "data" => $data,
    "summary" => [
        "openingBalance" => $opening_balance,
        "totalThu" => $total_thu,
        "totalChi" => $total_chi,
        "closingBalance" => $closing_balance,
        "totalVouchers" => $recordsFiltered
    ]
]);
?>