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

$message = '';

// ==================== Role Management ====================
$allowed_roles = ['admin','manager'];
$user_role = $_SESSION['role'] ?? 'guest';

function canManageMenu(){
    global $user_role, $allowed_roles;
    return in_array($user_role, $allowed_roles);
}

// ==================== Handle Add Menu ====================
if(isset($_POST['add_menu']) && canManageMenu()){
    $name = $conn->real_escape_string($_POST['name']);
    $category = $conn->real_escape_string($_POST['category']);
    $cate = $conn->real_escape_string($_POST['cate']);
    $price = floatval($_POST['price']);
    $product_id = !empty($_POST['product_id']) ? intval($_POST['product_id']) : NULL;
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    $sql = "INSERT INTO restaurant_menu (name, category, cate, price, product_id, is_active) 
            VALUES ('$name', '$category','$cate', $price, ".($product_id ?? 'NULL').", $is_active)";
    
    if($conn->query($sql)){
        $message = "<div class='alert alert-success'>Menu item '$name' added successfully!</div>";
    } else {
        $message = "<div class='alert alert-danger'>Error: ".$conn->error."</div>";
    }
} elseif(isset($_POST['add_menu'])){
    $message = "<div class='alert alert-danger'>You do not have permission to add menu items.</div>";
}

// ==================== Handle Delete Menu ====================
if(isset($_GET['delete'])){
    if(canManageMenu()){
        $delete_id = intval($_GET['delete']);
        $conn->query("DELETE FROM restaurant_menu WHERE id=$delete_id");
        echo "<script>window.location='restaurant_menu.php';</script>";
        exit;
    } else {
        $message = "<div class='alert alert-danger'>You do not have permission to delete menu items.</div>";
    }
}

// ==================== Fetch Products ====================
$products = $conn->query("SELECT * FROM products ORDER BY name ASC");

// ==================== Filters ====================
$filter_category = $_GET['filter_category'] ?? '';
$filter_cate = $_GET['filter_cate'] ?? '';

// ==================== Fetch Menu Items ====================
$query = "SELECT rm.*, p.name AS product_name 
          FROM restaurant_menu rm 
          LEFT JOIN products p ON rm.product_id = p.id 
          WHERE 1";

if($filter_category) $query .= " AND rm.category='$filter_category'";
if($filter_cate) $query .= " AND rm.cate='$filter_cate'";

$query .= " ORDER BY FIELD(rm.category,'Appetizer','Main','Dessert','Drink','Snack','Other','Starter'), rm.name";

$menus = $conn->query($query);

// ==================== Export to Excel ====================
if(isset($_GET['export_excel'])){
    header("Content-Type: application/vnd.ms-excel");
    header("Content-Disposition: attachment; filename=restaurant_menu.xls");
    
    echo "Name\tCategory\tMeal Type\tPrice\tLinked Product\tStatus\n";

    $menus_for_export = $conn->query($query);
    while($m = $menus_for_export->fetch_assoc()){
        $status = $m['is_active'] ? 'Active' : 'Inactive';
        echo "{$m['name']}\t{$m['category']}\t{$m['cate']}\t{$m['price']}\t{$m['product_name']}\t{$status}\n";
    }
    exit;
}
?>

