<?php
/**
 * POS Order Submission API
 */

session_start();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

require_once '../../include/con_data.php';
require_once '../../include/secondary_ids.php';

$user_id = $_SESSION['user_id'];
// In this system, $_SESSION['user_id'] already contains the US_xxx string,
// so we don't need to look it up using the integer ID.
$user_secondary_id = (strpos($user_id, 'US_') === 0) ? $user_id : getUserSecondaryId($conn, $user_id);

try {
    if (isset($_POST['data'])) {
        $input = json_decode($_POST['data'], true);
    } else {
        $input = json_decode(file_get_contents('php://input'), true);
    }

    if (!$input || empty($input['cart'])) {
        throw new Exception('ຂໍ້ມູນບໍ່ຖືກຕ້ອງ');
    }

    $shop_id = intval($input['shop_id']);
    $sale_type = $input['sale_type'] ?? 'pos';
    $cart = $input['cart'];

    // Customer - store CU_id
    $customer_name = trim($input['customer_name'] ?? '');
    $customer_phone = trim($input['customer_phone'] ?? '');
    $customer_secondary_id = null;

    if (!empty($customer_name)) {
        $stmt = $conn->prepare("SELECT id, CU_id FROM customers WHERE shop_id = ? AND name = ? LIMIT 1");
        $stmt->bind_param("is", $shop_id, $customer_name);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($row = $result->fetch_assoc()) {
            $customer_secondary_id = $row['CU_id'];
        } else {
            // New Customer
            // Check if customers table has CU_id trigger or we need to generate?
            // The source code relied on trigger.
            $stmt = $conn->prepare("INSERT INTO customers (shop_id, name, phone, created_by) VALUES (?, ?, ?, ?)");
            $stmt->bind_param("isss", $shop_id, $customer_name, $customer_phone, $user_secondary_id);
            $stmt->execute();
            $new_customer_id = $conn->insert_id;
            $customer_secondary_id = getCustomerSecondaryId($conn, $new_customer_id);
        }
    }

    // Shipping
    $shipping_company_secondary_id = null;
    $shipping_branch_secondary_id = null;

    if (!empty($input['shipping_company_id'])) {
        $shipping_company_secondary_id = getShippingCompanySecondaryId($conn, intval($input['shipping_company_id']));
    }
    if (!empty($input['shipping_branch_id'])) {
        $shipping_branch_secondary_id = getShippingBranchSecondaryId($conn, intval($input['shipping_branch_id']));
    }

    $cod_type = $input['cod_type'] ?? null;
    $payment_status = $input['payment_status'] ?? 'pending';
    $payment_method = !empty($input['payment_method']) ? $conn->real_escape_string($input['payment_method']) : null;

    // LAK amounts
    $subtotal_lak = floatval($input['subtotal_lak'] ?? 0);
    $discount_lak = floatval($input['discount_lak'] ?? 0);
    $vat_amount_lak = floatval($input['vat_amount_lak'] ?? 0);
    $total_amount_lak = floatval($input['total_amount_lak'] ?? 0);

    // Display amounts
    $subtotal_display = floatval($input['subtotal_display'] ?? $subtotal_lak);
    $discount_display = floatval($input['discount_display'] ?? $discount_lak);
    $vat_display = floatval($input['vat_display'] ?? $vat_amount_lak);
    $total_display = floatval($input['total_display'] ?? $total_amount_lak);

    // Currency
    $currencys_id = !empty($input['currencys_id']) ? $conn->real_escape_string($input['currencys_id']) : null;
    $currency_rate = floatval($input['currency_rate'] ?? 1);
    $rate_id = !empty($input['rate_id']) ? $conn->real_escape_string($input['rate_id']) : null;
    $vat_enabled = intval($input['vat_enabled'] ?? 1);

    // Cash
    $cash_received = floatval($input['amount_received'] ?? 0);
    $cash_change = floatval($input['change_amount'] ?? 0);
    $deposit_amount = ($payment_status === 'partial') ? floatval($input['deposit_amount'] ?? 0) : 0;

    $order_type = $sale_type === 'online' ? 'online' : 'pos';
    $order_status = ($order_type === 'online') ? 'pending' : 'delivered';
    $notes = $cod_type ? $conn->real_escape_string($cod_type) : null;

    // Handle Image Upload (multiple slips)
    $order_image_slip = null;
    $slip_filenames = [];
    if (isset($_FILES['slip_images']) && is_array($_FILES['slip_images']['name'])) {
        $upload_dir = '../../img/slip/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }

        $allowed = ['jpg', 'jpeg', 'png', 'webp', 'gif'];
        $file_count = count($_FILES['slip_images']['name']);

        for ($i = 0; $i < $file_count; $i++) {
            if ($_FILES['slip_images']['error'][$i] === UPLOAD_ERR_OK) {
                $file_info = pathinfo($_FILES['slip_images']['name'][$i]);
                $ext = strtolower($file_info['extension']);

                if (in_array($ext, $allowed)) {
                    $new_filename = uniqid('slip_') . '.' . $ext;
                    $upload_path = $upload_dir . $new_filename;

                    if (move_uploaded_file($_FILES['slip_images']['tmp_name'][$i], $upload_path)) {
                        $slip_filenames[] = $new_filename;
                    }
                }
            }
        }

        if (!empty($slip_filenames)) {
            $order_image_slip = implode(',', $slip_filenames);
        }
    }

    $conn->begin_transaction();

    // INSERT orders
    $sql = "INSERT INTO orders (
        shop_id, customer_id, order_type, order_status, payment_status, payment_method,
        shipping_company_id, shipping_branch_id,
        subtotal, discount_amount, tax_amount, total_amount, deposit_amount,
        cash_received, cash_change, notes,
        vat_enabled, currencys_id, rate_id, currency_rate,
        subtotal_lak, vat_amount_lak, total_amount_lak, discount_lak,
        created_by, order_image_slip
    ) VALUES (
        $shop_id,
        " . ($customer_secondary_id ? "'" . $conn->real_escape_string($customer_secondary_id) . "'" : 'NULL') . ",
        '$order_type',
        '$order_status',
        '$payment_status',
        " . ($payment_method ? "'$payment_method'" : 'NULL') . ",
        " . ($shipping_company_secondary_id ? "'" . $conn->real_escape_string($shipping_company_secondary_id) . "'" : 'NULL') . ",
        " . ($shipping_branch_secondary_id ? "'" . $conn->real_escape_string($shipping_branch_secondary_id) . "'" : 'NULL') . ",
        $subtotal_display,
        $discount_display,
        $vat_display,
        $total_display,
        $deposit_amount,
        $cash_received,
        $cash_change,
        " . ($notes ? "'$notes'" : 'NULL') . ",
        $vat_enabled,
        " . ($currencys_id ? "'$currencys_id'" : 'NULL') . ",
        " . ($rate_id ? "'$rate_id'" : 'NULL') . ",
        $currency_rate,
        $subtotal_lak,
        $vat_amount_lak,
        $total_amount_lak,
        $discount_lak,
        '" . $conn->real_escape_string($user_secondary_id) . "',
        " . ($order_image_slip ? "'" . $conn->real_escape_string($order_image_slip) . "'" : 'NULL') . "
    )";

    if (!$conn->query($sql)) {
        throw new Exception('ບໍ່ສາມາດບັນທຶກອໍເດີໄດ້: ' . $conn->error);
    }

    $order_id = $conn->insert_id;

    $stmt_item = $conn->prepare("INSERT INTO order_items (order_id, product_id, product_name, quantity, unit_price, total) VALUES (?, ?, ?, ?, ?, ?)");

    foreach ($cart as $item) {
        $product_id = intval($item['product_id']);
        $product_secondary_id = getProductSecondaryId($conn, $product_id); // Returns product_code or PR_id
        $product_name = $item['product_name'];
        $qty = floatval($item['quantity']);

        $unit_price = floatval($item['unit_price_display'] ?? $item['unit_price_lak']);
        $item_total = floatval($item['subtotal_display'] ?? $item['subtotal_lak']);

        $stmt_item->bind_param("issddd", $order_id, $product_secondary_id, $product_name, $qty, $unit_price, $item_total);
        if (!$stmt_item->execute()) {
            throw new Exception('ບໍ່ສາມາດບັນທຶກລາຍການສິນຄ້າໄດ້: ' . $stmt_item->error);
        }
    }

    // Get table OR_id if exists/needed for Tips, but we skip Tips complex logic for now unless requested.
    // The source code did fetch OR_id for tips.

    // Check if tips data exists
    $tip_id = null;
    if (!empty($input['tip_data']) && $payment_status === 'paid') {
        // Retrieve OR_id first
        $or_res = $conn->query("SELECT OR_id FROM orders WHERE id = $order_id");
        if ($or_row = $or_res->fetch_assoc()) {
            $or_id = $or_row['OR_id'];

            $tip_data = $input['tip_data'];
            $tip_sql = "INSERT INTO tips (shop_id, order_id, currencys_id, currency_rate, original_total, rounded_total, tip_amount_foreign, tip_amount_lak, calculation_note, created_by) VALUES (
                $shop_id, '$or_id',
                '" . $conn->real_escape_string($tip_data['currencys_id']) . "',
                " . floatval($tip_data['currency_rate']) . ",
                " . floatval($tip_data['original_total']) . ",
                " . floatval($tip_data['rounded_total']) . ",
                " . floatval($tip_data['tip_amount_foreign']) . ",
                " . floatval($tip_data['tip_amount_lak']) . ",
                '" . $conn->real_escape_string($tip_data['calculation_note']) . "',
                '" . $conn->real_escape_string($user_secondary_id) . "'
            )";
            if ($conn->query($tip_sql)) {
                $tip_id = $conn->insert_id;
            }
        }
    }

    $conn->commit();

    echo json_encode([
        'success' => true,
        'message' => 'ບັນທຶກສຳເລັດ',
        'order_id' => $order_id,
        'tip_id' => $tip_id
    ]);

} catch (Exception $e) {
    if (isset($conn) && $conn->ping())
        $conn->rollback();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>