<?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_suppliers':
        handle_get_suppliers($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_suppliers($conn) {
    $term = $_GET['term'] ?? '';
    $sql = "SELECT id, supplier_name as text FROM cms_suppliers WHERE supplier_name LIKE ? OR supplier_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 = ["i.deleted = 0"];

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

    $where_sql = " WHERE " . implode(" AND ", $where_conditions);
    $base_sql = "FROM cms_input i 
                 LEFT JOIN cms_suppliers sup ON i.supplier_id = sup.ID 
                 LEFT JOIN cms_stores s ON i.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(i.id) as total_slips, SUM(i.total_quantity) as total_quantity, SUM(i.total_money) as total_amount, SUM(i.lack) as total_debt " . $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_slips'] ?? 0);
    $recordsTotal = $conn->query("SELECT COUNT(ID) FROM cms_input WHERE deleted = 0")->fetch_row()[0] ?? 0;

    $sql_data = "SELECT i.id, i.input_code, i.input_date, i.total_quantity, i.total_money, i.payed, i.lack,
                 COALESCE(sup.supplier_name, 'Không có NCC') as supplier_name, s.store_name 
                 " . $base_sql . $where_sql . " ORDER BY i.input_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['input_date'] = date('d/m/Y H:i', strtotime($row['input_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=BaoCaoNhapKho_' . date('Ymd') . '.csv');
    
    $output = fopen('php://output', 'w');
    fwrite($output, "\xEF\xBB\xBF");
    
    fputcsv($output, ['STT', 'Mã PN', 'Ngày nhập', 'Nhà cung cấp', 'Kho', 'Số lượng', 'Tổng tiền', 'Đã trả', 'Còn nợ']);
    
    $sql = "SELECT i.id, i.input_code, i.input_date, i.total_quantity, i.total_money, i.payed, i.lack,
            COALESCE(sup.supplier_name, 'Không có NCC') as supplier_name, s.store_name " . $sql_with_where . " ORDER BY i.input_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['input_code'], date('d/m/Y H:i', strtotime($row['input_date'])),
            $row['supplier_name'], $row['store_name'], $row['total_quantity'],
            $row['total_money'], $row['payed'], $row['lack']
        ]);
    }
    
    fclose($output);
    exit();
}