<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include('config/constants.php');

$msg = '';
$success = false;

// عند إرسال الطلب
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $customer_name = mysqli_real_escape_string($conn, $_POST['customer_name']);
    $customer_contact = mysqli_real_escape_string($conn, $_POST['customer_contact']);
    $customer_address = mysqli_real_escape_string($conn, $_POST['customer_address']);
    $order_type = 'delivery';
    $status = 'Pending';
    $order_date = date('Y-m-d H:i:s');

    // المتغيرات
    $foods = isset($_POST['food']) ? $_POST['food'] : array();
    $qtys = isset($_POST['qty']) ? $_POST['qty'] : array();
    $total = 0;
    $items = array();

    // الآن فقط الاسم واختيار صنف مطلوب
    if (empty($foods) || empty($customer_name)) {
        $msg = "<div class='msg error'>يجب ملء اسم الزبون واختيار صنف واحد على الأقل.</div>";
    } else {
        $qty_counter = 0;
        foreach ($foods as $food_id) {
            $food_id = intval($food_id);
            $qty = isset($qtys[$qty_counter]) ? max(1, intval($qtys[$qty_counter])) : 1;
            $qty_counter++;

            $food_result = mysqli_query($conn, "SELECT * FROM tbl_food WHERE id=$food_id LIMIT 1");
            $food_data = mysqli_fetch_assoc($food_result);
            $food_name = $food_data['title'];
            $price = $food_data['price'];
            $subtotal = $price * $qty;
            $total += $subtotal;
            $items[] = "$food_name x $qty";
        }
        $food_list = implode(', ', $items);

        // إضافة الطلب لجدول الطلبات
        $sql = "INSERT INTO tbl_order (food, price, qty, total, order_date, status, customer_name, customer_contact, customer_address, order_type)
                VALUES ('$food_list', '$price', '$qty', '$total', '$order_date', '$status', '$customer_name', '$customer_contact', '$customer_address', '$order_type')";
        if (mysqli_query($conn, $sql)) {
            $order_id = mysqli_insert_id($conn);
            mysqli_query($conn, "INSERT INTO kitchen_orders (order_id) VALUES ($order_id)");
            $msg = "<div class='msg success'>تم تسجيل الطلب بنجاح وسيتم إرساله للمطبخ والكاشير مع توضيح أنه دليفري!</div>";
            $success = true;
        } else {
            $msg = "<div class='msg error'>حدث خطأ أثناء حفظ الطلب. حاول مجدداً!</div>";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <title>إضافة طلب دليفري</title>
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@500;700&display=swap" rel="stylesheet">
    <style>
        body {
            background: #f4f7fb;
            font-family: 'Cairo', Arial, sans-serif;
            margin: 0;
            padding: 0;
        }
        .delivery-form-container {
            max-width: 480px;
            background: #fff;
            margin: 50px auto 0 auto;
            border-radius: 18px;
            box-shadow: 0 4px 32px #aeaeae25;
            padding: 38px 24px 26px 24px;
        }
        h2 {
            color: #1976d2;
            font-weight: bold;
            font-size: 2rem;
            margin-bottom: 18px;
            letter-spacing: 1px;
            text-align: center;
        }
        label {
            display: block;
            margin-bottom: 6px;
            color: #222b45;
            font-weight: 500;
            font-size: 1rem;
            margin-top: 15px;
        }
        input[type="text"], input[type="number"] {
            width: 100%;
            padding: 10px 13px;
            margin-bottom: 9px;
            border-radius: 7px;
            border: 1.5px solid #d5e1ef;
            font-size: 1.06rem;
            transition: border 0.17s;
        }
        input[type="text"]:focus, input[type="number"]:focus {
            border-color: #1976d2;
            outline: none;
        }
        .foods-list {
            background: #f8fafb;
            border-radius: 10px;
            padding: 13px 10px 4px 10px;
            margin-bottom: 13px;
            max-height: 260px;
            overflow-y: auto;
            box-shadow: 0 1px 6px #ccc1;
        }
        .food-row {
            display: flex;
            align-items: center;
            margin-bottom: 8px;
            gap: 10px;
        }
        .food-row label {
            margin: 0;
            flex: 1;
            font-size: 1rem;
            color: #273043;
        }
        .food-row input[type="checkbox"] {
            accent-color: #1976d2;
            width: 17px;
            height: 17px;
            cursor: pointer;
        }
        .food-row input[type="number"] {
            width: 60px;
            margin-bottom: 0;
            padding: 7px 6px;
            font-size: 1rem;
        }
        .submit-btn {
            background: linear-gradient(90deg, #1976d2 70%, #328de3 100%);
            color: #fff;
            border: none;
            border-radius: 9px;
            font-size: 1.2rem;
            font-weight: bold;
            width: 100%;
            padding: 13px;
            margin-top: 22px;
            cursor: pointer;
            box-shadow: 0 3px 18px #1976d22a;
            transition: background 0.15s;
        }
        .submit-btn:hover {
            background: linear-gradient(90deg, #1153a2 60%, #217dbb 100%);
        }
        .msg {
            padding: 11px 15px;
            border-radius: 7px;
            margin-bottom: 20px;
            margin-top: -8px;
            text-align: center;
            font-weight: bold;
            font-size: 1.05rem;
        }
        .msg.success { background: #e1f8e5; color: #197145; border: 1.5px solid #4caf50; }
        .msg.error { background: #ffe6e6; color: #d81b1b; border: 1.5px solid #ff7676; }
        .foods-list .food-row[disabled] label { color: #bbb; }
        @media (max-width: 600px) {
            .delivery-form-container { max-width: 98vw; padding: 13px 6vw; }
        }
        .add-another-btn {
            background:#1976d2;
            color:#fff;
            padding:11px 30px;
            border-radius:8px;
            text-decoration:none;
            font-size:1.1rem;
            font-weight:bold;
            display:inline-block;
            box-shadow:0 3px 16px #1976d255;
            margin:18px auto 0 auto;
        }
        .add-another-btn:hover {
            background:#1255a8;
            color:#fff;
        }
    </style>
    <script>
    function toggleQtyInput(chk, index) {
        var qty = document.getElementById('qty-' + index);
        qty.disabled = !chk.checked;
        if(!chk.checked) qty.value = 1;
    }
    </script>
</head>
<body>
    <div class="delivery-form-container">
        <h2>طلب دليفري جديد</h2>
        <?php echo $msg; ?>
        <?php if (!$success) { ?>
        <form method="post" autocomplete="off">
            <label>اسم الزبون:</label>
            <input type="text" name="customer_name" required>

            <label>رقم الهاتف:</label>
            <input type="text" name="customer_contact">

            <label>العنوان:</label>
            <input type="text" name="customer_address">

            <label>الأطعمة المطلوبة:</label>
            <div class="foods-list">
            <?php
            $foods = mysqli_query($conn, "SELECT * FROM tbl_food WHERE active='Yes'");
            $i = 0;
            while ($row = mysqli_fetch_assoc($foods)) {
                echo "<div class='food-row'>";
                echo "<input type='checkbox' name='food[]' value='{$row['id']}' id='food-{$i}' onclick='toggleQtyInput(this, {$i})'>";
                echo "<label for='food-{$i}'>{$row['title']} <span style='color:#1976d2;font-size:13px;'>({$row['price']} د.ع)</span></label>";
                echo "<input type='number' name='qty[]' id='qty-{$i}' min='1' value='1' disabled>";
                echo "</div>";
                $i++;
            }
            ?>
            </div>
            <button type="submit" class="submit-btn">إرسال الطلب</button>
        </form>
        <?php } ?>
        <?php if ($success) { ?>
        <div style="text-align:center;margin-top:20px;">
            <a href="add-delivery-order.php" class="add-another-btn">إضافة طلب دليفري آخر</a>
        </div>
        <?php } ?>
    </div>
</body>
</html>
