<?php
// app/Controllers/QrController.php

class QrController {
    public function menu() {
        $token = $_GET['t'] ?? '';
        $code  = $_GET['code'] ?? '';

        if (!$token && !$code) {
            require 'app/Views/qr/entry.php';
            exit;
        }

        $db = getDB();
        if ($token) {
            $stmt = $db->prepare('SELECT t.*, f.name as floor_name, r.name as restaurant_name, r.logo as restaurant_logo, r.id as rest_id FROM tables t JOIN floors f ON f.id = t.floor_id JOIN restaurants r ON r.id = t.restaurant_id WHERE t.qr_code = ? LIMIT 1');
            $stmt->execute([$token]);
        } else {
            $stmt = $db->prepare('SELECT t.*, f.name as floor_name, r.name as restaurant_name, r.logo as restaurant_logo, r.id as rest_id FROM tables t JOIN floors f ON f.id = t.floor_id JOIN restaurants r ON r.id = t.restaurant_id WHERE t.table_code = ? LIMIT 1');
            $stmt->execute([$code]);
        }
        $table = $stmt->fetch();

        if (!$table) {
            echo '<!DOCTYPE html><html><body style="font-family:sans-serif;text-align:center;padding:50px"><h2>Table Not Found</h2></body></html>';
            exit;
        }

        // Check subscription expiry for this restaurant
        if (FeatureGate::isExpired($table['rest_id'])) {
            echo '<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><title>Service Unavailable</title></head>';
            echo '<body style="font-family:system-ui,sans-serif;text-align:center;padding:60px 20px;background:#0f172a;color:#e2e8f0;margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center">';
            echo '<div><div style="font-size:48px;margin-bottom:16px">⚠️</div>';
            echo '<h2 style="font-size:22px;font-weight:700;margin:0 0 8px;color:#fca5a5">Service Temporarily Unavailable</h2>';
            echo '<p style="color:#94a3b8;font-size:14px;margin:0">Online ordering is currently unavailable for this restaurant.<br>Please contact the staff for assistance.</p>';
            echo '</div></body></html>';
            exit;
        }

        // Check if QR Ordering is included in the package
        if (!FeatureGate::hasQrOrdering($table['rest_id'])) {
            echo '<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><title>Service Unavailable</title></head>';
            echo '<body style="font-family:system-ui,sans-serif;text-align:center;padding:60px 20px;background:#0f172a;color:#e2e8f0;margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center">';
            echo '<div><div style="font-size:48px;margin-bottom:16px">⚠️</div>';
            echo '<h2 style="font-size:22px;font-weight:700;margin:0 0 8px;color:#fca5a5">Service Temporarily Unavailable</h2>';
            echo '<p style="color:#94a3b8;font-size:14px;margin:0">Online QR ordering is not included in this restaurant\'s active subscription package.</p>';
            echo '</div></body></html>';
            exit;
        }

        $cats = $db->prepare('SELECT * FROM categories WHERE restaurant_id = ? AND status="active" ORDER BY name');
        $cats->execute([$table['rest_id']]);
        $categories = $cats->fetchAll();

        $prods = $db->prepare('SELECT * FROM products WHERE restaurant_id = ? AND status="active" ORDER BY category_id, name');
        $prods->execute([$table['rest_id']]);
        $products = $prods->fetchAll();

        $cpns = $db->prepare('SELECT * FROM restaurant_coupons WHERE restaurant_id = ? AND (floor_id IS NULL OR floor_id = ?) AND status = "active" AND expiry_date >= DATE(NOW())');
        $cpns->execute([$table['rest_id'], $table['floor_id']]);
        $coupons = $cpns->fetchAll();

        $currency = FeatureGate::currency($table['rest_id']);

        // Fetch active/unpaid order if table is occupied
        $activeOrder = null;
        $activeOrderItems = [];
        if ($table['status'] === 'occupied') {
            $activeStmt = $db->prepare('SELECT * FROM orders WHERE table_id = ? AND payment_status = "unpaid" AND status != "voided" ORDER BY id DESC LIMIT 1');
            $activeStmt->execute([$table['id']]);
            $activeOrder = $activeStmt->fetch();

            if ($activeOrder) {
                $itemsStmt = $db->prepare('SELECT oi.*, p.name as product_name, p.image as product_image FROM order_items oi JOIN products p ON p.id = oi.product_id WHERE oi.order_id = ?');
                $itemsStmt->execute([$activeOrder['id']]);
                $activeOrderItems = $itemsStmt->fetchAll();
            }
        }

        require 'app/Views/qr/menu.php';
    }