<style>
.table thead th { text-align:center; }
.table tbody td { vertical-align:middle; }
.card-header .fa { margin-right:10px; }
.category-badge { font-size:0.85rem; }
.price-tag { font-weight:bold; color:#28a745; }
.status-badge { font-size:0.85rem; padding:0.35rem 0.65rem; }
.btn-custom { margin-bottom:15px; }
@media print {
    body { font-size: 12px; }
    .btn, form { display: none; }
    table { width: 100%; border-collapse: collapse; }
    table, th, td { border: 1px solid black; }
    th, td { padding: 5px; text-align: center; }
}
</style>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
            <i class="fa fa-user-circle fa-lg text-primary"></i> Welcome, <strong><?= htmlspecialchars($_SESSION['username'] ?? 'Guest') ?></strong>!
        </div>
        <button class="btn btn-secondary btn-custom" onclick="history.back()">
            <i class="fa fa-arrow-left"></i> Back
        </button>
    </div>

    <?= $message ?>

    <!-- ==================== Add Menu Form ==================== -->
    <?php if(canManageMenu()): ?>
    <h3 class="text-dark"><i class="fa fa-utensils"></i> Add Restaurant Menu Item</h3>
    <hr>
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form method="POST" class="row g-3">
                <div class="col-md-6">
                    <label>Menu Item Name</label>
                    <input type="text" name="name" class="form-control" required>
                </div>
                <div class="col-md-3">
                    <label>Main Category</label>
                    <select name="category" class="form-control" required>
                        <option value="">-- Select Category --</option>
                        <option value="Appetizer">Appetizer</option>
                        <option value="Main">Main Course</option>
                        <option value="Dessert">Dessert</option>
                        <option value="Snack">Snack</option>
                        <option value="Starter">Starter</option>
                        <option value="Bevarages">Bevarages</option>
                         <option value="Breakfast">Breakfast</option>
                        <option value="Other">Other</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>Meal Type</label>
                    <select name="cate" class="form-control" required>
                        <option value="">-- Select --</option>
                        <option value="HOT STARTERS">HOT STARTERS</option>
                        <option value="COLD STARTERS">COLD STARTERS</option>
                        <option value="BREAKFAST">BREAKFAST</option>
                        <option value="SNACK">SNACK</option>
                        <option value="DESSERTS">DESSERTS</option>
                        <option value="STEWS">STEWS</option>
                         <option value="STEAKS">STEAKS</option>
                          <option value="LAKES">LAKES</option>
                           <option value="LAKES">BREAKFAST</option>
                           <option value="BEVARAGES">BEVARAGES</option>
                        <option value="LUNCH">LUNCH</option>
                        <option value="DINNER">DINNER</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>Price (MK)</label>
                    <input type="number" step="0.01" name="price" class="form-control" required>
                </div>
                <div class="col-md-6">
                    <label>Link to Stock Product (optional)</label>
                    <select name="product_id" class="form-control">
                        <option value="">-- None --</option>
                        <?php while($p = $products->fetch_assoc()): ?>
                            <option value="<?= $p['id'] ?>"><?= $p['name'] ?> (SKU: <?= $p['sku'] ?>)</option>
                        <?php endwhile; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label>Active?</label>
                    <div class="form-check mt-2">
                        <input type="checkbox" name="is_active" class="form-check-input" checked>
                        <label class="form-check-label">Yes</label>
                    </div>
                </div>
                <div class="col-md-12 mt-3">
                    <button type="submit" name="add_menu" class="btn btn-primary w-100">
                        <i class="fa fa-plus"></i> Add Menu Item
                    </button>
                </div>
            </form>
        </div>
    </div>
    <?php else: ?>
        <div class="alert alert-warning">You do not have permission to add menu items.</div>
    <?php endif; ?>

    <!-- ==================== Filters ==================== -->
    <form method="GET" class="row g-3 mb-3">
        <div class="col-md-3">
            <select name="filter_category" class="form-control">
                <option value="">-- Filter Category --</option>
                <?php
                $categories = ['Appetizer','Main','Dessert','Snack','Drink','Other','Starter'];
                foreach($categories as $cat){
                    $selected = ($cat==$filter_category)?'selected':'';
                    echo "<option value='$cat' $selected>$cat</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-3">
            <select name="filter_cate" class="form-control">
                <option value="">-- Filter Meal Type --</option>
                <?php
                $cates = ['HOT STARTERS','COLD STARTERS','BREAKFAST','SNACK','DESSERTS','STEWS','LUNCH','DINNER'];
                foreach($cates as $c){
                    $selected = ($c==$filter_cate)?'selected':'';
                    echo "<option value='$c' $selected>$c</option>";
                }
                ?>
            </select>
        </div>
        <div class="col-md-2">
            <button type="submit" class="btn btn-info"><i class="fa fa-filter"></i> Filter</button>
            <a href="restaurant_menu.php" class="btn btn-secondary"><i class="fa fa-times"></i> Reset</a>
        </div>
    </form>

    <!-- ==================== Export Buttons ==================== -->
    <div class="mb-3">
        <a href="?<?= http_build_query(array_merge($_GET,['export_excel'=>1])) ?>" class="btn btn-success">
            <i class="fa fa-file-excel"></i> Export to Excel
        </a>
        <button class="btn btn-danger" onclick="printPDF()">
            <i class="fa fa-file-pdf"></i> Export to PDF
        </button>
    </div>

    <!-- ==================== Menu List ==================== -->
    <h3 class="text-dark"><i class="fa fa-list"></i> Existing Menu Items</h3>
    <table class="table table-hover table-bordered align-middle shadow-sm">
        <thead class="table-dark text-center">
            <tr>
                <th>#</th>
                <th>Name</th>
                <th>Main Category</th>
                <th>Meal Type</th>
                <th>Price (MK)</th>
                <th>Linked Product</th>
                <th>Status</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php $i=1; while($m = $menus->fetch_assoc()): ?>
            <tr>
                <td class="text-center"><?= $i ?></td>
                <td><i class="fa fa-hamburger text-warning me-1"></i> <?= htmlspecialchars($m['name']) ?></td>
                <td class="text-center">
                    <span class="badge bg-info category-badge"><?= $m['category'] ?></span>
                </td>
                <td class="text-center">
                    <span class="badge bg-secondary category-badge"><?= $m['cate'] ?></span>
                </td>
                <td class="text-end price-tag"><?= number_format($m['price'],2) ?></td>
                <td><?= htmlspecialchars($m['product_name'] ?? '-') ?></td>
                <td class="text-center">
                    <?php if($m['is_active']): ?>
                        <span class="badge bg-success status-badge">Active</span>
                    <?php else: ?>
                        <span class="badge bg-danger status-badge">Inactive</span>
                    <?php endif; ?>
                </td>
                <td class="text-center">
                    <?php if(canManageMenu()): ?>
                        <a href="edit_menu.php?id=<?= $m['id'] ?>" class="btn btn-warning btn-sm mb-1"><i class="fa fa-edit"></i></a>
                        <a href="restaurant_menu.php?delete=<?= $m['id'] ?>" onclick="return confirm('Are you sure?')" class="btn btn-danger btn-sm mb-1"><i class="fa fa-trash"></i></a>
                    <?php else: ?>
                        <span class="text-muted">No Access</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php $i++; endwhile; ?>
        </tbody>
    </table>
</div>

<script>
function printPDF(){
    var printContents = document.querySelector('table').outerHTML;
    var originalContents = document.body.innerHTML;
    document.body.innerHTML = `
        <h2>Restaurant Menu List</h2>
        ${printContents}
    `;
    window.print();
    document.body.innerHTML = originalContents;
}
</script>

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