false, 'error' => 'No data provided']); exit; } try { $pdo = db(); $pdo->beginTransaction(); // Validate order_type against allowed ENUM values $allowed_types = ['dine-in', 'takeaway', 'delivery', 'drive-thru']; $order_type = isset($data['order_type']) && in_array($data['order_type'], $allowed_types) ? $data['order_type'] : 'dine-in'; // Get outlet_id from input, default to 1 if missing $outlet_id = isset($data['outlet_id']) ? intval($data['outlet_id']) : 1; $table_id = null; $table_number = null; if ($order_type === 'dine-in') { $tid = $data['table_number'] ?? null; // Front-end sends ID as table_number if ($tid) { // Validate table exists AND belongs to the correct outlet $stmt = $pdo->prepare( "SELECT t.id, t.name FROM tables t JOIN areas a ON t.area_id = a.id WHERE t.id = ? AND a.outlet_id = ?" ); $stmt->execute([$tid, $outlet_id]); $table = $stmt->fetch(PDO::FETCH_ASSOC); if ($table) { $table_id = $table['id']; $table_number = $table['name']; } } // If not found or not provided, leave null (Walk-in/Counter) or try to find a default table for this outlet if (!$table_id) { // Optional: try to find the first available table for this outlet $stmt = $pdo->prepare( "SELECT t.id, t.name FROM tables t JOIN areas a ON t.area_id = a.id WHERE a.outlet_id = ? LIMIT 1" ); $stmt->execute([$outlet_id]); $table = $stmt->fetch(PDO::FETCH_ASSOC); if ($table) { $table_id = $table['id']; $table_number = $table['name']; } } } // Customer Handling $customer_id = $data['customer_id'] ?? null; $customer_name = $data['customer_name'] ?? null; $customer_phone = $data['customer_phone'] ?? null; // Fetch Loyalty Settings $settingsStmt = $pdo->query("SELECT is_enabled, points_per_order, points_for_free_meal FROM loyalty_settings WHERE id = 1"); $settings = $settingsStmt->fetch(PDO::FETCH_ASSOC); $loyalty_enabled = $settings ? (bool)$settings['is_enabled'] : true; $points_per_order = $settings ? intval($settings['points_per_order']) : 10; $points_threshold = $settings ? intval($settings['points_for_free_meal']) : 70; $current_points = 0; $points_deducted = 0; $points_awarded = 0; if ($customer_id) { $stmt = $pdo->prepare("SELECT name, phone, points FROM customers WHERE id = ?"); $stmt->execute([$customer_id]); $cust = $stmt->fetch(PDO::FETCH_ASSOC); if ($cust) { $customer_name = $cust['name']; $customer_phone = $cust['phone']; $current_points = intval($cust['points']); } else { $customer_id = null; } } // Loyalty Redemption Logic $redeem_loyalty = !empty($data['redeem_loyalty']) && $loyalty_enabled; if ($redeem_loyalty && $customer_id) { if ($current_points < $points_threshold) { throw new Exception("Insufficient loyalty points for redemption."); } // Deduct points $deductStmt = $pdo->prepare("UPDATE customers SET points = points - ? WHERE id = ?"); $pdo->prepare("UPDATE customers SET loyalty_redemptions_count = loyalty_redemptions_count + 1 WHERE id = ?")->execute([$customer_id]); $deductStmt->execute([$points_threshold, $customer_id]); $points_deducted = $points_threshold; // --- OVERRIDE PAYMENT TYPE --- $ptStmt = $pdo->prepare("SELECT id FROM payment_types WHERE name = 'Loyalty Redeem' LIMIT 1"); $ptStmt->execute(); $loyaltyPt = $ptStmt->fetchColumn(); if ($loyaltyPt) { $data['payment_type_id'] = $loyaltyPt; } } // Award Points if ($customer_id && $loyalty_enabled) { $awardStmt = $pdo->prepare("UPDATE customers SET points = points + ? WHERE id = ?"); $awardStmt->execute([$points_per_order, $customer_id]); $points_awarded = $points_per_order; } // User/Payment info $user = get_logged_user(); $user_id = $user ? $user['id'] : null; $payment_type_id = isset($data['payment_type_id']) ? intval($data['payment_type_id']) : null; // VAT vs Discount: We repurpose the 'discount' column in the database to store VAT value. // If it's a positive value, it's VAT. If negative, it acts as a discount (loyalty). $vat = isset($data['vat']) ? floatval($data['vat']) : 0.00; // Total amount will be recalculated on server to be safe $calculated_total = 0; // First, process items to calculate real total $processed_items = []; if (!empty($data['items']) && is_array($data['items'])) { foreach ($data['items'] as $item) { $pid = $item['product_id'] ?? ($item['id'] ?? null); if (!$pid) continue; $qty = intval($item['quantity'] ?? 1); $vid = $item['variant_id'] ?? null; // Fetch Product Price (Promo aware) $pStmt = $pdo->prepare("SELECT * FROM products WHERE id = ?"); $pStmt->execute([$pid]); $product = $pStmt->fetch(PDO::FETCH_ASSOC); if (!$product) continue; $unit_price = get_product_price($product); // Add variant adjustment if ($vid) { $vStmt = $pdo->prepare("SELECT price_adjustment FROM product_variants WHERE id = ? AND product_id = ?"); $vStmt->execute([$vid, $pid]); $vAdjustment = $vStmt->fetchColumn(); if ($vAdjustment !== false) { $unit_price += floatval($vAdjustment); } } $item_total = $unit_price * $qty; $calculated_total += $item_total; $processed_items[] = [ 'product_id' => $pid, 'variant_id' => $vid, 'quantity' => $qty, 'unit_price' => $unit_price, 'name' => $product['name'] ]; } } $final_total = max(0, $calculated_total + $vat); // Check for Existing Order ID (Update Mode) $order_id = isset($data['order_id']) ? intval($data['order_id']) : null; $is_update = false; if ($order_id) { $checkStmt = $pdo->prepare("SELECT id FROM orders WHERE id = ?"); $checkStmt->execute([$order_id]); if ($checkStmt->fetch()) { $is_update = true; } else { $order_id = null; } } if ($is_update) { // UPDATE Existing Order $stmt = $pdo->prepare("UPDATE orders SET outlet_id = ?, table_id = ?, table_number = ?, order_type = ?, customer_id = ?, customer_name = ?, customer_phone = ?, payment_type_id = ?, total_amount = ?, discount = ?, user_id = ?, status = 'pending' WHERE id = ?"); $stmt->execute([ $outlet_id, $table_id, $table_number, $order_type, $customer_id, $customer_name, $customer_phone, $payment_type_id, $final_total, $vat, $user_id, $order_id ]); $delStmt = $pdo->prepare("DELETE FROM order_items WHERE order_id = ?"); $delStmt->execute([$order_id]); } else { // INSERT New Order $stmt = $pdo->prepare("INSERT INTO orders (outlet_id, table_id, table_number, order_type, customer_id, customer_name, customer_phone, payment_type_id, total_amount, discount, user_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')"); $stmt->execute([$outlet_id, $table_id, $table_number, $order_type, $customer_id, $customer_name, $customer_phone, $payment_type_id, $final_total, $vat, $user_id]); $order_id = $pdo->lastInsertId(); } // Insert Items and Update Stock $item_stmt = $pdo->prepare("INSERT INTO order_items (order_id, product_id, variant_id, quantity, unit_price) VALUES (?, ?, ?, ?, ?)"); $stock_stmt = $pdo->prepare("UPDATE products SET stock_quantity = stock_quantity - ? WHERE id = ?"); $varNameStmt = $pdo->prepare("SELECT name FROM product_variants WHERE id = ?"); $order_items_list = []; foreach ($processed_items as $pi) { $item_stmt->execute([$order_id, $pi['product_id'], $pi['variant_id'], $pi['quantity'], $pi['unit_price']]); // Decrement Stock $stock_stmt->execute([$pi['quantity'], $pi['product_id']]); $pName = $pi['name']; if ($pi['variant_id']) { $varNameStmt->execute([$pi['variant_id']]); $vName = $varNameStmt->fetchColumn(); if ($vName) $pName .= " ($vName)"; } $order_items_list[] = "{$pi['quantity']} x $pName"; } $pdo->commit(); // --- Post-Transaction Actions (WhatsApp) --- if ($customer_id && $customer_phone) { try { $final_points = $current_points - $points_deducted + ($loyalty_enabled ? $points_awarded : 0); $wablas = new WablasService($pdo); $companySettings = get_company_settings(); $company_name = $companySettings['company_name'] ?? 'Flatlogic POS'; $stmt = $pdo->prepare("SELECT setting_value FROM integration_settings WHERE provider = 'wablas' AND setting_key = 'order_template'"); $stmt->execute(); $template = $stmt->fetchColumn(); if (!$template) { $template = "Dear *{customer_name}*, Thank you for dining with *{company_name}*! 🍽️ *Order Details:* {order_details} Total: *{total_amount}* OMR You've earned *{points_earned} points* with this order. 💰 *Current Balance: {new_balance} points* {loyalty_status}"; } $loyalty_status = ""; if ($loyalty_enabled) { $loyalty_status = ($final_points >= $points_threshold) ? "🎉 Congratulations! You have enough points for a *FREE MEAL* on your next visit!" : "You need *" . ($points_threshold - $final_points) . " more points* to unlock a free meal."; } $replacements = [ '{customer_name}' => $customer_name, '{company_name}' => $company_name, '{order_id}' => $order_id, '{order_details}' => implode("\n", $order_items_list), '{total_amount}' => number_format($final_total, 3), '{points_earned}' => $loyalty_enabled ? $points_awarded : 0, '{points_redeemed}' => $points_deducted, '{new_balance}' => $final_points, '{loyalty_status}' => $loyalty_status ]; $msg = str_replace(array_keys($replacements), array_values($replacements), $template); $wablas->sendMessage($customer_phone, $msg); } catch (Exception $w) { error_log("Wablas Exception: " . $w->getMessage()); } } echo json_encode(['success' => true, 'order_id' => $order_id]); } catch (Exception $e) { if ($pdo->inTransaction()) $pdo->rollBack(); error_log("Order Error: " . $e->getMessage()); echo json_encode(['success' => false, 'error' => $e->getMessage()]); }