    public function menuBySlug($slug) {
        $db = getDB();
        $stmt = $db->prepare('SELECT * FROM restaurants WHERE slug = ? LIMIT 1');
        $stmt->execute([$slug]);
        $restaurant = $stmt->fetch();
        if (!$restaurant) {
            echo '<!DOCTYPE html><html><body style="font-family:sans-serif;text-align:center;padding:50px"><h2>Restaurant Not Found</h2></body></html>';
            exit;
        }

        $code = $_GET['code'] ?? $_GET['t'] ?? '';
        if (!$code) {
            $error = '';
            require 'app/Views/qr/entry.php';
            exit;
        }

        // Table code can be either 6-digit code or qr_code (token)
        $tStmt = $db->prepare('SELECT t.*, f.name as floor_name, r.name as restaurant_name, r.logo as restaurant_logo, r.id as rest_id FROM tables t JOIN floors f ON f.id = t.floor_id JOIN restaurants r ON r.id = t.restaurant_id WHERE r.id = ? AND (t.table_code = ? OR t.qr_code = ?) LIMIT 1');
        $tStmt->execute([$restaurant['id'], $code, $code]);
        $table = $tStmt->fetch();

        if (!$table) {
            $error = 'Invalid table code.';
            require 'app/Views/qr/entry.php';
            exit;
        }

        // Check if table is within allowed subscription limits
        $allowedTableIds = FeatureGate::getAllowedTableIds($table['rest_id']);
        if (!in_array($table['id'], $allowedTableIds)) {
            echo '<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><title>Service Unavailable</title></head>';
            echo '<body style="font-family:system-ui,sans-serif;text-align:center;padding:60px 20px;background:#0f172a;color:#e2e8f0;margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center">';
            echo '<div><div style="font-size:48px;margin-bottom:16px">⚠️</div>';
            echo '<h2 style="font-size:22px;font-weight:700;margin:0 0 8px;color:#fca5a5">Service Temporarily Unavailable</h2>';
            echo '<p style="color:#94a3b8;font-size:14px;margin:0">This table is currently disabled as it exceeds the restaurant\'s active subscription package limits.</p>';
            echo '</div></body></html>';
            exit;
        }

        // Check subscription expiry
        if (FeatureGate::isExpired($table['rest_id'])) {
            echo '<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><title>Service Unavailable</title></head>';
            echo '<body style="font-family:system-ui,sans-serif;text-align:center;padding:60px 20px;background:#0f172a;color:#e2e8f0;margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center">';
            echo '<div><div style="font-size:48px;margin-bottom:16px">⚠️</div>';
            echo '<h2 style="font-size:22px;font-weight:700;margin:0 0 8px;color:#fca5a5">Service Temporarily Unavailable</h2>';
            echo '<p style="color:#94a3b8;font-size:14px;margin:0">Online ordering is currently unavailable for this restaurant.<br>Please contact the staff for assistance.</p>';
            echo '</div></body></html>';
            exit;
        }

        // Check if QR Ordering is included in the package
        if (!FeatureGate::hasQrOrdering($table['rest_id'])) {
            echo '<!DOCTYPE html><html><head><meta name="viewport" content="width=device-width,initial-scale=1"><title>Service Unavailable</title></head>';
            echo '<body style="font-family:system-ui,sans-serif;text-align:center;padding:60px 20px;background:#0f172a;color:#e2e8f0;margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center">';
            echo '<div><div style="font-size:48px;margin-bottom:16px">⚠️</div>';
            echo '<h2 style="font-size:22px;font-weight:700;margin:0 0 8px;color:#fca5a5">Service Temporarily Unavailable</h2>';
            echo '<p style="color:#94a3b8;font-size:14px;margin:0">Online QR ordering is not included in this restaurant\'s active subscription package.</p>';
            echo '</div></body></html>';
            exit;
        }

        $cats = $db->prepare('SELECT * FROM categories WHERE restaurant_id = ? AND status="active" ORDER BY name');
        $cats->execute([$table['rest_id']]);
        $categories = $cats->fetchAll();

        $prods = $db->prepare('SELECT * FROM products WHERE restaurant_id = ? AND status="active" ORDER BY category_id, name');
        $prods->execute([$table['rest_id']]);
        $products = $prods->fetchAll();

        $cpns = $db->prepare('SELECT * FROM restaurant_coupons WHERE restaurant_id = ? AND (floor_id IS NULL OR floor_id = ?) AND status = "active" AND expiry_date >= DATE(NOW())');
        $cpns->execute([$table['rest_id'], $table['floor_id']]);
        $coupons = $cpns->fetchAll();

        $currency = FeatureGate::currency($table['rest_id']);

        // Fetch active/unpaid order if table is occupied
        $activeOrder = null;
        $activeOrderItems = [];
        if ($table['status'] === 'occupied') {
            $activeStmt = $db->prepare('SELECT * FROM orders WHERE table_id = ? AND payment_status = "unpaid" AND status != "voided" ORDER BY id DESC LIMIT 1');
            $activeStmt->execute([$table['id']]);
            $activeOrder = $activeStmt->fetch();

            if ($activeOrder) {
                $itemsStmt = $db->prepare('SELECT oi.*, p.name as product_name, p.image as product_image FROM order_items oi JOIN products p ON p.id = oi.product_id WHERE oi.order_id = ?');
                $itemsStmt->execute([$activeOrder['id']]);
                $activeOrderItems = $itemsStmt->fetchAll();
            }
        }

        require 'app/Views/qr/menu.php';
    }

