<?php
// --- BẬT HIỂN THỊ LỖI ĐỂ KIỂM TRA ---
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// ------------------------------------
require_once __DIR__ . '/../core/init.php';
require_once __DIR__ . '/../includes/receipt_helpers.php';

header('Content-Type: application/json; charset=utf-8');
if (session_status() == PHP_SESSION_NONE) { session_start(); }

$action = $_REQUEST['action'] ?? '';

function json_error($message) {
    echo json_encode(['status' => 'error', 'message' => $message]);
    exit();
}

function json_success($message, $data = []) {
    $response = ['status' => 'success', 'message' => $message];
    if (!empty($data)) {
        $response['data'] = $data;
    }
    echo json_encode($response);
    exit();
}

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));
}

switch ($action) {
    case 'get_receipts':
        handle_get_receipts($conn);
        break;
    case 'save_receipt':
        handle_save_receipt($conn);
        break;
    case 'get_receipt_details':
        handle_get_receipt_details($conn);
        break;
    case 'delete_receipt':
        handle_delete_receipt($conn);
        break;
    default:
        json_error('Hành động không hợp lệ.');
}

function handle_get_receipts($conn) {
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);
    
    $baseQuery = "FROM cms_receipt r 
                  LEFT JOIN cms_users u ON r.user_init = u.ID 
                  LEFT JOIN cms_stores s ON r.store_id = s.ID";
    $whereClauses = ["r.deleted = 0"];
    $params = [];
    $types = '';

    if (!empty($_POST['search_term'])) {
        $whereClauses[] = "(r.receipt_code LIKE ? OR r.notes LIKE ?)";
        $searchTerm = "%" . $_POST['search_term'] . "%";
        array_push($params, $searchTerm, $searchTerm);
        $types .= 'ss';
    }
    if (!empty($_POST['type_id'])) {
        $whereClauses[] = "r.type_id = ?";
        $params[] = $_POST['type_id'];
        $types .= 'i';
    }
    if (!empty($_POST['start_date'])) {
        $whereClauses[] = "DATE(r.receipt_date) >= ?";
        $params[] = $_POST['start_date'];
        $types .= 's';
    }
    if (!empty($_POST['end_date'])) {
        $whereClauses[] = "DATE(r.receipt_date) <= ?";
        $params[] = $_POST['end_date'];
        $types .= 's';
    }

    $whereSql = " WHERE " . implode(" AND ", $whereClauses);

    $summaryQuery = "SELECT 
                        COUNT(r.id) as total_receipts,
                        SUM(r.total_money) as total_amount,
                        SUM(CASE WHEN DATE(r.receipt_date) = CURDATE() THEN r.total_money ELSE 0 END) as today_amount
                     {$baseQuery} {$whereSql}";
    $stmtSummary = $conn->prepare($summaryQuery);
    if ($stmtSummary) {
        bind_dynamic_params($stmtSummary, $types, $params);
        $stmtSummary->execute();
        $summary_data = $stmtSummary->get_result()->fetch_assoc();
        $stmtSummary->close();
    } else {
        $summary_data = ['total_receipts' => 0, 'total_amount' => 0, 'today_amount' => 0];
    }
    
    $totalRecords = $conn->query("SELECT COUNT(ID) FROM cms_receipt WHERE deleted = 0")->fetch_row()[0] ?? 0;

    $stmtFiltered = $conn->prepare("SELECT COUNT(r.ID) {$baseQuery} {$whereSql}");
    if(!$stmtFiltered) json_error("Lỗi truy vấn đếm dữ liệu: " . $conn->error);
    bind_dynamic_params($stmtFiltered, $types, $params);
    $stmtFiltered->execute();
    $totalFiltered = $stmtFiltered->get_result()->fetch_row()[0];
    $stmtFiltered->close();
    
    $dataQuery = "SELECT r.ID, r.receipt_code, r.receipt_image, s.store_name, r.receipt_date, u.display_name as user_name, r.notes, r.type_id, r.total_money 
                  {$baseQuery} {$whereSql} ORDER BY r.ID DESC LIMIT ?, ?";
    $dataStmt = $conn->prepare($dataQuery);
    if(!$dataStmt) json_error("Lỗi truy vấn lấy dữ liệu: " . $conn->error);
    $data_types = $types . 'ii';
    $data_params = array_merge($params, [$start, $length]);
    bind_dynamic_params($dataStmt, $data_types, $data_params);
    $dataStmt->execute();
    $result = $dataStmt->get_result();
    
    $data = [];
    $receipt_types = get_receipt_types();
    while ($row = $result->fetch_assoc()) {
        $row['type_name'] = $receipt_types[$row['type_id']] ?? 'Không xác định';
        $data[] = $row;
    }
    $dataStmt->close();

    $totalSum = $summary_data['total_amount'] ?? 0;

    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => intval($totalRecords),
        "recordsFiltered" => intval($totalFiltered),
        "data" => $data,
        "totalSum" => $totalSum,
        "summary" => $summary_data
    ]);
}

