<?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;
$action = $_REQUEST['action'] ?? '';

function process_draft_order_saving($conn, $user_id)
{
    $order_id = intval($_POST['order_id'] ?? 0);
    $is_edit = $order_id > 0;
    
    $new_status = intval($_POST['order_status'] ?? 0); 

    $store_id = intval($_POST['store_id'] ?? ($_SESSION['store_id'] ?? 0));
    if ($store_id <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Không tìm thấy thông tin cửa hàng.']);
        return;
    }
    
    $customer_id = intval($_POST['customer_id'] ?? 1);
    $notes = trim($_POST['notes'] ?? '');
    
    $items = json_decode($_POST['items'] ?? '[]', true);
    $discount_value = floatval(str_replace(',', '.', $_POST['discount_value'] ?? 0));
    $discount_type = $_POST['discount_type'] ?? 'percent';
    $vat_percent = intval($_POST['vat'] ?? 0);
    $payment_method = intval($_POST['payment_method'] ?? 1);
    $sell_date = $_POST['sale_date'] ? date('Y-m-d H:i:s', strtotime($_POST['sale_date'])) : date('Y-m-d H:i:s');

    if (empty($items) || !is_array($items)) {
        echo json_encode(['status' => 'error', 'message' => 'Đơn hàng phải có ít nhất một sản phẩm.']);
        return;
    }

    $conn->begin_transaction();
    try {
        $old_status = -1;
        if ($is_edit) {
            $stmt_old = $conn->prepare("SELECT order_status FROM cms_orders WHERE ID = ? FOR UPDATE");
            $stmt_old->bind_param("i", $order_id);
            $stmt_old->execute();
            $old_order_data = $stmt_old->get_result()->fetch_assoc();
            $stmt_old->close();
            if ($old_order_data) {
                $old_status = intval($old_order_data['order_status']);
            }
        }
        
        $total_price_after_item_discount = 0;
        $total_origin_price_for_db = 0;
        $total_quantity = 0;
        $total_discount_on_items = 0;
        $items_to_save = [];
        
        $product_ids = array_column($items, 'id');
        $products_info = [];
        if (!empty($product_ids)) {
             $ids_placeholder = implode(',', array_fill(0, count($product_ids), '?'));
             $types = str_repeat('i', count($product_ids));
             $sql_products = "SELECT ID, prd_origin_price, 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();
             $result = $stmt_products->get_result();
             while($row = $result->fetch_assoc()) {
                 $products_info[$row['ID']] = $row;
             }
             $stmt_products->close();
        }

        foreach ($items as $item) {
            $p_id = intval($item['id']);
            $p_qty_new = intval($item['quantity']);
            $p_price = floatval($item['price']);
            $p_discount_percent = floatval($item['percent'] ?? 0);
            $p_note = trim($item['note'] ?? '');

            $prod_info = $products_info[$p_id] ?? null;
            if (!$prod_info) {
                throw new Exception("Không tìm thấy thông tin sản phẩm với ID: " . $p_id);
            }

            $p_cost = $prod_info['prd_origin_price'] ?? 0;

            if ($p_price < $p_cost) {
                throw new Exception("Giá bán của sản phẩm '{$prod_info['prd_name']}' không được thấp hơn giá vốn.");
            }

            $line_original_price = $p_qty_new * $p_price;
            $line_item_discount_amount = $line_original_price * ($p_discount_percent / 100);
            $line_final_price = $line_original_price - $line_item_discount_amount;

            $total_price_after_item_discount += $line_final_price;
            $total_discount_on_items += $line_item_discount_amount;
            $total_origin_price_for_db += ($p_qty_new * $p_cost);
            $total_quantity += $p_qty_new;

            $items_to_save[] = [
                'id' => $p_id, 'code' => $prod_info['prd_code'] ?? 'N/A',
                'name' => $item['name'] ?? $prod_info['prd_name'], 'quantity' => $p_qty_new,
                'price' => $p_price, 'origin_price' => $p_cost,
                'percent' => $p_discount_percent, 'discount' => $line_item_discount_amount,
                'note' => $p_note
            ];
        }

        if ($new_status == 1 && $old_status == 0) {
            $stmt_stock_check = $conn->prepare("SELECT prd_sls, prd_name FROM cms_products WHERE ID = ? FOR UPDATE");
            $stmt_stock_update = $conn->prepare("UPDATE cms_products SET prd_sls = prd_sls - ? WHERE ID = ?");
            foreach ($items_to_save as $item) {
                $stmt_stock_check->bind_param("i", $item['id']);
                $stmt_stock_check->execute();
                $stock_data = $stmt_stock_check->get_result()->fetch_assoc();
                $current_stock = $stock_data['prd_sls'];
                
                if ($item['quantity'] > $current_stock) {
                    throw new Exception("Sản phẩm '{$stock_data['prd_name']}' không đủ tồn kho (còn {$current_stock}, cần {$item['quantity']}).");
                }
                $stmt_stock_update->bind_param("ii", $item['quantity'], $item['id']);
                $stmt_stock_update->execute();
            }
            $stmt_stock_check->close();
            $stmt_stock_update->close();
        }

        $discount_order_amount = ($discount_type === 'fixed') ? $discount_value : ($total_price_after_item_discount * ($discount_value / 100));
        $discount_order_percent = ($discount_type === 'percent') ? $discount_value : 0;
        
        $price_after_order_discount = $total_price_after_item_discount - $discount_order_amount;
        $vat_money = $price_after_order_discount * ($vat_percent / 100);
        $final_total_money = $price_after_order_discount + $vat_money;

        $customer_pay_raw = $_POST['customer_pay'] ?? '';
        $customer_pay_provided = ($customer_pay_raw !== '' && $customer_pay_raw !== null);
        $customer_pay_value = floatval(str_replace('.', '', $customer_pay_raw));

        if ($new_status == 1 && $payment_method == 2) {
            if (!$customer_pay_provided || $customer_pay_value == $final_total_money) {
                $customer_pay = 0;
            } else {
                $customer_pay = $customer_pay_value;
            }
        } else if ($new_status == 0) {
            $customer_pay = 0;
        } else if (!$customer_pay_provided) {
            $customer_pay = $final_total_money;
        } else {
            $customer_pay = $customer_pay_value;
        }
        
        $lack = $final_total_money - $customer_pay;
        $detail_order_json = json_encode($items_to_save, JSON_UNESCAPED_UNICODE);
        
        $output_code = '';

        if ($is_edit) {
            $output_code_update_sql = "";
            if ($new_status == 1 && $old_status == 0) {
                $last_id = $conn->query("SELECT MAX(CAST(SUBSTRING(output_code, 4) AS UNSIGNED)) FROM cms_orders WHERE output_code LIKE 'PXK%' AND output_code NOT LIKE 'PXKT%'")->fetch_row()[0] ?? 0;
                $output_code = 'PXK' . str_pad($last_id + 1, 7, '0', STR_PAD_LEFT);
                $output_code_update_sql = ", output_code='" . $conn->real_escape_string($output_code) . "'";
            }

            $sql_order = "UPDATE cms_orders SET customer_id=?, store_id=?, sell_date=?, notes=?, total_price=?, total_origin_price=?, total_quantity=?, total_money=?, total_discount=?, discount_item=?, discount_percent=?, vat=?, customer_pay=?, lack=?, detail_order=?, user_upd=?, payment_method=?, order_status=? {$output_code_update_sql} WHERE ID=?";
            $stmt_order = $conn->prepare($sql_order);
            $stmt_order->bind_param("iissddiddddiddsiiii", $customer_id, $store_id, $sell_date, $notes, $total_price_after_item_discount, $total_origin_price_for_db, $total_quantity, $final_total_money, $discount_order_amount, $total_discount_on_items, $discount_order_percent, $vat_percent, $customer_pay, $lack, $detail_order_json, $user_id, $payment_method, $new_status, $order_id);
        } else {
            $last_id_result = $conn->query("SELECT id FROM cms_orders ORDER BY id DESC LIMIT 1");
            $last_id = $last_id_result->fetch_row()[0] ?? 0;
            $output_code = 'PXKT' . str_pad($last_id + 1, 7, '0', STR_PAD_LEFT);
            $sql_order = "INSERT INTO cms_orders (output_code, customer_id, store_id, sell_date, notes, total_price, total_origin_price, total_quantity, total_money, total_discount, discount_item, discount_percent, vat, customer_pay, lack, detail_order, user_init, created, order_status, payment_method) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?, ?)";
            $stmt_order = $conn->prepare($sql_order);
            $stmt_order->bind_param("siissddiddddiddsiii", $output_code, $customer_id, $store_id, $sell_date, $notes, $total_price_after_item_discount, $total_origin_price_for_db, $total_quantity, $final_total_money, $discount_order_amount, $total_discount_on_items, $discount_order_percent, $vat_percent, $customer_pay, $lack, $detail_order_json, $user_id, $new_status, $payment_method);
        }

        if (!$stmt_order->execute()) {
            throw new Exception("Lỗi CSDL khi lưu đơn hàng: " . $stmt_order->error);
        }
        
        if (!$is_edit) $order_id = $conn->insert_id;

        $output_code_for_display = $output_code;
        if ($is_edit) {
            if (empty($output_code)) {
                $stmt_code = $conn->prepare("SELECT output_code FROM cms_orders WHERE ID = ?");
                $stmt_code->bind_param("i", $order_id);
                $stmt_code->execute();
                $output_code_for_display = $stmt_code->get_result()->fetch_row()[0];
                $stmt_code->close();
            }
        }
        
        $customer_name = 'Khách lẻ';
        $customer_phone = '';
        if ($customer_id > 1) {
            $stmt_cust = $conn->prepare("SELECT customer_name, customer_phone FROM cms_customers WHERE ID = ?");
            $stmt_cust->bind_param("i", $customer_id);
            $stmt_cust->execute();
            $cust_result = $stmt_cust->get_result()->fetch_assoc();
            if ($cust_result) {
                $customer_name = $cust_result['customer_name'];
                $customer_phone = $cust_result['customer_phone'];
            }
            $stmt_cust->close();
        }

        if ($new_status == 1) {
            $sql_update_display = "UPDATE cms_payment_display SET order_id = ?, order_code = ?, customer_name = ?, customer_phone = ?, total_amount = ?, payment_status = 'waiting' WHERE id = 1";
            $stmt_display_update = $conn->prepare($sql_update_display);
            
            if ($stmt_display_update) {
                $stmt_display_update->bind_param(
                    "isssd",
                    $order_id,
                    $output_code_for_display,
                    $customer_name,
                    $customer_phone,
                    $final_total_money
                );
                if (!$stmt_display_update->execute()) {
                    throw new Exception("Lỗi khi cập nhật bảng hiển thị: " . $stmt_display_update->error);
                }
                $stmt_display_update->close();
            } else {
                throw new Exception("Lỗi khi chuẩn bị câu lệnh cập nhật hiển thị: " . $conn->error);
            }
        }
        
        $conn->commit();
        $message = "Thao tác thành công!";
        if ($new_status == 1 && $old_status == 0) {
            $message = "Chuyển đơn hàng sang trạng thái thành công!";
        }
        echo json_encode(['status' => 'success', 'message' => $message, 'order_id' => $order_id]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode(['status' => 'error', 'message' => 'Lỗi: ' . $e->getMessage()]);
    }
}

switch ($action) {
    case 'save_or_update_order':
        process_draft_order_saving($conn, $user_id);
        break;
    default:
        echo json_encode(['status' => 'error', 'message' => 'Hành động không hợp lệ.']);
        break;
}
?>