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

$username = $_SESSION['username'] ?? 'Guest';
$current_user = $_SESSION['username'] ?? '';
$current_role = strtolower($_SESSION['role'] ?? 'guest');

// ==================== SET BAR DEPARTMENT ====================
$department_id = 1; // Only Bar department

// Start cart session
if(!isset($_SESSION['cart'])) $_SESSION['cart'] = [];

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

    // Check stock by department only

// Check stock for the Bar department
// ==================== CHECK STOCK FOR BAR ====================
$product_id = intval($_POST['product_id']);
$qty = intval($_POST['qty']);

// Fetch product info along with Bar stock from bar_requisition_items
$product = $conn->query("
    SELECT p.id, p.name, p.sku, p.selling_price, p.vat_rate,
           COALESCE(SUM(bri.quantity),0) AS available_qty
    FROM products p
    LEFT JOIN bar_requisition_items bri 
      ON p.id = bri.product_id 
    WHERE p.id = $product_id
    GROUP BY p.id
")->fetch_assoc();

$available_qty = $product['available_qty'] ?? 0;

if($qty > $available_qty){
    echo "<script>alert('⚠️ Insufficient stock! Available: $available_qty');</script>";
} else {
    $_SESSION['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['cart'][$_GET['remove']]);
    $_SESSION['cart'] = array_values($_SESSION['cart']);
}

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

    $subtotal = 0; $total_vat = 0;

    foreach($_SESSION['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;
 $created_by = $conn->real_escape_string($_SESSION['username'] ?? 'Guest');

    // Insert sale
   $conn->query("
INSERT INTO sales(total, vat_total, discount, payment_method, customer_id, phone_number, created_by, sales_date) 
VALUES($grand_total, $total_vat, $discount, '$payment_method', $customer_id,'$phone_number','$created_by','$sales_date')
");
    $sale_id = $conn->insert_id;

    // Insert sale items and deduct stock
    foreach($_SESSION['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, sales_date, created_by)
VALUES($sale_id, $pid, $price, $qty, $vat, '$sales_date', '$created_by')
");
        // Deduct stock proportionally from all product_stock rows in the department
     $stock_rows = $conn->query("
    SELECT bri.id, bri.quantity 
    FROM bar_requisition_items bri
    WHERE  bri.product_id = $pid
    ORDER BY bri.id ASC
");

$remaining = $qty;
while($remaining > 0 && ($row = $stock_rows->fetch_assoc())){
    $deduct = min($remaining, $row['quantity']);
    $conn->query("UPDATE bar_requisition_items SET quantity = quantity - $deduct WHERE id = {$row['id']}");
    $remaining -= $deduct;
}

        // Log movement
        $conn->query("
            INSERT INTO stock_movements(product_id, from_store_id, to_store_id, quantity, movement_type) 
            VALUES($pid, NULL, NULL, $qty, '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 Bar Sale #$sale_id', NOW())");
    }

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

    $email_message = '
    <html>
    <head>
      <title>New Bar Sale</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>New Bar Sale Completed</h2>
        <p>Sale ID: '.$sale_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['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);
    }
    // ========================================================

    // Clear cart
    $_SESSION['cart'] = [];

    echo "<script>alert('Bar Sale completed successfully! Admins notified via email.'); window.location='bar_sale_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" onclick="history.back()"><i class="fa fa-arrow-left"></i> Back</button>

    <a href="bar_sale_list.php" class="btn btn-sm btn-primary">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>
    <a href="bar_inventory.php" class="btn btn-sm btn-primary">Inventory</a>

    <h5 class="text-center">🍺 <b>Bar POS (Bar Department Only)</b></h5>
    <hr>


<!-- Fast Sale Buttons Section -->
<!-- Fast Sale Buttons Section -->
<h4>💨 Fast Sale</h4>
<div class="mb-3 d-flex flex-wrap gap-2">
    <?php
    // Fetch top 20 fast sale products for Bar Department
$fast_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
  LIMIT 20;
");

    while($fp = $fast_products->fetch_assoc()){
        $available = $fp['bar_qty'] ?? 0;

        // Button style and disabled if no stock
        $btn_class = $available > 0 ? 'btn-success' : 'btn-danger';
        $disabled = $available > 0 ? '' : 'disabled';

        echo '<form method="POST" class="m-0 p-0 d-inline-block">';
        echo '<input type="hidden" name="product_id" value="'.$fp['id'].'">';
        echo '<input type="hidden" name="qty" value="1">';
        echo "<button type='submit' name='add_to_cart' class='btn btn-sm $btn_class' $disabled>";
        echo htmlspecialchars($fp['name']).' (MK '.$fp['selling_price'].')';
        if($available <= 0) echo ' - Out of Stock';
        echo '</button>';
        echo '</form>';
    }
    ?>
</div>

<!-- Add Product Dropdown -->
<form method="POST" class="row g-3">
    <div class="col-md-6">
        <label>Select Product</label>
        <select name="product_id" class="form-control" required>
            <option value="">-- Select Product --</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($row = $products->fetch_assoc()){
    $available = $row['bar_qty'] ?? 0;          // Only bar_requisition_items stock
    $disabled = $available > 0 ? '' : 'disabled';
    $text = "{$row['name']} ({$row['sku']}) - MK {$row['selling_price']} - Available: $available";
    if($available <= 0) $text .= " - Out of Stock";
    echo "<option value='{$row['id']}' $disabled>$text</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 Sale/Cart</button>
    </div>
</form>

    <hr>

    <!-- Cart Table -->
    <h4>Cart</h4>

    <table class="table table-bordered table-striped">
        <thead class="bg-dark text-white">
            <tr>
                <th>#</th><th>SKU</th><th>Item</th><th>Price (MK)</th><th>Qty</th><th>VAT (MK)</th><th>Total (MK)</th><th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $subtotal = 0; $total_vat = 0;
            foreach($_SESSION['cart'] as $i=>$c){
                $line_total = $c['price'] * $c['qty'];
                $vat = $line_total * ($c['vat_rate']/100);
                $subtotal += $line_total; 
                $total_vat += $vat;
                $total_line = $line_total + $vat;

                echo "<tr>
                    <td>".($i+1)."</td>
                    <td>{$c['sku']}</td>
                    <td>{$c['name']}</td>
                    <td>{$c['price']}</td>
                    <td>{$c['qty']}</td>
                    <td>".number_format($vat,2)."</td>
                    <td>".number_format($total_line,2)."</td>
                    <td><a href='sales_pos.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">Total VAT:</th>
                <th colspan="3">MK <?= number_format($total_vat,2) ?></th>
            </tr>
        </tfoot>
    </table>

    <?php if($subtotal>0): ?>
        <form method="POST" class="row g-3">
            <div class="col-md-4">
                <label>Select Customer (optional)</label>
                <select name="customer_id" class="form-control">
                    <option value="">-- Walk-in --</option>
                    <?php
                    $cust = $conn->query("SELECT * FROM guests WHERE status =2  ORDER BY name ASC");
                    while($c = $cust->fetch_assoc()){
                        echo "<option value='{$c['id']}'>{$c['name']} (Points: {$c['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>
        <option value="">-- Select Method --</option>

        <option value="Cash">💵 Cash</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="phone_field" style="display:none;">
    <label>Customer Phone Number</label>
    <input type="text" name="phone_number" class="form-control" placeholder="Enter phone number">
</div>
<div class="col-md-4">
    <label>Select Sale Date</label>
    <input type="datetime-local" name="sales_date" 
           value="<?= date('Y-m-d\TH:i') ?>" 
           class="form-control" required>
</div>
            <div class="col-md-12 mt-3">
                <button name="complete_sale" class="btn btn-primary w-100">
                    <i class="fa fa-check"></i> Complete Sale
                </button>
            </div>
        </form>
        <hr/>

    <?php endif; ?>

</div>
<script>
document.getElementById('payment_method').addEventListener('change', function(){
    let val = this.value;
    let phoneField = document.getElementById('phone_field');
    if(val === 'Airtel Money' || val === 'TNM Mpamba'){
        phoneField.style.display = 'block';
        phoneField.querySelector('input').required = true;
    } else {
        phoneField.style.display = 'none';
        phoneField.querySelector('input').required = false;
    }
});
</script>

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