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

require_once __DIR__ . '/../config/database.php';
header('Content-Type: application/json; charset=utf-8');

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

$user_id = $_SESSION['user_id'] ?? 0;
$group_id = $_SESSION['group_id'] ?? 0;
$action = $_REQUEST['action'] ?? '';

switch ($action) {
    case 'get_orders_list':
        handle_get_orders_list($conn, $user_id, $group_id);
        break;
    case 'delete_order':
        handle_delete_order($conn, $user_id);
        break;
    case 'get_order_details':
        handle_get_order_details($conn);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}

function revert_stock_from_order($conn, $order_id)
{
    $stmt_get_order = $conn->prepare("SELECT detail_order FROM cms_orders WHERE ID = ? FOR UPDATE");
    $stmt_get_order->bind_param("i", $order_id);
    $stmt_get_order->execute();
    $order = $stmt_get_order->get_result()->fetch_assoc();
    $stmt_get_order->close();

    if (!$order || empty($order['detail_order'])) {
        return;
    }
    $items = json_decode($order['detail_order'], true);

    if (is_array($items) && !empty($items)) {
        $stmt_revert_stock = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls + ? WHERE ID = ?");
        foreach ($items as $item) {
            if (isset($item['id'], $item['quantity'])) {
                $product_id = intval($item['id']);
                $quantity = intval($item['quantity']);
                if ($product_id > 0 && $quantity > 0) {
                    $stmt_revert_stock->bind_param("ii", $quantity, $product_id);
                    $stmt_revert_stock->execute();
                }
            }
        }
        $stmt_revert_stock->close();
    }
}

function handle_delete_order($conn, $user_id)
{
    $order_id = intval($_POST['order_id'] ?? 0);
    if ($order_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID đơn hàng không hợp lệ.']);
        exit();
    }
    $conn->begin_transaction();
    try {
        $stmt_check_order = $conn->prepare("SELECT ID, order_status FROM cms_orders WHERE ID = ? AND deleted = 0");
        $stmt_check_order->bind_param("i", $order_id);
        $stmt_check_order->execute();
        $order_exists = $stmt_check_order->get_result()->fetch_assoc();
        $stmt_check_order->close();

        if (!$order_exists) {
            throw new Exception("Đơn hàng không tồn tại hoặc đã bị xóa.");
        }

        if ($order_exists['order_status'] > 0) {
            revert_stock_from_order($conn, $order_id);
        }

        $stmt_delete_order = $conn->prepare("UPDATE cms_orders SET deleted = 1, user_upd = ?, updated = NOW() WHERE ID = ?");
        $stmt_delete_order->bind_param("ii", $user_id, $order_id);
        $stmt_delete_order->execute();
        $stmt_delete_order->close();

        $conn->commit();
        echo json_encode(['status' => 'success', 'message' => 'Xóa đơn hàng thành công!']);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Đã xảy ra lỗi: ' . $e->getMessage()]);
    }
    exit();
}

function handle_get_order_details($conn)
{
    $order_id = intval($_POST['order_id'] ?? 0);
    if ($order_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'ID đơn hàng không hợp lệ.']);
        exit();
    }

    $stmt_order = $conn->prepare("SELECT * FROM cms_orders WHERE id = ?");
    $stmt_order->bind_param("i", $order_id);
    $stmt_order->execute();
    $order_record = $stmt_order->get_result()->fetch_assoc();
    $stmt_order->close();

    if (!$order_record) {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy đơn hàng.']);
        exit();
    }

    $items_from_db = json_decode($order_record['detail_order'], true) ?: [];
    echo json_encode(['status' => 'success', 'order' => $order_record, 'items' => $items_from_db]);
    exit();
}