function handle_save_receipt($conn) {
    $id = intval($_POST['id'] ?? 0);
    $notes = trim($_POST['notes'] ?? '');
    $type_id = intval($_POST['type_id'] ?? 0);
    $total_money = floatval(str_replace('.', '', $_POST['total_money'] ?? '0'));
    $customer_id = intval($_POST['customer_id'] ?? 0);
    $receipt_date = $_POST['receipt_date'] ?? date('Y-m-d H:i:s');
    $user_id = $_SESSION['user_id'] ?? 0;
    $store_id = $_SESSION['store_id'] ?? 1;

    if ($total_money <= 0) json_error('Số tiền thu phải lớn hơn 0.');

    $image_path = $_POST['current_image'] ?? '';
    if (isset($_FILES['receipt_image']) && $_FILES['receipt_image']['error'] == 0) {
        $target_dir = __DIR__ . "/../../uploads/receipts/";
        if (!is_dir($target_dir)) { mkdir($target_dir, 0755, true); }
        $file_name = time() . '_' . basename($_FILES["receipt_image"]["name"]);
        $target_file = $target_dir . $file_name;
        if (move_uploaded_file($_FILES["receipt_image"]["tmp_name"], $target_file)) {
            $image_path = 'uploads/receipts/' . $file_name;
        }
    }

    if ($id > 0) {
        $sql = "UPDATE cms_receipt SET notes=?, type_id=?, total_money=?, receipt_date=?, receipt_image=?, user_upd=?, customer_id=? WHERE ID=?";
        $stmt = $conn->prepare($sql);
        if (!$stmt) json_error('Lỗi chuẩn bị câu lệnh cập nhật: ' . $conn->error);
        $stmt->bind_param('sidssiii', $notes, $type_id, $total_money, $receipt_date, $image_path, $user_id, $customer_id, $id);
    } else {
        $last_id_result = $conn->query("SELECT ID FROM cms_receipt ORDER BY ID DESC LIMIT 1");
        $last_id = $last_id_result ? $last_id_result->fetch_row()[0] : 0;
        $receipt_code = 'PT' . str_pad($last_id + 1, 7, '0', STR_PAD_LEFT);
        
        $sql = "INSERT INTO cms_receipt (receipt_code, notes, type_id, total_money, receipt_date, receipt_image, store_id, user_init, customer_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        if (!$stmt) json_error('Lỗi chuẩn bị câu lệnh thêm mới: ' . $conn->error);
        $stmt->bind_param('ssidsiiii', $receipt_code, $notes, $type_id, $total_money, $receipt_date, $image_path, $store_id, $user_id, $customer_id);
    }

    if ($stmt->execute()) {
        json_success('Lưu phiếu thu thành công!');
    } else {
        json_error('Lỗi khi lưu phiếu thu: ' . $stmt->error);
    }
    $stmt->close();
}

function handle_get_receipt_details($conn) {
    // Thay đổi ở đây: $_REQUEST -> $_POST
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) { json_error('ID phiếu thu không hợp lệ.'); }

    $stmt = $conn->prepare("SELECT r.*, c.customer_name, c.customer_phone 
                             FROM cms_receipt r
                             LEFT JOIN cms_customers c ON r.customer_id = c.ID
                             WHERE r.ID = ?");
    if (!$stmt) {
        json_error('Lỗi chuẩn bị câu lệnh lấy chi tiết phiếu thu: ' . $conn->error);
    }
    
    $stmt->bind_param('i', $id);
    if (!$stmt->execute()) {
        json_error('Lỗi thực thi câu lệnh lấy chi tiết: ' . $stmt->error);
    }
    
    $result = $stmt->get_result();
    $data = $result->fetch_assoc();
    $stmt->close();

    if ($data) {
        json_success('Lấy chi tiết thành công.', $data);
    } else {
        json_error('Không tìm thấy phiếu thu với ID đã cho.');
    }
}

function handle_delete_receipt($conn) {
    $id = intval($_POST['id'] ?? 0);
    if ($id <= 0) { json_error('ID không hợp lệ.'); }

    $stmt = $conn->prepare("UPDATE cms_receipt SET deleted = 1 WHERE ID = ?");
    if (!$stmt) {
        json_error('Lỗi chuẩn bị câu lệnh xóa: ' . $conn->error);
    }

    $stmt->bind_param('i', $id);
    if ($stmt->execute()) {
        json_success('Xóa phiếu thu thành công!');
    } else {
        json_error('Lỗi khi xóa phiếu thu: ' . $stmt->error);
    }
    $stmt->close();
}

$conn->close();
?>