<?php
include 'includes/auth.php';
include 'db.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
$tab = $conn->query("SELECT * FROM bar_tabs WHERE id=$tab_id")->fetch_assoc();

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

if($tab['status'] != 'Closed'){
    echo "<script>alert('This tab is not closed.'); window.location='bar_tab_details.php?tab_id=$tab_id';</script>";
    exit;
}

// Reopen tab
$conn->query("UPDATE bar_tabs SET status='Open', closed_at=NULL WHERE id=$tab_id");

// Optional: Restore cart items from sale to session for POS
$sale = $conn->query("SELECT * FROM sales WHERE tab_id=$tab_id LIMIT 1")->fetch_assoc();
$_SESSION['current_bar_tab'] = $tab_id;
$_SESSION['bar_cart'] = [];

if($sale){
    $items = $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($i = $items->fetch_assoc()){
        $_SESSION['bar_cart'][] = [
            'id'=>$i['product_id'],
            'name'=>$i['name'],
            'sku'=>$i['sku'],
            'price'=>$i['price'],
            'qty'=>$i['qty'],
            'vat_rate'=>($i['vat'] / ($i['price']*$i['qty']))*100
        ];
    }
}

// Delete original sale to allow reopening (optional)
$conn->query("DELETE FROM sale_items WHERE sale_id={$sale['id']}");
$conn->query("DELETE FROM sales WHERE id={$sale['id']}");

echo "<script>alert('Tab reopened successfully!'); window.location='bar_tab_details.php?tab_id=$tab_id';</script>";
exit;
?>
