<?php
require_once __DIR__ . '/../core/init.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'] ?? '';

function refValues($arr){
    $refs = array();
    foreach($arr as $key => $value)
        $refs[$key] = &$arr[$key];
    return $refs;
}

// --- BỘ ĐỊNH TUYẾN (ROUTER) ---
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 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_get_order = $conn->prepare("SELECT detail_order FROM cms_orders WHERE ID = ? AND deleted = 0 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) {
            throw new Exception("Đơn hàng không tồn tại hoặc đã bị xóa trước đó.");
        }

        $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 + ?, prd_total_value = prd_total_value + ? WHERE ID = ?");
            foreach ($items as $item) {
                if (isset($item['id'], $item['quantity'], $item['origin_price'])) {
                    $product_id = intval($item['id']);
                    $quantity = floatval($item['quantity']);
                    $origin_price = floatval($item['origin_price']);
                    $value_to_revert = $quantity * $origin_price;

                    if ($product_id > 0 && $quantity > 0) {
                        $stmt_revert_stock->bind_param("ddi", $quantity, $value_to_revert, $product_id);
                        $stmt_revert_stock->execute();
                    }
                }
            }
            $stmt_revert_stock->close();

            $product_ids_in_order = array_unique(array_column($items, 'id'));
            $stmt_recalc_avg_cost = $conn->prepare("UPDATE cms_products SET prd_average_cost = IF(prd_sls > 0, prd_total_value / prd_sls, 0) WHERE ID = ?");
            foreach($product_ids_in_order as $pid) {
                if($pid > 0) {
                    $stmt_recalc_avg_cost->bind_param("i", $pid);
                    $stmt_recalc_avg_cost->execute();
                }
            }
            $stmt_recalc_avg_cost->close();
        }
        
        $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 và hoàn trả tồn kho 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 detail_order FROM cms_orders WHERE id = ?");
    $stmt_order->bind_param("i", $order_id);
    $stmt_order->execute();
    $order_data = $stmt_order->get_result()->fetch_assoc();
    $stmt_order->close();

    if (!$order_data || empty($order_data['detail_order'])) {
        echo json_encode(['status' => 'success', 'data' => []]);
        exit();
    }

    $details = json_decode($order_data['detail_order'], true);
    if (json_last_error() !== JSON_ERROR_NONE || !is_array($details) || empty($details)) {
        echo json_encode(['status' => 'success', 'data' => []]);
        exit();
    }

    $valid_items = array_filter($details, function($item) {
        return is_array($item) && isset($item['id']) && is_numeric($item['id']);
    });
    $product_ids = array_column($valid_items, 'id');

    if (!empty($product_ids)) {
        $products_info = [];
        $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
        $types = str_repeat('i', count($product_ids));
        
        $sql_products = "SELECT ID, prd_name, prd_code FROM cms_products WHERE ID IN ($ids_placeholder)";
        $stmt_products = $conn->prepare($sql_products);
        $stmt_products->bind_param($types, ...$product_ids);
        $stmt_products->execute();
        $products_result = $stmt_products->get_result();
        while($row = $products_result->fetch_assoc()) {
            $products_info[$row['ID']] = $row;
        }
        $stmt_products->close();

        foreach ($details as $key => $item) {
            if (isset($item['id']) && isset($products_info[$item['id']])) {
                $details[$key]['name'] = $products_info[$item['id']]['prd_name'];
                $details[$key]['code'] = $products_info[$item['id']]['prd_code'];
            } else {
                $details[$key]['name'] = 'Sản phẩm không tồn tại';
                $details[$key]['code'] = 'N/A';
            }
        }
    }
    echo json_encode(['status' => 'success', 'data' => $details]);
    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);
    
    $order_by_sql = "ORDER BY o.sell_date DESC, o.ID DESC";
    
    // Đã thêm Status 5 (Khởi tạo/Chờ duyệt)
    $status_map = [ 
        0 => ['text' => 'Đã hủy', 'class' => 'bg-danger'], 
        1 => ['text' => 'Hoàn thành', 'class' => 'bg-success'], 
        2 => ['text' => 'Đang giao', 'class' => 'bg-info'], 
        3 => ['text' => 'Xác nhận', 'class' => 'bg-primary'],
        5 => ['text' => 'Khởi tạo', 'class' => 'bg-secondary'], // Trạng thái đơn từ Mobile
    ];
    
    $base_sql = "FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID LEFT JOIN cms_users u ON o.user_init = u.id";
    
    $params = []; $types = ""; $where_conditions = [];
    $view_mode = $_POST['view_mode'] ?? 'all';
    switch ($view_mode) {
        case 'deleted': $where_conditions[] = "o.deleted = 1"; break;
        case 'debt': $where_conditions[] = "o.deleted = 0 AND o.lack > 0"; break;
        default: $where_conditions[] = "o.deleted = 0"; break;
    }

    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 = " WHERE " . implode(" AND ", $where_conditions);
    $sql_summary = "SELECT COUNT(o.id) as total_orders, SUM(o.total_money) as total_amount, SUM(o.lack) as total_debt " . $base_sql . $where_sql;
    $stmt_summary = $conn->prepare($sql_summary);
    if ($types) {
        call_user_func_array([$stmt_summary, 'bind_param'], refValues(array_merge([$types], $params)));
    }
    $stmt_summary->execute();
    $summary_row = $stmt_summary->get_result()->fetch_assoc();
    $stmt_summary->close();
    $recordsFiltered = intval($summary_row['total_orders'] ?? 0);
    
    $sql_total_all = "SELECT COUNT(ID) FROM cms_orders WHERE deleted = 0";
    if ($group_id != 1) {
        $sql_total_all .= " AND user_init = " . $user_id;
    }
    $recordsTotal = $conn->query($sql_total_all)->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, COALESCE(c.customer_name, 'Khách lẻ') as customer_name, u.username, o.deleted " . $base_sql . $where_sql . " " . $order_by_sql . " LIMIT ?, ?";
    
    $data_params = $params; array_push($data_params, $start, $length);
    $data_types = $types . 'ii';

    $stmt_data = $conn->prepare($sql_data);
    if($stmt_data) {
        call_user_func_array([$stmt_data, 'bind_param'], refValues(array_merge([$data_types], $data_params)));
        $stmt_data->execute();
        $result = $stmt_data->get_result();
        $data_rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
        $stmt_data->close();
    } else {
        $data_rows = [];
    }
    
    $data = [];
    foreach($data_rows as $order) {
        $status_info = $status_map[$order['order_status']] ?? ['text' => 'N/A', 'class' => 'bg-secondary'];
        $actions = '';
        if ($order['deleted'] == 1) {
            $actions = '<span class="badge bg-dark">Đã bị xóa</span>';
        } else {
            // Thay đổi URL Sửa đơn để chuyển đến POS desktop (cho Kế toán duyệt)
            $edit_url = "/quanlybanhang/modules/pos/pos.php?edit_order_id={$order['id']}";
            
            $edit_button = '<a href="'.$edit_url.'" 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-secondary 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 đơn hàng"><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'], "sell_date" => date('d/m/Y H:i', strtotime($order['sell_date'])), "customer_name" => htmlspecialchars($order['customer_name']), "username" => htmlspecialchars($order['username'] ?? 'N/A'), "total_money" => $order['total_money'], "lack" => $order['lack'], "order_status" => "<span class='badge {$status_info['class']}'>{$status_info['text']}</span>", "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);
}
?>