<?php
// ajax/pos_table_ajax.php (Bản Fix lỗi Thanh toán ngay & Trả về Order ID để in)
ini_set('display_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/../config/database.php';
session_start();

$store_id = $_SESSION['store_id'] ?? 1;
$user_id = $_SESSION['user_id'] ?? 0;
$action = $_POST['action'] ?? $_GET['action'] ?? '';

// --- 1. LƯU ĐƠN / IN BẾP ---
if ($action == 'save_order') {
    $table_id = intval($_POST['table_id']);
    $customer_id = intval($_POST['customer_id']);
    $items = $_POST['items']; 
    $discount = floatval($_POST['discount']);
    $discount_type = $_POST['discount_type']; 
    
    if($table_id == 0) { echo json_encode(['status'=>'error', 'message'=>'Chưa chọn bàn']); exit; }

    // Logic Lưu đơn giữ nguyên như cũ (Check -> Update hoặc Insert)
    $check = $conn->query("SELECT ID FROM cms_orders WHERE table_id = $table_id AND order_status = 0 AND deleted = 0 LIMIT 1");
    $order_id = 0;
    
    $cart = json_decode($items, true);
    $total_money = 0;
    $total_qty = 0;
    if(is_array($cart)) {
        foreach($cart as $item) {
            $total_money += $item['price'] * $item['qty'];
            $total_qty += $item['qty'];
        }
    }
    
    if ($check->num_rows > 0) {
        $order = $check->fetch_assoc();
        $order_id = $order['ID'];
        $sql = "UPDATE cms_orders SET detail_order = '$items', total_money = $total_money, total_quantity = $total_qty, customer_id = $customer_id, coupon = $discount, updated = NOW() WHERE ID = $order_id";
    } else {
        $code = 'DH' . time();
        $sql = "INSERT INTO cms_orders (output_code, store_id, customer_id, table_id, detail_order, total_money, total_quantity, coupon, order_status, user_init, created) 
                VALUES ('$code', $store_id, $customer_id, $table_id, '$items', $total_money, $total_qty, $discount, 0, $user_id, NOW())";
    }
    
    if($conn->query($sql)) {
        $conn->query("UPDATE cms_tables SET table_status = 1 WHERE id = $table_id");
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => $conn->error]);
    }
}

// --- 2. THANH TOÁN (SỬA LẠI LOGIC: INSERT NẾU CHƯA CÓ) ---
if ($action == 'pay_order') {
    $table_id = intval($_POST['table_id']);
    $customer_id = intval($_POST['customer_id']);
    $items = $_POST['items']; 
    $discount = floatval($_POST['discount']);
    $customer_pay = floatval($_POST['customer_pay']);
    
    // Tính toán tổng tiền & giá vốn
    $cart = json_decode($items, true);
    $total_money = 0;
    $total_qty = 0;
    $cogs_total = 0; 
    
    if(is_array($cart)) {
        foreach($cart as $item) {
            $total_money += $item['price'] * $item['qty'];
            $total_qty += $item['qty'];
            $cogs_total += ($item['origin'] ?? 0) * $item['qty']; 
        }
    }
    
    $final_money = max(0, $total_money - $discount);
    
    // Tìm đơn đang mở
    $check = $conn->query("SELECT ID FROM cms_orders WHERE table_id = $table_id AND order_status = 0 AND deleted = 0 LIMIT 1");
    $order_id = 0;

    if($check->num_rows > 0) {
        // TRƯỜNG HỢP 1: ĐÃ CÓ ĐƠN -> UPDATE
        $order = $check->fetch_assoc();
        $order_id = $order['ID'];
        
        $sql = "UPDATE cms_orders SET 
                order_status = 1, detail_order = '$items', total_money = $total_money, total_quantity = $total_qty,
                coupon = $discount, customer_pay = $customer_pay, customer_id = $customer_id, sell_date = NOW() 
                WHERE ID = $order_id";
    } else {
        // TRƯỜNG HỢP 2: CHƯA CÓ ĐƠN (THANH TOÁN LUÔN) -> INSERT MỚI
        $code = 'DH' . time();
        $sql = "INSERT INTO cms_orders (output_code, store_id, customer_id, table_id, detail_order, total_money, total_quantity, coupon, customer_pay, order_status, user_init, created, sell_date) 
                VALUES ('$code', $store_id, $customer_id, $table_id, '$items', $total_money, $total_qty, $discount, $customer_pay, 1, $user_id, NOW(), NOW())";
    }

    if($conn->query($sql)) {
        if ($order_id == 0) $order_id = $conn->insert_id; // Lấy ID nếu là insert mới

        // 1. Trả bàn về trống (0)
        $conn->query("UPDATE cms_tables SET table_status = 0 WHERE id = $table_id");
        
        // 2. Trừ kho (Chỉ hàng hóa - prd_type=0)
        if(is_array($cart)) {
            foreach($cart as $item) {
                if(isset($item['type']) && $item['type'] == 0) {
                    $pid = intval($item['id']);
                    $qty = floatval($item['qty']);
                    $conn->query("UPDATE cms_products SET prd_sls = prd_sls - $qty WHERE ID = $pid");
                }
            }
        }
        
        // 3. Ghi Sổ cái (Ledger)
        $checkTable = $conn->query("SHOW TABLES LIKE 'cms_ledger'");
        if($checkTable->num_rows > 0) {
            $conn->query("INSERT INTO cms_ledger (store_id, source_type, ref_id, amount_in, cogs, transaction_date) 
                          VALUES ($store_id, 'ORDER', $order_id, $final_money, $cogs_total, NOW())");
        }
        
        // TRẢ VỀ ORDER_ID ĐỂ JS GỌI TRANG IN
        echo json_encode(['status' => 'success', 'order_id' => $order_id]);
    } else {
        echo json_encode(['status' => 'error', 'message' => $conn->error]);
    }
}

// --- 3. LẤY ĐƠN HÀNG CỦA BÀN ---
if ($action == 'get_table_order') {
    $table_id = intval($_GET['table_id']);
    $res = $conn->query("SELECT detail_order, coupon, customer_id, ID FROM cms_orders WHERE table_id = $table_id AND order_status = 0 AND deleted = 0 LIMIT 1");
    if($res->num_rows > 0) {
        $row = $res->fetch_assoc();
        echo json_encode([
            'status' => 'success', 
            'data' => json_decode($row['detail_order'], true), 
            'order_id' => $row['ID'],
            'discount_val' => $row['coupon'],
            'customer_id' => $row['customer_id']
        ]);
    } else {
        echo json_encode(['status' => 'empty']);
    }
}
?>