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

// ================= CREATE NEW TAB =================
if(isset($_POST['new_tab'])){
    $tab_no = $conn->real_escape_string($_POST['tab_no']);
    $guest_name = $conn->real_escape_string($_POST['guest_name']);
    $waiter = $conn->real_escape_string($_SESSION['username']);

    $conn->query("INSERT INTO bar_tabs(tab_no, guest_id, waiter, status, created_at)
                  VALUES('$tab_no', NULL, '$waiter', 'Open', NOW())");
    echo "<script>alert('New Tab Created!'); window.location='bar_tabs_list.php';</script>";
    exit;
}

// ================== FETCH TABS ===================
$tabs = $conn->query("SELECT * FROM bar_tabs ORDER BY created_at DESC");
?>

<div class="container mt-4">
    <!-- ================= WELCOME MESSAGE ================= -->
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>
<h4>🍺 Bar Tabs</h4>
<hr>

<!-- Create New Tab -->
<div class="card mb-4">
<div class="card-header bg-success text-white">Create New Tab</div>
<div class="card-body">
<form method="POST" class="row g-3">
<div class="col-md-4">
<label>Tab Number</label>
<input type="text" name="tab_no" class="form-control" placeholder="Tab #123" required>
</div>
<div class="col-md-4">
<label>Guest Name (optional)</label>
<input type="text" name="guest_name" class="form-control" placeholder="Guest name">
</div>
<div class="col-md-4 mt-4">
<button type="submit" name="new_tab" class="btn btn-success w-100"><i class="fa fa-plus"></i> Create Tab</button>
</div>
</form>
</div>
</div>

<!-- List All Tabs -->
<div class="card mb-4">
<div class="card-header bg-dark text-white">Active Tabs</div>
<div class="card-body">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>#</th>
<th>Tab Number</th>
<th>Guest</th>
<th>Bartender</th>
<th>Status</th>
<th>Created At</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$i=1;
while($tab=$tabs->fetch_assoc()):
?>
<tr>
<td><?= $i ?></td>
<td><?= htmlspecialchars($tab['tab_no']) ?></td>
<td><?= $tab['guest_id'] ? 'Guest #' . $tab['guest_id'] : 'Walk-in' ?></td>
<td><?= htmlspecialchars($tab['waiter']) ?></td>
<td>
<?php if($tab['status']=='Open'): ?>
<span class="badge bg-success">Open</span>
<?php else: ?>
<span class="badge bg-secondary">Closed</span>
<?php endif; ?>
</td>
<td><?= date("d-M-Y H:i", strtotime($tab['created_at'])) ?></td>
<td>
<?php if($tab['status']=='Open'): ?>
<a href="bar_tab_pos.php?tab_id=<?= $tab['id'] ?>" class="btn btn-primary btn-sm">Open POS</a>
<?php else: ?>
<button class="btn btn-secondary btn-sm" disabled>Closed</button>
<?php endif; ?>
</td>
</tr>
<?php $i++; endwhile; ?>
</tbody>
</table>
</div>
</div>

</div>

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