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

if(!isset($_GET['tab_id'])){
    echo "<script>alert('No tab selected'); window.location='bar_tabs_list.php';</script>";
    exit;
}

$tab_id = intval($_GET['tab_id']);

// Load tab info
$tab = $conn->query("SELECT bt.*, g.name as guest_name, c.name as customer_name 
                     FROM bar_tabs bt
                     LEFT JOIN guests g ON bt.guest_id = g.id
                     LEFT JOIN customers c ON bt.customer_id = c.id
                     WHERE bt.id=$tab_id")->fetch_assoc();

if(!$tab){
    echo "<script>alert('Tab not found'); window.location='bar_tabs_list.php';</script>";
    exit;
}

$person = $tab['guest_name'] ?: $tab['customer_name'] ?: 'Walk-in';
?>

<div class="container mt-4">
     <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
    </div>
<h4>🍺 Tab Details: <?= htmlspecialchars($tab['tab_no']) ?></h4>
<p><strong>Bartender:</strong> <?= htmlspecialchars($tab['waiter']) ?> | 
<strong>Guest / Customer:</strong> <?= htmlspecialchars($person) ?></p>
<p><strong>Status:</strong> <?= htmlspecialchars($tab['status']) ?> | 
<strong>Created At:</strong> <?= date("d-M-Y H:i", strtotime($tab['created_at'])) ?>
<?php if($tab['status']=='Closed'): ?>
| <strong>Closed At:</strong> <?= date("d-M-Y H:i", strtotime($tab['closed_at'])) ?>
<?php endif; ?>
</p>
<hr>

<?php
// Fetch items
$sale_items = [];
$total_sub = 0;
$total_vat = 0;
$grand_total = 0;

if($tab['status']=='Closed'){
    // Fetch sale info
    $sale = $conn->query("SELECT * FROM sales WHERE tab_id=$tab_id LIMIT 1")->fetch_assoc();
    if($sale){
        $sale_items_res = $conn->query("SELECT si.*, p.name, p.sku 
                                        FROM sale_items si 
                                        LEFT JOIN products p ON si.product_id=p.id
                                        WHERE si.sale_id={$sale['id']}");
        while($si = $sale_items_res->fetch_assoc()){
            $sale_items[] = $si;
            $total_sub += $si['price'] * $si['qty'];
            $total_vat += $si['vat'];
        }
        $grand_total = $total_sub + $total_vat - $sale['discount'];
    }
} else {
    // Tab is open, load cart from session if current
    if(isset($_SESSION['current_bar_tab']) && $_SESSION['current_bar_tab']==$tab_id && isset($_SESSION['bar_cart'])){
        foreach($_SESSION['bar_cart'] as $c){
            $line_total = $c['price'] * $c['qty'];
            $vat = $line_total * ($c['vat_rate']/100);
            $sale_items[] = [
                'name'=>$c['name'],
                'sku'=>$c['sku'],
                'price'=>$c['price'],
                'qty'=>$c['qty'],
                'vat'=>$vat,
                'total'=>$line_total+$vat
            ];
            $total_sub += $line_total;
            $total_vat += $vat;
        }
        $grand_total = $total_sub + $total_vat;
    }
}
?>

<h5>Items in Tab</h5>
<table class="table table-bordered table-striped">
<thead class="bg-dark text-white">
<tr>
<th>#</th><th>SKU</th><th>Item</th><th>Price</th><th>Qty</th><th>VAT</th><th>Total</th>
</tr>
</thead>
<tbody>
<?php
if(count($sale_items)==0){
    echo "<tr><td colspan='7' class='text-center text-muted'>No items in this tab</td></tr>";
} else {
    $i=1;
    foreach($sale_items as $si){
        $price = number_format($si['price'],2);
        $qty = $si['qty'];
        $vat = number_format($si['vat'],2);
        $total = number_format(($si['price']*$si['qty'])+$si['vat'],2);
        $sku = $si['sku'] ?? '';
        $name = $si['name'];
        echo "<tr>
        <td>$i</td>
        <td>$sku</td>
        <td>$name</td>
        <td>$price</td>
        <td>$qty</td>
        <td>$vat</td>
        <td>$total</td>
        </tr>";
        $i++;
    }
}
?>
</tbody>
<tfoot>
<tr><th colspan="5" class="text-end">Subtotal:</th><th colspan="2">MK <?= number_format($total_sub,2) ?></th></tr>
<tr><th colspan="5" class="text-end">VAT:</th><th colspan="2">MK <?= number_format($total_vat,2) ?></th></tr>
<?php if(isset($sale['discount'])): ?>
<tr><th colspan="5" class="text-end">Discount:</th><th colspan="2">MK <?= number_format($sale['discount'],2) ?></th></tr>
<?php endif; ?>
<tr><th colspan="5" class="text-end">Grand Total:</th><th colspan="2">MK <?= number_format($grand_total,2) ?></th></tr>
</tfoot>
</table>

<?php if($tab['status']=='Closed'): ?>
<a href="bar_tab_reopen.php?tab_id=<?= $tab_id ?>" class="btn btn-warning"
   onclick="return confirm('Are you sure you want to reopen this tab?');">Reopen Tab</a>
<?php endif; ?>

<?php if(count($sale_items) > 0): ?>
<form method="POST" action="bar_tab_invoice.php" target="_blank" class="d-inline">
    <input type="hidden" name="tab_id" value="<?= $tab_id ?>">
    <button type="submit" class="btn btn-info">
        <i class="fa fa-file-invoice"></i> Generate Invoice
    </button>
</form>
<?php endif; ?>


<a href="bar_tab_pos.php" class="btn btn-secondary">Back to Tabs</a>

</div>

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