<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';
$username = $_SESSION['username'] ?? 'Guest';
// ==================== RESTAURANT STORE ====================
$restaurant_store_id = 3; // ID for Restaurant store

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

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

    // Get menu item
    $menu = $conn->query("
        SELECT rm.*, p.name as product_name
        FROM restaurant_menu rm
        LEFT JOIN products p ON rm.product_id = p.id
        WHERE rm.id=$menu_id AND rm.is_active=1
    ")->fetch_assoc();

    if(!$menu){
        echo "<script>alert('Menu item not found!');</script>";
    } else {
        $product_id = $menu['product_id'] ?? null;

        // Check stock if product_id is linked
        if($product_id){
            $stock = $conn->query("SELECT quantity FROM product_stock WHERE product_id=$product_id AND store_id=$restaurant_store_id")->fetch_assoc();
            $available_qty = $stock['quantity'] ?? 0;

            if($qty > $available_qty){
                echo "<script>alert('Insufficient stock for {$menu['name']}! Available: $available_qty');</script>";
            } else {
                $_SESSION['restaurant_cart'][] = [
                    'menu_id'    => $menu_id,
                    'name'       => $menu['name'],
                    'product_id' => $product_id,
                    'price'      => $menu['price'],
                    'qty'        => $qty
                ];
            }
        } else {
            // No stock linked, just add
            $_SESSION['restaurant_cart'][] = [
                'menu_id'    => $menu_id,
                'name'       => $menu['name'],
                'product_id' => null,
                'price'      => $menu['price'],
                'qty'        => $qty
            ];
        }
    }
}