function handle_get_orders_list($conn, $user_id, $group_id)
{
    $draw = intval($_POST['draw'] ?? 0);
    $start = intval($_POST['start'] ?? 0);
    $length = intval($_POST['length'] ?? 10);

    $status_map = [
        0 => ['text' => 'Khởi tạo', 'class' => 'bg-warning text-dark'],
        1 => ['text' => 'Hoàn thành', 'class' => 'bg-success'],
    ];

    $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";
    
    $params = [];
    $types = "";
    $where_conditions = [];
    $filter_status = $_POST['filter_status'] ?? 'all_orders';

    if ($filter_status === 'all') { // Đơn hàng hoàn thành
        $where_conditions[] = "o.order_status = 1";
    } elseif ($filter_status === 'draft') { // Đơn hàng khởi tạo
        $where_conditions[] = "o.order_status = 0";
    } elseif ($filter_status === 'debt') {
        $where_conditions[] = "o.lack > 0";
    }

    if ($filter_status !== 'deleted') {
        $where_conditions[] = "o.deleted = 0";
    } else {
        $where_conditions[] = "o.deleted = 1";
    }

    if (!empty($_POST['code'])) { $where_conditions[] = "o.output_code LIKE ?"; $params[] = "%{$_POST['code']}%"; $types .= "s"; }
    if (!empty($_POST['from'])) { $where_conditions[] = "o.sell_date >= ?"; $params[] = "{$_POST['from']} 00:00:00"; $types .= "s"; }
    if (!empty($_POST['to'])) { $where_conditions[] = "o.sell_date <= ?"; $params[] = "{$_POST['to']} 23:59:59"; $types .= "s"; }

    if ($group_id != 1) {
        $where_conditions[] = "o.user_init = ?";
        $params[] = $user_id;
        $types .= "i";
    }

    $where_sql = "";
    if (!empty($where_conditions)) {
        $where_sql = " WHERE " . implode(" AND ", $where_conditions);
    }
    
    $stmt_summary = $conn->prepare("SELECT COUNT(o.id) as total_orders, SUM(o.total_money) as total_amount, SUM(o.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_orders'] ?? 0);
    
    $recordsTotal = $conn->query("SELECT COUNT(ID) FROM cms_orders WHERE deleted = 0")->fetch_row()[0] ?? 0;

    $sql_data = "SELECT o.ID as id, o.output_code, o.sell_date, o.total_money, o.lack, o.order_status, o.total_quantity,
                 COALESCE(c.customer_name, 'Khách lẻ') as customer_name, s.store_name, o.deleted " 
                 . $base_sql . $where_sql . " ORDER BY o.ID 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 = [];
    foreach ($data_rows as $order) {
        $status_info = $status_map[$order['order_status']] ?? ['text' => 'Không xác định', 'class' => 'bg-secondary'];
        $actions = '';
        if ($order['deleted'] == 1) {
            $actions = '<span class="badge bg-dark">Đã bị xóa</span>';
        } else {
            $edit_link = ($order['order_status'] == 0) ? '/quanlybanhang/modules/pos/pos.php?edit_order_id=' . $order['id'] : '/quanlybanhang/modules/pos/pos.php?edit_order_id=' . $order['id'];
            
            $edit_button = '<a href="' . $edit_link . '" class="btn btn-warning btn-sm" title="Sửa"><i class="fas fa-edit"></i></a>';
            $print_button = '<a href="/quanlybanhang/modules/pos/print_invoice.php?order_id=' . $order['id'] . '" class="btn btn-info btn-sm" target="_blank" title="In phiếu"><i class="fas fa-print"></i></a>';
            $delete_button = '<button type="button" class="btn btn-danger btn-sm btn-delete-order" data-id="' . $order['id'] . '" data-code="' . $order['output_code'] . '" title="Xóa"><i class="fas fa-trash"></i></button>';
            $actions = '<div class="btn-group btn-group-sm">' . $edit_button . $print_button . $delete_button . '</div>';
        }

        $data[] = [
            "id" => $order['id'],
            "output_code" => $order['output_code'],
            "store_name" => htmlspecialchars($order['store_name'] ?? 'N/A'),
            "sell_date" => date('d/m/Y H:i', strtotime($order['sell_date'])),
            "customer_name" => htmlspecialchars($order['customer_name']),
            "order_status" => "<span class='badge {$status_info['class']}'>{$status_info['text']}</span>",
            "total_quantity" => $order['total_quantity'],
            "total_money" => $order['total_money'],
            "lack" => $order['lack'],
            "actions" => $actions
        ];
    }
    
    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => $recordsTotal,
        "recordsFiltered" => $recordsFiltered,
        "data" => $data,
        "summary" => [
            "total_orders" => $summary_row['total_orders'] ?? 0,
            "total_amount" => $summary_row['total_amount'] ?? 0,
            "total_debt" => $summary_row['total_debt'] ?? 0
        ]
    ], JSON_NUMERIC_CHECK);
}