    public function lookupCode() {
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);
        $code = trim($data['code'] ?? '');

        if (!$code || strlen($code) !== 6 || !ctype_digit($code)) {
            echo json_encode(['success' => false, 'message' => 'Please enter a valid 6-digit code.']);
            exit;
        }

        $db = getDB();
        $stmt = $db->prepare('SELECT t.id, t.table_code, t.restaurant_id, r.name as restaurant_name FROM tables t JOIN restaurants r ON r.id = t.restaurant_id WHERE t.table_code = ? LIMIT 1');
        $stmt->execute([$code]);
        $table = $stmt->fetch();

        if (!$table) {
            echo json_encode(['success' => false, 'message' => 'Code not found. Please check and try again.']);
            exit;
        }

        // Check if table is within allowed subscription limits
        $allowedTableIds = FeatureGate::getAllowedTableIds($table['restaurant_id']);
        if (!in_array($table['id'], $allowedTableIds)) {
            echo json_encode(['success' => false, 'message' => 'This table code is currently disabled under the restaurant\'s package limits.']);
            exit;
        }

        if (!FeatureGate::hasQrOrdering($table['restaurant_id'])) {
            echo json_encode(['success' => false, 'message' => 'Online QR ordering is not enabled for this restaurant.']);
            exit;
        }