// ==================== REMOVE ITEM ====================
if(isset($_GET['remove'])){
    $remove_index = intval($_GET['remove']);
    if(isset($_SESSION['restaurant_cart'][$remove_index])){
        unset($_SESSION['restaurant_cart'][$remove_index]);
        $_SESSION['restaurant_cart'] = array_values($_SESSION['restaurant_cart']);
    }
}
// ==================== SEND ORDER TO KITCHEN ====================
if(isset($_POST['send_to_kitchen'])){
    $waiter_id = $_SESSION['user_id'] ?? 0;
    $customer_id = intval($_POST['customer_id'] ?? 0);
    $discount = floatval($_POST['discount'] ?? 0);

    // Back date support
    $order_date = $_POST['order_date'] ?? date('Y-m-d H:i:s');
    $order_date = date('Y-m-d H:i:s', strtotime($order_date));

    $subtotal = 0;

    foreach($_SESSION['restaurant_cart'] as $c){
        $subtotal += $c['price'] * $c['qty'];
    }

    $grand_total = $subtotal - $discount;

    // Payment method is always 'Orders' for Kitchen
    $payment_method = 'Orders';

    // Insert order into restaurant_orders
    $created_by = $conn->real_escape_string($username);
   $conn->query("INSERT INTO restaurant_orders(
    waiter_id,
    customer_id,
    subtotal,
    discount,
    grand_total,
    status,
    payment_method,
    created_by,
    created_at
) VALUES(
    $waiter_id,
    $customer_id,
    $subtotal,
    $discount,
    $grand_total,
    'IN_KITCHEN',
    '$payment_method',
    '$created_by',
    '$order_date'
)");
    $order_id = $conn->insert_id;

    // Insert order items
    foreach($_SESSION['restaurant_cart'] as $c){
        $menu_id = $c['menu_id'];
        $product_id = $c['product_id'] ?? 'NULL';
        $price = $c['price'];
        $qty = $c['qty'];

        $conn->query("INSERT INTO restaurant_order_items(order_id, menu_id, product_id, price, qty)
                      VALUES($order_id, $menu_id, $product_id, $price, $qty)");
    }

    // ==================== SEND EMAIL ALERT ====================
    $admin_emails = ["giantplusmw@gmail.com", "rams.investments@gmail.com"];
    $subject = "New Kitchen Order (Order ID: $order_id)";

    // Build HTML email
    $email_message = '
    <html>
    <head>
      <title>New Kitchen Order</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 Kitchen Order Placed</h2>
        <p>Order ID: '.$order_id.'</p>
        <p>Waiter: '.htmlspecialchars($username).'</p>
        <p>Customer: '.($customer_id ? "ID $customer_id" : "Walk-in").'</p>
        <p>Payment Method: Orders</p>
        <p>Discount: MK '.number_format($discount,2).'</p>
        <p>Grand Total: MK '.number_format($grand_total,2).'</p>

        <h3>Items Ordered</h3>
        <table>
          <thead>
            <tr><th>Item</th><th>Qty</th><th>Price (MK)</th><th>Total (MK)</th></tr>
          </thead>
          <tbody>';
          foreach($_SESSION['restaurant_cart'] as $c){
              $total_line = $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($total_line,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['restaurant_cart'] = [];

    echo "<script>alert('✔ Order sent to kitchen. Admins notified via email.'); window.location='restaurant_orders_list.php';</script>";
    exit;
}
// ==================== COMPLETE SALE ====================
if(isset($_POST['complete_sale'])){
    $payment_method = $conn->real_escape_string($_POST['payment_method_select']);
    $discount       = floatval($_POST['discount'] ?? 0);
    $customer_id    = intval($_POST['customer_id'] ?? 0);
    $rest           = $conn->real_escape_string($_POST['rest'] ?? ''); 

    $subtotal = 0;
    foreach($_SESSION['restaurant_cart'] as $c){
        $subtotal += $c['price'] * $c['qty'];
    }

    $grand_total = $subtotal - $discount;

    // Insert sale into sales table
    $created_by = $conn->real_escape_string($username);
    $conn->query("INSERT INTO sales(total, vat_total, discount, rest, payment_method, customer_id, sale_date, store_id,created_by) 
                  VALUES($grand_total, 0, $discount,
                   '$rest','$payment_method', $customer_id, NOW(), $restaurant_store_id, '$created_by')");
    $sale_id = $conn->insert_id;

    // Insert sale items and update stock
    foreach($_SESSION['restaurant_cart'] as $c){
        $product_id = $c['product_id'] ?? null;
        $menu_id    = $c['menu_id'] ?? null;
        $price      = $c['price'];
        $qty        = $c['qty'];

        $conn->query("INSERT INTO sale_items(sale_id, product_id, menu_id, price, qty, vat, store_id) 
                      VALUES($sale_id, ".($product_id ?? 'NULL').", ".($menu_id ?? 'NULL').", $price, $qty, 0, $restaurant_store_id)");

        // Update stock if linked
        if($product_id){
            $conn->query("UPDATE product_stock 
                          SET quantity = quantity - $qty 
                          WHERE product_id=$product_id AND store_id=$restaurant_store_id");

            $conn->query("INSERT INTO stock_movements(product_id, from_store_id, to_store_id, quantity, movement_type)
                          VALUES($product_id, $restaurant_store_id, NULL, $qty, 'Sale')");
        }
    }

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

    // Build HTML email
    $email_message = '
    <html>
    <head>
      <title>New Sale Alert</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 Restaurant Sale Completed</h2>
        <p>Sale ID: '.$sale_id.'</p>
        <p>Waiter: '.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['restaurant_cart'] as $c){
              $total_line = $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($total_line,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['restaurant_cart'] = [];

    // Optionally, print receipt automatically
    echo "<script>window.open('print_restaurant_receipt.php?sale_id=$sale_id','_blank');</script>";
    echo "<script>alert('✔ Sale completed successfully! Admins notified via email.'); window.location='restaurant_sales_list.php';</script>";
    exit;
}
?>

<div class="container mt-4">
    <button class="btn btn-secondary btn-custom" onclick="history.back()">
        <i class="fa fa-arrow-left"></i> Back
    </button>
    <div class="welcome-msg">
        <i class="fa fa-user-circle"></i> Welcome, <strong><?= htmlspecialchars($username) ?></strong>!
    </div>
    <a href="restaurant_sales_list.php" class="btn btn-sm btn-primary">Restaurant Sales</a>
    <a href="restaurant_orders_list.php" class="btn btn-sm btn-primary">Orders</a>
    <h5 class="text-center"><b>Restaurant POS</b></h5>
    <hr>

    <!-- Fast Sale Buttons Section -->
    <h4>ðŸ’¨ Fast Sale</h4>
    <div class="mb-3 d-flex flex-wrap gap-2">
        <?php
        $fast_menu = $conn->query("
            SELECT rm.*, p.name as product_name
            FROM restaurant_menu rm
            LEFT JOIN products p ON rm.product_id = p.id
            WHERE rm.is_active=1
            ORDER BY FIELD(rm.category,'Appetizer','Main','Dessert','Drink','Other'), rm.name
            LIMIT 20
        ");

        while($fm = $fast_menu->fetch_assoc()){
            $available = 1; // default
            if($fm['product_id']){
                $stock = $conn->query("
                    SELECT quantity 
                    FROM product_stock 
                    WHERE product_id={$fm['product_id']} AND store_id=$restaurant_store_id
                ")->fetch_assoc();
                $available = $stock['quantity'] ?? 0;
            }

            if($available > 0){
                echo '<form method="POST" class="m-0 p-0 d-inline-block">';
                echo '<input type="hidden" name="menu_id" value="'.$fm['id'].'">';
                echo '<input type="hidden" name="qty" value="1">';
                echo '<button type="submit" name="add_to_cart" class="btn btn-sm btn-success">';
                echo htmlspecialchars($fm['name']).' (MK '.$fm['price'].')';
                echo '</button>';
                echo '</form>';
            }
        }
        ?>
    </div>

    <!-- Menu Selection -->
    <form method="POST" class="row g-3">
        <div class="col-md-8">
            <label>Select Menu Item</label>
            <select name="menu_id" class="form-control" required>
                <option value="">-- Select Item --</option>
                <?php
                $menu_items = $conn->query("
                    SELECT rm.*, p.name as product_name 
                    FROM restaurant_menu rm
                    LEFT JOIN products p ON rm.product_id = p.id
                    WHERE rm.is_active=1
                    ORDER BY FIELD(rm.category,'Appetizer','Main','Dessert','Drink','Other'), rm.name
                ");
                while($m = $menu_items->fetch_assoc()){
                    $display_name = $m['name'];
                    if($m['category']=='Drink' && $m['product_name']){
                        $display_name .= " ({$m['product_name']})";
                    }
                    echo "<option value='{$m['id']}'>{$display_name} - MK {$m['price']}</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-2">
            <label>Qty</label>
            <input type="number" name="qty" value="1" min="1" class="form-control" required>
        </div>
        <div class="col-md-2 mt-4">
            <button type="submit" name="add_to_cart" class="btn btn-success w-100">Add</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>Item</th><th>Price (MK)</th><th>Qty</th><th>Total (MK)</th><th>Action</th>
            </tr>
        </thead>
        <tbody>
            <?php
            $subtotal = 0;
            foreach($_SESSION['restaurant_cart'] as $i=>$c){
                $total_line = $c['price'] * $c['qty'];
                $subtotal += $total_line;
                echo "<tr>
                <td>".($i+1)."</td>
                <td>{$c['name']}</td>
                <td>{$c['price']}</td>
                <td>{$c['qty']}</td>
                <td>".number_format($total_line,2)."</td>
                <td><a href='restaurant_pos.php?remove=$i' class='btn btn-danger btn-sm'>Remove</a></td>
                </tr>";
            }
            ?>
        </tbody>
        <tfoot>
            <tr>
                <th colspan="4" class="text-end">Subtotal:</th>
                <th colspan="2">MK <?= number_format($subtotal,2) ?></th>
            </tr>
        </tfoot>
    </table>

    <?php if($subtotal>0): ?>
    <!-- Provisional Checkbox -->
    <div class="mb-3">
        <label>
            <input type="checkbox" id="provisionalCheckbox" checked>
            Kitchen Order (if unchecked, it's a Sale)
        </label>
    </div>

    <!-- Payment & Send to Kitchen -->
    <form method="POST" class="row g-3" id="posForm">
        <input type="hidden" name="payment_method" id="paymentMethodInput" value="Orders">
        <div id="customerPaymentSection">
            <div class="col-md-6">
                <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']}</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="col-md-3">
                <label>Discount (MK)</label>
                <input type="number" name="discount" step="0.01" value="0" class="form-control">
                <input type="hidden" name="rest" value="2" class="form-control">
            </div>
            <div class="col-md-3">
                
              <div class="form-group">
    <label><i class="fa fa-credit-card"></i> Payment Method</label>
    
    <select name="payment_method_select" class="form-control">
        <option value="Cash">💵 Cash</option>
        <option value="Mobile Money">📱 Mobile Money</option>
        <option value="Card">💳 Card</option>
        <option value="Bank Transfer">🏦 Bank Transfer</option>
        <option value="Cheque">🧾 Cheque</option>
        <option value="Online Payment">🌐 Online Payment</option>
        <option value="POS">🖥️ POS Machine</option>
        <option value="Wallet">👛 Digital Wallet</option>
        <option value="Other">➕ Other</option>
    </select>
</div>
            </div>
        </div>
        <div class="col-md-12 mt-3 d-flex gap-2">
            <div class="col-md-3">
    <label>Discount (MK)</label>
    <input type="number" name="discount" step="0.01" value="0" class="form-control">
    <input type="hidden" name="rest" value="2">
</div>

<div class="col-md-3">
    <label>Order Date</label>
    <input type="datetime-local" name="order_date"
           value="<?= date('Y-m-d\TH:i') ?>"
           class="form-control">
</div>
            <button type="submit" name="send_to_kitchen" id="sendToKitchenBtn" class="btn btn-warning w-50">
                Send to Kitchen
            </button>
            <button type="submit" name="complete_sale" id="completeSaleBtn" class="btn btn-primary w-50">
                ðŸ’³ Complete Sale
            </button>
        </div>
    </form>
    <?php endif; ?>
</div>

<script>
    const checkbox = document.getElementById('provisionalCheckbox');
    const paymentSection = document.getElementById('customerPaymentSection');
    const sendBtn = document.getElementById('sendToKitchenBtn');
    const saleBtn = document.getElementById('completeSaleBtn');
    const paymentInput = document.getElementById('paymentMethodInput');

    function togglePOSSections() {
        if(checkbox.checked){
            // Kitchen Order
            paymentSection.style.display = 'none';
            saleBtn.style.display = 'none';
            sendBtn.style.display = 'inline-block';
            paymentInput.value = 'Orders'; // force Orders for kitchen
        } else {
            // Sale
            paymentSection.style.display = 'flex';
            saleBtn.style.display = 'inline-block';
            sendBtn.style.display = 'none';
        }
    }

    // Initialize
    togglePOSSections();

    // Listen for change
    checkbox.addEventListener('change', togglePOSSections);
</script>

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