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

/* =========================
   CORE
========================= */
require_once __DIR__ . "/../includes/db.php";
require_once __DIR__ . "/../includes/functions.php";

/* =========================
   RESTAURANT BY FOLDER
========================= */
$folder = basename(dirname(__FILE__));
$restaurant = get_restaurant($folder);
if(!$restaurant) die("Restaurant not found");
$restaurant_id = $restaurant['id'];

/* =========================
   LANGUAGE (FROM URL ONLY)
========================= */
$lang = $_GET['lang'] ?? 'ar';
if(!in_array($lang,['ar','en','ku'])) $lang = 'ar';
$dir = ($lang === 'ar') ? 'rtl' : 'ltr';
$tr  = require __DIR__."/lang/$lang.php";

/* =========================
   SETTINGS (TIME)
========================= */
$settings_rows = fetch_all("
    SELECT from_time, to_time, slot_minutes
    FROM reservation_settings
    WHERE restaurant_id=? AND active=1
    ORDER BY from_time ASC
", [$restaurant_id]);

function time_slots_range($from, $to, $step){
    $out = [];
    $s = strtotime($from);
    $e = strtotime($to);
    while($s < $e){
        $out[] = date("H:i", $s);
        $s = strtotime("+$step minutes", $s);
    }
    return $out;
}

$slots = [];
foreach($settings_rows as $row){
    $range = time_slots_range(
        $row['from_time'],
        $row['to_time'],
        (int)$row['slot_minutes']
    );
    $slots = array_merge($slots, $range);
}

$slots = array_unique($slots);
sort($slots);

/* =========================
   MENU DATA
========================= */
$categories = fetch_all("
    SELECT * FROM categories
    WHERE restaurant_id=? AND active=1
    ORDER BY ordering ASC
",[$restaurant_id]);

$items = fetch_all("
    SELECT * FROM items
    WHERE restaurant_id=? AND active=1
    ORDER BY ordering ASC
",[$restaurant_id]);

$cat_items=[];
foreach($categories as $c){
    $cat_items[$c['id']] = [];
}
foreach($items as $i){
    if(isset($cat_items[$i['category_id']])){
        $cat_items[$i['category_id']][] = $i;
    }
}




/* =========================
   SUBMIT RESERVATION + EMAIL
========================= */
if (isset($_POST['submit_reservation'])) {

    $name  = trim($_POST['name'] ?? '');
    $phone = trim($_POST['phone'] ?? '');
    $date  = $_POST['date'] ?? '';
    $time  = $_POST['time'] ?? '';
    $items_selected = $_POST['items'] ?? [];

    if ($name === '' || $phone === '' || $date === '' || $time === '') {
        $error = $tr['fill_all'] ?? 'يرجى تعبئة جميع الحقول';
    } else {

        /* 1️⃣ إنشاء الحجز */
        db()->prepare("
            INSERT INTO reservations
            (restaurant_id, customer_name, customer_phone, reservation_date, reservation_time, status)
            VALUES (?,?,?,?,?,'pending')
        ")->execute([$restaurant_id, $name, $phone, $date, $time]);

        $res_id = (int)db()->lastInsertId();
        $total  = 0;
        $email_items = '';

        /* 2️⃣ الإيتمات */
        foreach ((array)$items_selected as $item_id => $qty) {
            $qty = (int)$qty;
            if ($qty < 1) continue;

            $item = fetch_one("
                SELECT base_price, name_ar, name_en, name_ku
                FROM items
                WHERE id=? AND restaurant_id=?
            ", [$item_id, $restaurant_id]);

            if (!$item) continue;

            $line = $item['base_price'] * $qty;
            $total += $line;

            db()->prepare("
                INSERT INTO reservation_items
                (reservation_id, item_id, qty, price)
                VALUES (?,?,?,?)
            ")->execute([$res_id, $item_id, $qty, $item['base_price']]);

            $item_name = $item["name_$lang"] ?: $item['name_ar'];
            $email_items .= "
                <tr>
                    <td>{$item_name}</td>
                    <td>{$qty}</td>
                    <td>".number_format($item['base_price'])." IQD</td>
                    <td>".number_format($line)." IQD</td>
                </tr>
            ";
        }

        /* 3️⃣ تحديث السعر */
        db()->prepare("UPDATE reservations SET total_price=? WHERE id=?")
            ->execute([$total, $res_id]);

        /* =========================
           4️⃣ SEND EMAIL (mail)
        ========================= */
        $to = $restaurant['folder_name'] . "@meta-qr.com";
        $subject = "New Reservation #{$res_id}";

        $headers  = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type: text/html; charset=UTF-8\r\n";
        $headers .= "From: Meta QR <support@meta-qr.com>\r\n";

        $message = "
            <h2>New Reservation</h2>
            <p><b>ID:</b> #{$res_id}</p>
            <p><b>Name:</b> {$name}</p>
            <p><b>Phone:</b> {$phone}</p>
            <p><b>Date:</b> {$date}</p>
            <p><b>Time:</b> {$time}</p>

            <table border='1' cellpadding='8' cellspacing='0' width='100%'>
                <tr>
                    <th>Item</th>
                    <th>Qty</th>
                    <th>Price</th>
                    <th>Total</th>
                </tr>
                {$email_items}
            </table>

            <h3>Total: ".number_format($total)." IQD</h3>
        ";

        @mail($to, $subject, $message, $headers, "-f support@meta-qr.com");

        /* 5️⃣ تحويل */
        header("Location: reservation_success.php?id={$res_id}&lang={$lang}");
        exit;
    }
}


?>
<!DOCTYPE html>
<html lang="<?= $lang ?>" dir="<?= $dir ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?= $tr['reservation'] ?></title>

<style>
body{
    margin:0;background:#111;color:#fff;
    font-family:Tajawal,sans-serif
}
.container{
    max-width:900px;margin:auto;padding:20px
}
h1{color:#ff7a00}
.card{
    background:#1c1c1c;border:1px solid #333;
    border-radius:12px;padding:16px;margin-bottom:16px
}
input,select{
    width:100%;padding:10px;
    border-radius:8px;border:1px solid #444;
    background:#111;color:#fff
}
.btn{
    background:#ff7a00;color:#000;
    padding:14px;border:none;border-radius:10px;
    font-size:16px;width:100%;cursor:pointer
}
.error{
    background:#b00000;padding:12px;
    border-radius:8px;margin-bottom:10px;text-align:center
}

/* ACCORDION */
.category{
    border:1px solid #333;
    border-radius:12px;
    margin-bottom:12px;
    overflow:hidden
}
.cat-header{
    background:#1c1c1c;
    padding:14px;
    font-size:18px;
    font-weight:bold;
    display:flex;
    justify-content:space-between;
    cursor:pointer
}
.cat-body{display:none;padding:12px}

.item-row{
    border-bottom:1px solid #333;
    padding:10px 0
}
.item-info{
    display:flex;
    justify-content:space-between;
    margin-bottom:6px
}
.qty-box{
    display:flex;
    justify-content:flex-end;
    gap:8px;
    margin-top:6px
}
.qty-box button{
    width:32px;height:32px;
    border:none;border-radius:6px;
    background:#ff7a00;color:#000;
    font-size:18px
}
.qty-box input{
    width:50px;text-align:center
}
</style>
</head>

<body>
<div class="container">

<h1><?= $tr['reservation'] ?></h1>

<?php if(isset($error)): ?>
<div class="error"><?= $error ?></div>
<?php endif; ?>

<form method="post">

<div class="card">
<input type="text" name="name" placeholder="<?= $tr['name'] ?>" required>
<br><br>
<input type="text" name="phone" placeholder="<?= $tr['phone'] ?>" required>
</div>

<div class="card">
<input type="date" name="date" required>
<br><br>
<select name="time" required>
<?php foreach($slots as $s): ?>
<option value="<?= $s ?>"><?= $s ?></option>
<?php endforeach; ?>
</select>
</div>

<?php foreach($categories as $c): ?>
<div class="category">
    <div class="cat-header" onclick="toggleCat(this)">
        <?= $c["name_$lang"] ?: $c['name'] ?>
        <span>⌄</span>
    </div>
    <div class="cat-body">

    <?php foreach($cat_items[$c['id']] as $i): ?>
    <div class="item-row">
        <div class="item-info">
            <span><?= $i["name_$lang"] ?: $i['name'] ?></span>
            <span><?= number_format($i['base_price']) ?> IQD</span>
        </div>

        <?php
        $opts = fetch_all("
            SELECT * FROM item_options
            WHERE item_id=? AND active=1
        ",[$i['id']]);
        ?>

        <?php if($opts): ?>
        <select>
            <option><?= $tr['choose_option'] ?? 'اختر خيار' ?></option>
            <?php foreach($opts as $o): ?>
            <option><?= $o["name_$lang"] ?: $o['name'] ?></option>
            <?php endforeach; ?>
        </select>
        <?php endif; ?>

        <div class="qty-box">
            <button type="button" onclick="changeQty(this,-1)">−</button>
            <input type="number" name="items[<?= $i['id'] ?>]" value="0" min="0">
            <button type="button" onclick="changeQty(this,1)">+</button>
        </div>
    </div>
    <?php endforeach; ?>

    </div>
</div>
<?php endforeach; ?>

<button class="btn" name="submit_reservation">
<?= $tr['confirm_reservation'] ?>
</button>

</form>
</div>

<script>
function toggleCat(el){
    const b = el.nextElementSibling;
    b.style.display = b.style.display === "block" ? "none" : "block";
}
function changeQty(btn,step){
    const i = btn.parentElement.querySelector("input");
    let v = parseInt(i.value)||0;
    v += step;
    if(v < 0) v = 0;
    i.value = v;
}
</script>

</body>
</html>