        echo json_encode([
            'success' => true,
            'restaurant' => $table['restaurant_name'],
            'redirect' => BASE_URL . '/menu?code=' . $code
        ]);
        exit;
    }

    public function placeOrder() {
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);

        if (!$data || empty($data['items']) || empty($data['table_id'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid order data.']);
            exit;
        }

        $db = getDB();
        $tbl = $db->prepare('SELECT * FROM tables WHERE id = ? AND qr_code = ? LIMIT 1');
        $tbl->execute([$data['table_id'], $data['qr_token'] ?? $data['qr_code'] ?? '']);
        $table = $tbl->fetch();

        if (!$table) {
            echo json_encode(['success' => false, 'message' => 'Invalid table or QR.']);
            exit;
        }

        // Check if table is within allowed subscription limits
        $allowedTableIds = FeatureGate::getAllowedTableIds($table['restaurant_id']);
        if (!in_array($table['id'], $allowedTableIds)) {
            echo json_encode(['success' => false, 'message' => 'This table is currently disabled under the restaurant\'s package limits.']);
            exit;
        }

        if (FeatureGate::isExpired($table['restaurant_id'])) {
            echo json_encode(['success' => false, 'message' => 'Online ordering is temporarily suspended for this restaurant.']);
            exit;
        }

        if (!FeatureGate::hasQrOrdering($table['restaurant_id'])) {
            echo json_encode(['success' => false, 'message' => 'Online QR ordering is not enabled for this restaurant.']);
            exit;
        }

        // Block ordering if table has active unpaid order
        $activeCheck = $db->prepare('SELECT COUNT(*) FROM orders WHERE table_id = ? AND payment_status = "unpaid" AND status != "voided"');
        $activeCheck->execute([$table['id']]);
        if ($activeCheck->fetchColumn() > 0) {
            echo json_encode(['success' => false, 'message' => 'This table has an active order. Please contact the cashier to add more items.']);
            exit;
        }

        $db->beginTransaction();
        try {
            $subtotal = 0;
            foreach ($data['items'] as $item) { $subtotal += ($item['price'] * $item['quantity']); }

            // Get settings for tax
            $settingsStmt = $db->prepare('SELECT setting_key, setting_value FROM restaurant_settings WHERE restaurant_id = ?');
            $settingsStmt->execute([$table['restaurant_id']]);
            $rows = $settingsStmt->fetchAll();
            $s = [];
            foreach ($rows as $r) { $s[$r['setting_key']] = $r['setting_value']; }
            $tax_rate = floatval($s['tax_rate'] ?? 5);

            $coupon_discount = 0;
            $coupon_code = !empty($data['coupon_code']) ? strtoupper(trim($data['coupon_code'])) : null;
            if ($coupon_code) {
                $cpn = $db->prepare('SELECT * FROM restaurant_coupons WHERE restaurant_id = ? AND (floor_id IS NULL OR floor_id = ?) AND code = ? AND status="active" AND expiry_date >= DATE(NOW()) LIMIT 1');
                $cpn->execute([$table['restaurant_id'], $table['floor_id'], $coupon_code]);
                $coupon = $cpn->fetch();
                if ($coupon) {
                    require_once 'app/Helpers/CouponHelper.php';
                    $coupon_discount = CouponHelper::calculateDiscount($coupon, $data['items'], $subtotal);
                } else {
                    echo json_encode(['success' => false, 'message' => 'Coupon not found or expired.']);
                    $db->rollBack();
                    exit;
                }
            }

            $tax = ($subtotal - $coupon_discount) * ($tax_rate / 100);
            $total = max(0, $subtotal - $coupon_discount + $tax);

            // Assign to an active session/cashier if available to maintain sequence flow
            $session_id = null;
            $cashier_id = null;
            $activeStmt = $db->prepare('SELECT id, user_id FROM sessions WHERE restaurant_id = ? AND status = "open" ORDER BY id DESC LIMIT 1');
            $activeStmt->execute([$table['restaurant_id']]);
            $activeSession = $activeStmt->fetch(\PDO::FETCH_ASSOC);
            if ($activeSession) {
                $session_id = $activeSession['id'];
                $cashier_id = $activeSession['user_id'];
            }

            // Calculate next sequential order number for this restaurant
            $order_number = FeatureGate::getNextOrderNumber($table['restaurant_id'], $session_id, $cashier_id);

            $stmt = $db->prepare('INSERT INTO orders (restaurant_id, order_number, session_id, cashier_id, table_id, order_type, status, subtotal, discount, tax, total, notes, coupon_code, coupon_discount) VALUES (?, ?, ?, ?, ?, "dining", "pending", ?, ?, ?, ?, ?, ?, ?)');
            $stmt->execute([$table['restaurant_id'], $order_number, $session_id, $cashier_id, $table['id'], $subtotal, $coupon_discount, $tax, $total, $data['notes'] ?? '', $coupon_code, $coupon_discount]);
            $order_id = $db->lastInsertId();

            $itemStmt = $db->prepare('INSERT INTO order_items (order_id, product_id, quantity, price, subtotal) VALUES (?, ?, ?, ?, ?)');
            foreach ($data['items'] as $item) {
                $itemStmt->execute([$order_id, $item['id'], $item['quantity'], $item['price'], $item['price'] * $item['quantity']]);
            }

            $db->prepare('UPDATE tables SET status = "occupied" WHERE id = ?')->execute([$table['id']]);
            $db->commit();
            echo json_encode(['success' => true, 'message' => 'Order placed! Staff notified.', 'order_id' => $order_id, 'order_number' => $order_number]);
        } catch (\Exception $e) {
            $db->rollBack();
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
        exit;
    }

    public function manage() {
        if (!isset($_SESSION['user_id']) || ($_SESSION['role'] !== 'admin' && $_SESSION['role'] !== 'superadmin')) {
            header('Location: /restpo/login'); exit;
        }

        $db = getDB();
        $rest_id = $_SESSION['restaurant_id'];
        FeatureGate::enforceQrOrdering($rest_id);

        // Restore context from cookie if available
        if (!isset($_SESSION['selected_cashier_id_qr']) && isset($_COOKIE['selected_cashier_id_qr'])) {
            $_SESSION['selected_cashier_id_qr'] = $_COOKIE['selected_cashier_id_qr'];
            if (isset($_COOKIE['selected_cashier_name_qr'])) {
                $_SESSION['selected_cashier_name_qr'] = $_COOKIE['selected_cashier_name_qr'];
            }
        }

        // Admin / Superadmin Cashier selection logic for QR
        if (isset($_GET['cashier_id'])) {
            if ($_GET['cashier_id'] === 'change') {
                unset($_SESSION['selected_cashier_id_qr']);
                unset($_SESSION['selected_cashier_name_qr']);
                setcookie('selected_cashier_id_qr', '', time() - 3600, '/');
                setcookie('selected_cashier_name_qr', '', time() - 3600, '/');
                header('Location: /restpo/admin/qr');
                exit;
            }

            if ($_GET['cashier_id'] === 'all') {
                $_SESSION['selected_cashier_id_qr'] = 'all';
                setcookie('selected_cashier_id_qr', 'all', time() + (86400 * 30), '/');
                setcookie('selected_cashier_name_qr', 'All Tables', time() + (86400 * 30), '/');
                header('Location: /restpo/admin/qr');
                exit;
            }

            $cId = intval($_GET['cashier_id']);
            $cStmt = $db->prepare('SELECT id, name FROM users WHERE id = ? AND restaurant_id = ? AND role = "cashier" AND status = "active" LIMIT 1');
            $cStmt->execute([$cId, $rest_id]);
            $selected_cashier = $cStmt->fetch();
            if ($selected_cashier) {
                $_SESSION['selected_cashier_id_qr'] = $selected_cashier['id'];
                $_SESSION['selected_cashier_name_qr'] = $selected_cashier['name'];
                setcookie('selected_cashier_id_qr', $selected_cashier['id'], time() + (86400 * 30), '/');
                setcookie('selected_cashier_name_qr', $selected_cashier['name'], time() + (86400 * 30), '/');
            }
            header('Location: /restpo/admin/qr');
            exit;
        }

        if (!isset($_SESSION['selected_cashier_id_qr'])) {
            // Fetch active cashiers and their active session count (open sessions)
            $cStmt = $db->prepare('
                SELECT u.id, u.name, u.email,
                       (SELECT COUNT(*) FROM sessions s WHERE s.user_id = u.id AND s.status = "open" AND s.restaurant_id = ?) as has_active_session
                FROM users u
                WHERE u.restaurant_id = ? AND u.role = "cashier" AND u.status = "active"
                ORDER BY u.name
            ');
            $cStmt->execute([$rest_id, $rest_id]);
            $cashiers = $cStmt->fetchAll();

            $target_page = 'qr';
            require_once 'app/Views/admin/cashier_select.php';
            exit;
        }

        $pageTitle = 'QR Code Manager';

        // Auto-generate tokens for tables that lack one
        $missing = $db->prepare('SELECT id FROM tables WHERE restaurant_id = ? AND (qr_code IS NULL OR qr_code = "")');
        $missing->execute([$rest_id]);
        foreach ($missing->fetchAll() as $t) {
            $db->prepare('UPDATE tables SET qr_code = ? WHERE id = ?')
               ->execute([bin2hex(random_bytes(16)), $t['id']]);
        }

        // Auto-generate 6-digit table codes for tables that lack one
        $missingCode = $db->prepare('SELECT id FROM tables WHERE restaurant_id = ? AND (table_code IS NULL OR table_code = "")');
        $missingCode->execute([$rest_id]);
        foreach ($missingCode->fetchAll() as $t) {
            $code = '';
            while (true) {
                $candidate = sprintf('%06d', mt_rand(100000, 999999));
                $chk = $db->prepare('SELECT COUNT(*) FROM tables WHERE table_code = ?');
                $chk->execute([$candidate]);
                if ($chk->fetchColumn() == 0) {
                    $code = $candidate;
                    break;
                }
            }
            $db->prepare('UPDATE tables SET table_code = ? WHERE id = ?')
               ->execute([$code, $t['id']]);
        }

        // Fetch restaurant details for QR printing
        $rStmt = $db->prepare('SELECT name, logo, phone, address, slug FROM restaurants WHERE id = ?');
        $rStmt->execute([$rest_id]);
        $restaurant = $rStmt->fetch();

        if ($_SESSION['selected_cashier_id_qr'] === 'all') {
            $floors = $db->prepare('SELECT * FROM floors WHERE restaurant_id = ? ORDER BY id');
            $floors->execute([$rest_id]);
            $floors = $floors->fetchAll();

            $tables = $db->prepare('SELECT t.*, f.name as floor_name FROM tables t JOIN floors f ON f.id = t.floor_id WHERE t.restaurant_id = ? ORDER BY f.id, t.name');
            $tables->execute([$rest_id]);
            $tables = $tables->fetchAll();
        } else {
            $cashier_id = intval($_SESSION['selected_cashier_id_qr']);
            $floors = $db->prepare('SELECT * FROM floors WHERE restaurant_id = ? AND cashier_id = ? ORDER BY id');
            $floors->execute([$rest_id, $cashier_id]);
            $floors = $floors->fetchAll();

            $tables = $db->prepare('SELECT t.*, f.name as floor_name FROM tables t JOIN floors f ON f.id = t.floor_id WHERE t.restaurant_id = ? AND f.cashier_id = ? ORDER BY f.id, t.name');
            $tables->execute([$rest_id, $cashier_id]);
            $tables = $tables->fetchAll();
        }

        $baseUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']==='on' ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'];

        ob_start();
        require 'app/Views/qr/manage.php';
        $content = ob_get_clean();
        require 'app/Views/layouts/admin.php';
    }

    public function submitFeedback() {
        header('Content-Type: application/json');
        $data = json_decode(file_get_contents('php://input'), true);

        if (!$data || empty($data['table_id']) || empty($data['type']) || empty($data['message'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid feedback data.']);
            exit;
        }

        $type = $data['type'];
        if (!in_array($type, ['compliment', 'complaint'])) {
            echo json_encode(['success' => false, 'message' => 'Invalid feedback type.']);
            exit;
        }

        $message = trim($data['message']);
        if (strlen($message) < 5) {
            echo json_encode(['success' => false, 'message' => 'Feedback message is too short (min 5 chars).']);
            exit;
        }

        $db = getDB();
        $stmt = $db->prepare('SELECT * FROM tables WHERE id = ? LIMIT 1');
        $stmt->execute([$data['table_id']]);
        $table = $stmt->fetch();

        if (!$table) {
            echo json_encode(['success' => false, 'message' => 'Table not found.']);
            exit;
        }

        try {
            $customer_name = !empty($data['customer_name']) ? trim($data['customer_name']) : null;
            $phone = !empty($data['phone']) ? trim($data['phone']) : null;

            $ins = $db->prepare('INSERT INTO feedbacks (restaurant_id, floor_id, table_id, type, message, customer_name, phone) VALUES (?, ?, ?, ?, ?, ?, ?)');
            $ins->execute([
                $table['restaurant_id'],
                $table['floor_id'],
                $table['id'],
                $type,
                $message,
                $customer_name,
                $phone
            ]);
            echo json_encode(['success' => true, 'message' => 'Thank you for your feedback!']);
        } catch (\Exception $e) {
            echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
        }
        exit;
    }
}
