<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$username = $_SESSION['username'] ?? 'Bartender';

if(isset($_POST['create_tab'])){

    // ✅ Guest only (customers removed)
    $guest_id = intval($_POST['guest_id'] ?? 0);
    $waiter   = $conn->real_escape_string($_POST['waiter']);

    // Generate tab number
    $tab_no = "TAB".time();

    // Insert tab
    $conn->query("
        INSERT INTO bar_tabs(tab_no, guest_id, waiter, status, created_at)
        VALUES('$tab_no',".($guest_id ?: "NULL").",'$waiter','Open',NOW())
    ");

    $_SESSION['current_bar_tab'] = $conn->insert_id;
    $_SESSION['bar_cart'] = [];

    echo "<script>window.location='bar_tab_pos.php';</script>";
    exit;
}
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>

<button class="btn btn-secondary btn-custom" onclick="history.back()">
    <i class="fa fa-arrow-left"></i> Back
</button>

<h4>🍺 Open Bar Tab</h4>

<a href="bar_sale_list.php" class="btn btn-sm btn-primary">Bar Sales</a>
<a href="open_bar_tab.php" class="btn btn-sm btn-primary">Open Tab</a>
<a href="bar_tab_pos.php" class="btn btn-sm btn-primary">Tabs</a>

<hr>

<form method="POST" class="row g-3">

<!-- ✅ Bartender -->
<div class="col-md-4">
<label>Bartender</label>
<input type="text" name="waiter"
       value="<?= htmlspecialchars($username) ?>"
       class="form-control" required readonly>
</div>

<!-- ✅ Guest dropdown -->
<div class="col-md-4">
<label>Guest (Optional)</label>
<select name="guest_id" class="form-control">
<option value="">-- Walk-in --</option>

<?php
$c = $conn->query("SELECT * FROM guests WHERE status = 2 ORDER BY name");
while($row = $c->fetch_assoc()){
    echo "<option value='{$row['id']}'>".htmlspecialchars($row['name'])."</option>";
}
?>
</select>
</div>

<!-- ✅ Submit -->
<div class="col-md-12">
<button name="create_tab" class="btn btn-success w-100">
    <i class="fa fa-beer"></i> Open Bar Tab
</button>
</div>

</form>
</div>

<?php include 'includes/footer.php'; ?>
