<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/../config/database.php';

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

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

switch ($action) {
    case 'get_report_data':
        handle_get_report_data($conn);
        break;
    case 'get_stores':
        handle_get_stores($conn);
        break;
    case 'get_customers':
        handle_get_customers($conn);
        break;
    default:
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

function handle_get_stores($conn) {
    $term = $_GET['term'] ?? '';
    $sql = "SELECT id, store_name as text FROM cms_stores WHERE store_name LIKE ? LIMIT 20";
    $stmt = $conn->prepare($sql);
    $searchTerm = "%{$term}%";
    $stmt->bind_param("s", $searchTerm);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result);
}

function handle_get_customers($conn) {
    $term = $_GET['term'] ?? '';
    $sql = "SELECT id, customer_name as text FROM cms_customers WHERE customer_name LIKE ? OR customer_phone LIKE ? LIMIT 20";
    $stmt = $conn->prepare($sql);
    $searchTerm = "%{$term}%";
    $stmt->bind_param("ss", $searchTerm, $searchTerm);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode($result);
}

function handle_get_report_data($conn) {
    $params = [];
    $types = "";
    $where_conditions = ["o.deleted = 0", "o.order_status = 1"];

    if (!empty($_REQUEST['from'])) { $where_conditions[] = "o.sell_date >= ?"; $params[] = "{$_REQUEST['from']} 00:00:00"; $types .= "s"; }
    if (!empty($_REQUEST['to'])) { $where_conditions[] = "o.sell_date <= ?"; $params[] = "{$_REQUEST['to']} 23:59:59"; $types .= "s"; }
    if (!empty($_REQUEST['store_id'])) { $where_conditions[] = "o.store_id = ?"; $params[] = intval($_REQUEST['store_id']); $types .= "i"; }
    if (!empty($_REQUEST['customer_id'])) { $where_conditions[] = "o.customer_id = ?"; $params[] = intval($_REQUEST['customer_id']); $types .= "i"; }

    $where_sql = " WHERE " . implode(" AND ", $where_conditions);
    $base_sql = "FROM cms_orders o 
                 LEFT JOIN cms_customers c ON o.customer_id = c.ID 
                 LEFT JOIN cms_stores s ON o.store_id = s.id";

    if (isset($_REQUEST['export']) && $_REQUEST['export'] === 'excel') {
        export_to_excel($conn, $base_sql . $where_sql, $params, $types);
        return;
    }

    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);

    $stmt_summary = $conn->prepare("SELECT 
        COUNT(o.id) as total_orders, 
        SUM(o.total_quantity) as total_quantity, 
        SUM(o.total_money) as total_revenue, 
        SUM(o.total_money - o.total_origin_price) as total_profit 
        " . $base_sql . $where_sql);
    if (!empty($types)) { $stmt_summary->bind_param($types, ...$params); }
    $stmt_summary->execute();
    $summary_row = $stmt_summary->get_result()->fetch_assoc();
    $stmt_summary->close();
    $recordsFiltered = intval($summary_row['total_orders'] ?? 0);
    $recordsTotal = $conn->query("SELECT COUNT(ID) FROM cms_orders WHERE deleted = 0 AND order_status = 1")->fetch_row()[0] ?? 0;

    $sql_data = "SELECT o.ID, o.output_code, o.sell_date, o.total_quantity, o.total_money, o.total_origin_price, 
                 (o.total_money - o.total_origin_price) as profit,
                 COALESCE(c.customer_name, 'Khách lẻ') as customer_name, s.store_name 
                 " . $base_sql . $where_sql . " ORDER BY o.sell_date DESC LIMIT ?, ?";
    
    $data_params = $params;
    $data_params[] = $start;
    $data_params[] = $length;
    $data_types = $types . 'ii';
    
    $stmt_data = $conn->prepare($sql_data);
    $stmt_data->bind_param($data_types, ...$data_params);
    $stmt_data->execute();
    $result = $stmt_data->get_result();
    $data_rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
    $stmt_data->close();
    
    $data = [];
    $stt = $start + 1;
    foreach ($data_rows as $row) {
        $row['stt'] = $stt++;
        $row['sell_date'] = date('d/m/Y H:i', strtotime($row['sell_date']));
        $data[] = $row;
    }
    
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => $recordsTotal,
        "recordsFiltered" => $recordsFiltered,
        "data" => $data,
        "summary" => $summary_row
    ], JSON_NUMERIC_CHECK);
}

function export_to_excel($conn, $sql_with_where, $params, $types) {
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename=BaoCaoXuatDonHang_' . date('Ymd') . '.csv');
    
    $output = fopen('php://output', 'w');
    
    // Thêm UTF-8 BOM để Excel đọc tiếng Việt có dấu đúng
    fwrite($output, "\xEF\xBB\xBF");
    
    fputcsv($output, [
        'STT', 'Mã ĐH', 'Ngày bán', 'Khách hàng', 'Kho', 
        'Số lượng', 'Doanh thu', 'Vốn', 'Lợi nhuận'
    ]);
    
    $sql = "SELECT o.ID, o.output_code, o.sell_date, o.total_quantity, o.total_money, o.total_origin_price, 
            (o.total_money - o.total_origin_price) as profit,
            COALESCE(c.customer_name, 'Khách lẻ') as customer_name, s.store_name " . $sql_with_where . " ORDER BY o.sell_date DESC";
            
    $stmt = $conn->prepare($sql);
    if (!empty($types)) { $stmt->bind_param($types, ...$params); }
    $stmt->execute();
    $result = $stmt->get_result();
    
    $stt = 1;
    while ($row = $result->fetch_assoc()) {
        fputcsv($output, [
            $stt++,
            $row['output_code'],
            date('d/m/Y H:i', strtotime($row['sell_date'])),
            $row['customer_name'],
            $row['store_name'],
            $row['total_quantity'],
            $row['total_money'],
            $row['total_origin_price'],
            $row['profit']
        ]);
    }
    
    fclose($output);
    exit();
}