<?php
ob_start(); // start output buffering
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

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

// ======== DEFINE BAR STORE ID ========
$bar_store_id = 1;    // Bar store ID
$department_id = 1;   // Only Bar department products

// ================= LOAD CURRENT TAB =================
if(isset($_GET['tab_id'])){
    $_SESSION['current_bar_tab'] = intval($_GET['tab_id']);
}

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

$tab_id = $_SESSION['current_bar_tab'];

// Get tab info
$tab_info = $conn->query("SELECT * FROM bar_tabs WHERE id=$tab_id")->fetch_assoc();

// Initialize cart
if(!isset($_SESSION['bar_cart'])) $_SESSION['bar_cart'] = [];

// ================== ADD PRODUCT TO CART ==================
if(isset($_POST['add_to_cart'])){
    $product_id = intval($_POST['product_id']);
    $qty = intval($_POST['qty']);

    // Get available stock from bar_requisition_items, filtered by department
    $stock = $conn->query("
        SELECT COALESCE(SUM(bri.quantity),0) AS quantity
        FROM bar_requisition_items bri
        JOIN product_stock ps 
            ON bri.product_id = ps.product_id 
            AND ps.department_id = $department_id
        WHERE bri.product_id = $product_id
    ")->fetch_assoc();

    $available_qty = $stock['quantity'] ?? 0;

    if($qty > $available_qty){
        echo "<script>alert('⚠️ Insufficient stock! Available: $available_qty');</script>";
    } else {
        // Fetch product info
        $product = $conn->query("SELECT * FROM products WHERE id=$product_id")->fetch_assoc();

        // Check if product is already in the cart
        $found = false;
        foreach($_SESSION['bar_cart'] as &$c){
            if($c['id'] == $product_id){ 
                $c['qty'] += $qty; 
                $found = true; 
                break;
            }
        }

        // If not in cart, add new entry
        if(!$found){
            $_SESSION['bar_cart'][] = [
                'id' => $product_id,
                'name' => $product['name'],
                'sku' => $product['sku'],
                'price' => $product['selling_price'],
                'qty' => $qty,
                'vat_rate' => $product['vat_rate']
            ];
        }
    }
}

// ================== REMOVE ITEM ==================
if(isset($_GET['remove'])){
    unset($_SESSION['bar_cart'][$_GET['remove']]);
    $_SESSION['bar_cart'] = array_values($_SESSION['bar_cart']);
    header("Location: bar_tab_pos_open.php");
    exit;
}

// ================== COMPLETE TAB SALE ==================
// ================== COMPLETE TAB SALE ==================
if(isset($_POST['complete_tab'])){
    $payment_method = $conn->real_escape_string($_POST['payment_method']);
    $discount = floatval($_POST['discount']);
    $customer_id = intval($_POST['customer_id'] ?? 0);
    $phone_number = $conn->real_escape_string($_POST['phone_number'] ?? '');

    $subtotal = 0; $total_vat = 0;
    foreach($_SESSION['bar_cart'] as $c){
        $line_total = $c['price'] * $c['qty'];
        $vat = $line_total * ($c['vat_rate']/100);
        $subtotal += $line_total;
        $total_vat += $vat;
    }
    $grand_total = $subtotal + $total_vat - $discount;

    // Insert sale with cashier info
    $created_by = $_SESSION['username'] ?? 'Bartender';
    $conn->query("INSERT INTO sales(total, vat_total, discount, payment_method, customer_id, phone_number, sale_date, store_id, tab_id, created_by) 
        VALUES($grand_total, $total_vat, $discount, '$payment_method', $customer_id, '$phone_number', NOW(), $bar_store_id, $tab_id, '$created_by')");
    $sale_id = $conn->insert_id;

    // Insert sale items and deduct stock from bar_requisition_items
    foreach($_SESSION['bar_cart'] as $c){
        $pid = $c['id']; 
        $price = $c['price']; 
        $qty = $c['qty']; 
        $vat = $price * $qty * ($c['vat_rate']/100);

        $conn->query("INSERT INTO sale_items(sale_id, product_id, price, qty, vat, store_id) 
                      VALUES($sale_id, $pid, $price, $qty, $vat, $bar_store_id)");

        // Deduct from bar_requisition_items (FIFO)
      // Deduct from bar_requisition_items (FIFO)
$remaining_qty = $qty;
$items = $conn->query("SELECT id, quantity FROM bar_requisition_items WHERE product_id=$pid ORDER BY id ASC");

while(($item = $items->fetch_assoc()) && $remaining_qty > 0){
    $deduct = min($item['quantity'], $remaining_qty);
    if($deduct > 0){
        $conn->query("UPDATE bar_requisition_items SET quantity = quantity - $deduct WHERE id = {$item['id']}");
        $remaining_qty -= $deduct;
    }
}

        // Log stock movement
        $conn->query("INSERT INTO stock_movements(product_id, from_store_id, to_store_id, quantity, movement_type) 
                      VALUES($pid, $bar_store_id, NULL, $qty, 'Bar Sale')");
    }

    // Loyalty points
    if($customer_id > 0){
        $points_earned = floor($grand_total/100);
        $conn->query("UPDATE guests SET loyalty_points = loyalty_points + $points_earned WHERE id=$customer_id");
        $conn->query("INSERT INTO loyalty_transactions(customer_id, points, reason, date)
                      VALUES($customer_id, $points_earned, 'Points from Tab Sale #$sale_id', NOW())");
    }

    // Close tab
    $conn->query("UPDATE bar_tabs SET status='Closed', closed_at=NOW() WHERE id=$tab_id");

    $_SESSION['bar_cart'] = [];
    unset($_SESSION['current_bar_tab']);

    echo "<script>alert('Tab sale completed!'); window.location='bar_tabs_list.php';</script>";
    exit;

    // ================== SEND EMAIL TO ADMINS ==================
    $admin_emails = ["giantplusmw@gmail.com", "rams.investments@gmail.com"];
    $subject = "New Bar Tab Sale Completed (Tab ID: $tab_id, Sale ID: $sale_id)";

    $email_message = '
    <html>
    <head>
      <title>Bar Tab Sale Completed</title>
      <style>
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; padding: 20px; }
        .container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        h2 { color: #2c3e50; }
        table { width: 100%; border-collapse: collapse; margin-top: 15px; }
        th, td { padding: 8px; border: 1px solid #ddd; text-align: left; }
        th { background-color: #2c3e50; color: white; }
      </style>
    </head>
    <body>
      <div class="container">
        <h2>Bar Tab Sale Completed</h2>
        <p>Sale ID: '.$sale_id.'</p>
        <p>Tab ID: '.$tab_id.'</p>
        <p>Cashier: '.htmlspecialchars($username).'</p>
        <p>Customer: '.($customer_id ? "ID $customer_id" : "Walk-in").'</p>
        <p>Payment Method: '.htmlspecialchars($payment_method).'</p>
        <p>Discount: MK '.number_format($discount,2).'</p>
        <p>Grand Total: MK '.number_format($grand_total,2).'</p>

        <h3>Items Sold</h3>
        <table>
          <thead>
            <tr><th>Item</th><th>Qty</th><th>Price (MK)</th><th>Total (MK)</th></tr>
          </thead>
          <tbody>';
          foreach($_SESSION['bar_cart'] as $c){
              $line_total = $c['price'] * $c['qty'];
              $email_message .= '<tr>
                  <td>'.htmlspecialchars($c['name']).'</td>
                  <td>'.$c['qty'].'</td>
                  <td>'.number_format($c['price'],2).'</td>
                  <td>'.number_format($line_total,2).'</td>
              </tr>';
          }
    $email_message .= '
          </tbody>
        </table>
      </div>
    </body>
    </html>';

    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= "From: cloud@gianterp.space" . "\r\n";

    foreach($admin_emails as $to){
        mail($to, $subject, $email_message, $headers);
    }
    // ========================================================

    $_SESSION['bar_cart'] = [];
    unset($_SESSION['current_bar_tab']);

    echo "<script>alert('Tab sale completed! Admins notified via email.'); window.location='bar_tabs_list.php';</script>";
    exit;
}
?>

<div class="container mt-4">
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>
    <button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>

    <h4>🍺 Tab POS: <?= htmlspecialchars($tab_info['tab_no']) ?></h4>
    <p>
        <strong>Bartender:</strong> <?= htmlspecialchars($tab_info['waiter']) ?> | 
        <strong>Guest / Customer:</strong> <?= htmlspecialchars($tab_info['guest_id'] ? 'Guest' : 'Walk-in') ?>
    </p>
    <hr>

    <!-- ADD PRODUCT -->
    <form method="POST" class="row g-3 mb-3">
        <div class="col-md-6">
            <label>Select Drink</label>
            <select name="product_id" class="form-control" required>
                <option value="">-- Select --</option>
                <?php
                $products = $conn->query("
                   SELECT 
    p.*, 
    COALESCE(SUM(
      CASE WHEN br.status = 'Approved' THEN bri.quantity ELSE 0 END
    ), 0) AS bar_qty
  FROM products p
  LEFT JOIN bar_requisition_items bri 
      ON p.id = bri.product_id
  LEFT JOIN bar_requisitions br
      ON bri.requisition_id = br.id
  LEFT JOIN product_stock ps
      ON p.id = ps.product_id 
      AND ps.department_id = 1
  GROUP BY p.id
  ORDER BY p.name ASC;
                ");
                while($p = $products->fetch_assoc()){
                    $available = $p['bar_qty'] ?? 0;
                    $disabled = $available <= 0 ? "disabled" : "";
                    echo "<option value='{$p['id']}' $disabled>{$p['name']} ({$p['sku']}) - MK {$p['selling_price']} - Stock: $available</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-3">
            <label>Qty</label>
            <input type="number" name="qty" value="1" min="1" class="form-control" required>
        </div>
        <div class="col-md-3 mt-4">
            <button type="submit" name="add_to_cart" class="btn btn-success w-100">Add to Tab</button>
        </div>
    </form>

    <!-- TAB CART -->
    <h5>Current Tab Cart</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><th>Action</th>
            </tr>
        </thead>
        <tbody>
        <?php
        $subtotal=0;$total_vat=0;
        foreach($_SESSION['bar_cart'] as $i=>$c){
            $line=$c['price']*$c['qty'];
            $vat=$line*($c['vat_rate']/100);
            $subtotal+=$line;$total_vat+=$vat;
            $total_line=$line+$vat;
            echo "<tr>
            <td>".($i+1)."</td>
            <td>{$c['sku']}</td>
            <td>{$c['name']}</td>
            <td>".number_format($c['price'],2)."</td>
            <td>{$c['qty']}</td>
            <td>".number_format($vat,2)."</td>
            <td>".number_format($total_line,2)."</td>
            <td><a href='bar_tab_pos_open.php?remove=$i' class='btn btn-danger btn-sm'>Remove</a></td>
            </tr>";
        }
        ?>
        </tbody>
        <tfoot>
            <tr><th colspan="5" class="text-end">Subtotal:</th><th colspan="3">MK <?= number_format($subtotal,2) ?></th></tr>
            <tr><th colspan="5" class="text-end">VAT:</th><th colspan="3">MK <?= number_format($total_vat,2) ?></th></tr>
            <tr><th colspan="5" class="text-end">Grand Total:</th><th colspan="3">MK <?= number_format($subtotal+$total_vat,2) ?></th></tr>
        </tfoot>
    </table>

<?php if($subtotal>0): ?>
    <!-- COMPLETE SALE -->
    <form method="POST" class="row g-3 mt-3">
        <div class="col-md-4">
            <label>Customer (optional)</label>
            <select name="customer_id" class="form-control">
                <option value="">-- Walk-in --</option>
                <?php
                $cust=$conn->query("SELECT * FROM guests ORDER BY name");
                while($cu=$cust->fetch_assoc()){
                    echo "<option value='{$cu['id']}'>{$cu['name']} (Points: {$cu['loyalty_points']})</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-4">
            <label>Discount (MK)</label>
            <input type="number" step="0.01" name="discount" value="0" class="form-control">
        </div>
      <div class="col-md-4">
    <label>Payment Method</label>
    <select name="payment_method" id="payment_method" class="form-control" required onchange="toggleMobileNumber()">
        <option value="">-- Select Method --</option>
        <option value="Cash">💵 Cash</option>
        <option value="Mobile Money">📱 Mobile Money</option>
        <option value="Airtel Money">📲 Airtel Money</option>
        <option value="TNM Mpamba">📲 TNM Mpamba</option>
        <option value="Card">💳 Card (POS)</option>
        <option value="Bank Transfer">🏦 Bank Transfer</option>
        <option value="Cheque">🧾 Cheque</option>
        <option value="Online Payment">🌐 Online Payment</option>
        <option value="Digital Wallet">👛 Digital Wallet</option>
        <option value="Other">➕ Other</option>
    </select>
</div>

<div class="col-md-4" id="mobile_number_div" style="display:none;">
    <label>Mobile Number</label>
    <input type="text" name="phone_number" id="phone_number" class="form-control" placeholder="Enter phone number" required>
</div>

<script>
function toggleMobileNumber(){
    let method = document.getElementById('payment_method').value;
    let div = document.getElementById('mobile_number_div');
    if(method=='TNM Mpamba' || method=='Airtel Money' || method=='Mobile Money'){
        div.style.display='block';
    } else {
        div.style.display='none';
    }
}
</script>
        <div class="col-md-6 mt-3">
            <button name="complete_tab" class="btn btn-primary w-100">
                <i class="fa fa-check"></i> Complete Tab Sale & Close Tab
            </button>
        </div>
        <div class="col-md-6 mt-3">
            <form method="GET" action="bar_tab_invoice.php" target="_blank">
                <input type="hidden" name="tab_id" value="<?= $tab_id ?>">
                <button type="submit" class="btn btn-info w-100">
                    <i class="fa fa-file-invoice"></i> Generate Invoice
                </button>
            </form>
        </div>
    </form>
<?php endif; ?>

</div>

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

ob_end_flush(); // send output
 ?>
