<?php
session_start();
$page_title = 'Menu Management';
$active_nav = 'menu';
include("includes/header.php");

$success=$error="";
$action=$_GET['action']??$_POST['action']??'';

// Toggle availability
if ($action==='toggle'&&isset($_GET['id'])) {
    $id=(int)$_GET['id'];
    $s=$conn->prepare("UPDATE menu_items SET is_available=1-is_available WHERE id=? AND restaurant_id=?");
    $s->bind_param("ii",$id,$__rid); $s->execute();
    header("Location: menu.php?msg=toggled"); exit;
}
// Delete
if ($action==='delete'&&isset($_POST['id'])) {
    $id=(int)$_POST['id'];
    // Remove image
    $si=$conn->prepare("SELECT image FROM menu_items WHERE id=? AND restaurant_id=?");
    $si->bind_param("ii",$id,$__rid); $si->execute();
    $img=$si->get_result()->fetch_assoc()['image']??'';
    if ($img && file_exists("uploads/menu/$img")) unlink("uploads/menu/$img");
    $s=$conn->prepare("DELETE FROM menu_items WHERE id=? AND restaurant_id=?");
    $s->bind_param("ii",$id,$__rid); $s->execute();
    header("Location: menu.php?msg=deleted"); exit;
}
// Create / Edit
if ($_SERVER['REQUEST_METHOD']==='POST'&&in_array($action,['create','edit'])&&$is_admin) {
    $name       =trim($_POST['name']??'');
    $desc       =trim($_POST['description']??'');
    $price      =(float)($_POST['price']??0);
    $cat_id     =(int)($_POST['category_id']??0) ?: null;
    $available  =isset($_POST['is_available'])?1:0;
    $item_id    =(int)($_POST['item_id']??0);
    $image_name =null;

    if (!$name||$price<=0) { $error="Name and a valid price are required."; }
    else {
        // Handle image upload
        if (!empty($_FILES['image']['name'])) {
            $ext = strtolower(pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION));
            $allowed_exts=['jpg','jpeg','png','webp'];
            if (!in_array($ext,$allowed_exts)) { $error="Image must be JPG, PNG, or WebP."; }
            elseif ($_FILES['image']['size']>2*1024*1024) { $error="Image must be under 2MB."; }
            else {
                $image_name = uniqid('menu_').'.'.$ext;
                move_uploaded_file($_FILES['image']['tmp_name'],"uploads/menu/$image_name");
            }
        }

        if (!$error) {
            if ($action==='create') {
                $ins=$conn->prepare("INSERT INTO menu_items(restaurant_id,category_id,name,description,price,image,is_available) VALUES(?,?,?,?,?,?,?)");
                $ins->bind_param("iissdsi",$__rid,$cat_id,$name,$desc,$price,$image_name,$available);
                $ins->execute();
                $success="'{$name}' added to menu.";
            } else {
                if ($image_name) {
                    // Remove old image
                    $oi=$conn->prepare("SELECT image FROM menu_items WHERE id=? AND restaurant_id=?");
                    $oi->bind_param("ii",$item_id,$__rid); $oi->execute();
                    $old=$oi->get_result()->fetch_assoc()['image']??'';
                    if ($old&&file_exists("uploads/menu/$old")) unlink("uploads/menu/$old");
                    $upd=$conn->prepare("UPDATE menu_items SET name=?,description=?,price=?,category_id=?,image=?,is_available=? WHERE id=? AND restaurant_id=?");
                    $upd->bind_param("ssdiisii",$name,$desc,$price,$cat_id,$image_name,$available,$item_id,$__rid);
                } else {
                    $upd=$conn->prepare("UPDATE menu_items SET name=?,description=?,price=?,category_id=?,is_available=? WHERE id=? AND restaurant_id=?");
                    $upd->bind_param("ssdiiii",$name,$desc,$price,$cat_id,$available,$item_id,$__rid);
                }
                $upd->execute();
                $success="Menu item updated.";
            }
        }
    }
}

$msg=$_GET['msg']??'';
if($msg==='toggled') $success="Availability updated.";
if($msg==='deleted') $success="Item deleted.";

// Fetch categories for this restaurant
$cats=$conn->prepare("SELECT * FROM categories WHERE restaurant_id=? ORDER BY sort_order,name");
$cats->bind_param("i",$__rid); $cats->execute();
$categories=$cats->get_result()->fetch_all(MYSQLI_ASSOC);

// Fetch for edit
$edit_item=null;
if($action==='edit'&&isset($_GET['id'])) {
    $edit_id=(int)$_GET['id'];
    $si=$conn->prepare("SELECT * FROM menu_items WHERE id=? AND restaurant_id=?");
    $si->bind_param("ii",$edit_id,$__rid); $si->execute();
    $edit_item=$si->get_result()->fetch_assoc();
}

// Filter
$cat_filter=(int)($_GET['cat']??0);
$search=trim($_GET['search']??'');
$avail_filter=$_GET['avail']??'all';

$q="SELECT m.*,c.name as cat_name FROM menu_items m LEFT JOIN categories c ON m.category_id=c.id WHERE m.restaurant_id=?";
$params=[$__rid]; $types="i";
if($cat_filter){$q.=" AND m.category_id=?";$params[]=$cat_filter;$types.="i";}
if($search){$q.=" AND m.name LIKE ?";$params[]="%$search%";$types.="s";}
if($avail_filter==='available'){$q.=" AND m.is_available=1";}
if($avail_filter==='unavailable'){$q.=" AND m.is_available=0";}
$q.=" ORDER BY c.sort_order,c.name,m.name";
$st=$conn->prepare($q); $st->bind_param($types,...$params); $st->execute();
$items=$st->get_result();

$item_count=$conn->prepare("SELECT COUNT(*) FROM menu_items WHERE restaurant_id=?"); $item_count->bind_param("i",$__rid); $item_count->execute(); $item_count=$item_count->get_result()->fetch_row()[0];
?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:24px;flex-wrap:wrap;gap:12px">
  <div>
    <h1 style="font-size:1.4rem;font-weight:800;letter-spacing:-.03em;margin-bottom:3px">Menu Management</h1>
    <p style="color:var(--text-muted);font-size:.85rem"><?php echo $item_count; ?> items across <?php echo count($categories); ?> categories</p>
  </div>
  <?php if($is_admin): ?>
  <div style="display:flex;gap:8px">
    <a href="categories.php" class="btn btn-secondary btn-md">Manage Categories</a>
    <button class="btn btn-primary btn-md" onclick="openModal('addItemModal')">
      <svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><path d="M12 8v8M8 12h8"/></svg>
      Add Menu Item
    </button>
  </div>
  <?php endif; ?>
</div>

<?php if($success): ?><div class="alert alert-success"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg><?php echo $success; ?></div><?php endif; ?>
<?php if($error): ?><div class="alert alert-error"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/></svg><?php echo htmlspecialchars($error); ?></div><?php endif; ?>

<!-- Filters -->
<div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;align-items:center">
  <a href="menu.php" class="btn btn-sm <?php echo !$cat_filter&&$avail_filter==='all'?'btn-primary':'btn-secondary'; ?>">All</a>
  <?php foreach($categories as $c): ?>
  <a href="?cat=<?php echo $c['id']; ?>" class="btn btn-sm <?php echo $cat_filter==$c['id']?'btn-primary':'btn-secondary'; ?>"><?php echo htmlspecialchars($c['name']); ?></a>
  <?php endforeach; ?>
  <div style="margin-left:auto;display:flex;gap:6px">
    <a href="?avail=available<?php echo $cat_filter?"&cat=$cat_filter":''; ?>" class="btn btn-sm <?php echo $avail_filter==='available'?'btn-success':'btn-secondary'; ?>">Available</a>
    <a href="?avail=unavailable<?php echo $cat_filter?"&cat=$cat_filter":''; ?>" class="btn btn-sm <?php echo $avail_filter==='unavailable'?'btn-danger':'btn-secondary'; ?>">Unavailable</a>
    <form method="GET" style="display:flex">
      <div style="position:relative">
        <svg style="position:absolute;left:10px;top:50%;transform:translateY(-50%);width:13px;height:13px;stroke:var(--text-light);fill:none" viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg>
        <input type="text" name="search" placeholder="Search menu…" value="<?php echo htmlspecialchars($search); ?>"
               style="height:36px;border:1.5px solid var(--border);border-radius:10px;background:var(--white);padding:0 12px 0 30px;font-size:.82rem;font-family:var(--font);outline:none;width:180px"
               onfocus="this.style.borderColor='var(--primary)'" onblur="this.style.borderColor='var(--border)'">
      </div>
    </form>
  </div>
</div>

<!-- Menu Grid -->
<?php if($items->num_rows===0): ?>
<div class="card" style="padding:60px;text-align:center;color:var(--text-muted)">
  <svg width="52" height="52" viewBox="0 0 24 24" fill="none" stroke="var(--border)" stroke-width="1.5" stroke-linecap="round" style="margin:0 auto 14px;display:block"><path d="M4 6h16M4 10h16M4 14h16M4 18h7"/></svg>
  <p style="font-weight:700;margin-bottom:6px">No menu items yet</p>
  <?php if($is_admin): ?><button class="btn btn-primary btn-md" onclick="openModal('addItemModal')" style="margin-top:12px">Add First Item</button><?php endif; ?>
</div>
<?php else: ?>
<div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:16px">
  <?php while($item=$items->fetch_assoc()): ?>
  <div class="card" style="overflow:hidden;transition:box-shadow .2s" onmouseover="this.style.boxShadow='0 8px 24px rgba(34,90,227,.12)'" onmouseout="this.style.boxShadow=''">
    <?php if($item['image']&&file_exists("uploads/menu/".$item['image'])): ?>
    <img src="uploads/menu/<?php echo htmlspecialchars($item['image']); ?>" alt="<?php echo htmlspecialchars($item['name']); ?>" style="width:100%;height:160px;object-fit:cover">
    <?php else: ?>
    <div style="height:100px;background:var(--primary-bg);display:flex;align-items:center;justify-content:center">
      <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="1.5" opacity=".35" stroke-linecap="round"><path d="M3 11l19-9-9 19-2-8-8-2z"/></svg>
    </div>
    <?php endif; ?>
    <div style="padding:14px">
      <div style="display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:6px;gap:8px">
        <div style="font-weight:700;font-size:.9rem;flex:1"><?php echo htmlspecialchars($item['name']); ?></div>
        <span class="badge <?php echo $item['is_available']?'badge-success':'badge-error'; ?>" style="flex-shrink:0">
          <?php echo $item['is_available']?'Available':'Off'; ?>
        </span>
      </div>
      <?php if($item['cat_name']): ?>
      <div style="font-size:.72rem;color:var(--primary);font-weight:600;margin-bottom:6px"><?php echo htmlspecialchars($item['cat_name']); ?></div>
      <?php endif; ?>
      <?php if($item['description']): ?>
      <div style="font-size:.75rem;color:var(--text-muted);margin-bottom:10px;line-height:1.5"><?php echo htmlspecialchars(mb_strimwidth($item['description'],0,80,'…')); ?></div>
      <?php endif; ?>
      <div style="display:flex;align-items:center;justify-content:space-between">
        <div style="font-size:1.05rem;font-weight:800;color:var(--primary)">₦<?php echo number_format($item['price'],0); ?></div>
        <div style="display:flex;gap:6px">
          <?php if($is_admin): ?>
          <a href="?action=edit&id=<?php echo $item['id']; ?>" class="btn btn-secondary btn-sm">Edit</a>
          <?php endif; ?>
          <a href="?action=toggle&id=<?php echo $item['id']; ?>" class="btn btn-sm <?php echo $item['is_available']?'btn-warning':'btn-success'; ?>">
            <?php echo $item['is_available']?'Disable':'Enable'; ?>
          </a>
          <?php if($is_admin): ?>
          <form method="POST" style="display:inline" onsubmit="return confirm('Delete <?php echo addslashes($item['name']); ?>?')">
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="id" value="<?php echo $item['id']; ?>">
            <button class="btn btn-danger btn-sm">Del</button>
          </form>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
  <?php endwhile; ?>
</div>
<?php endif; ?>

<!-- Add Item Modal -->
<div class="modal-backdrop" id="addItemModal">
  <div class="modal modal-lg">
    <div class="modal-header">
      <h3>Add Menu Item</h3>
      <button class="modal-close" onclick="closeModal('addItemModal')"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></button>
    </div>
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="action" value="create">
      <div class="modal-body">
        <div class="grid-2">
          <div class="form-group"><label>Item Name *</label><input type="text" name="name" class="form-control" placeholder="e.g. Jollof Rice" required></div>
          <div class="form-group"><label>Price (₦) *</label><input type="number" name="price" class="form-control" placeholder="0.00" min="0" step="0.01" required></div>
          <div class="form-group">
            <label>Category</label>
            <select name="category_id" class="form-control">
              <option value="">— No Category —</option>
              <?php foreach($categories as $c): ?><option value="<?php echo $c['id']; ?>"><?php echo htmlspecialchars($c['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Item Photo</label>
            <input type="file" name="image" class="form-control" accept="image/jpeg,image/png,image/webp" style="height:auto;padding:10px">
            <div style="font-size:.72rem;color:var(--text-muted);margin-top:4px">JPG/PNG/WebP, max 2MB</div>
          </div>
        </div>
        <div class="form-group"><label>Description</label><textarea name="description" class="form-control" placeholder="Brief description of the item…"></textarea></div>
        <label style="display:flex;align-items:center;gap:10px;cursor:pointer;font-size:.875rem;font-weight:500">
          <input type="checkbox" name="is_available" value="1" checked style="width:16px;height:16px;accent-color:var(--primary)">
          Mark as available immediately
        </label>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary btn-md" onclick="closeModal('addItemModal')">Cancel</button>
        <button type="submit" class="btn btn-primary btn-md">Add to Menu</button>
      </div>
    </form>
  </div>
</div>

<!-- Edit Item Modal -->
<?php if($edit_item): ?>
<div class="modal-backdrop" id="editItemModal" style="display:flex">
  <div class="modal modal-lg">
    <div class="modal-header">
      <h3>Edit — <?php echo htmlspecialchars($edit_item['name']); ?></h3>
      <a href="menu.php" class="modal-close"><svg viewBox="0 0 24 24" stroke-width="2" stroke-linecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg></a>
    </div>
    <form method="POST" action="?action=edit&id=<?php echo $edit_item['id']; ?>" enctype="multipart/form-data">
      <input type="hidden" name="action" value="edit">
      <input type="hidden" name="item_id" value="<?php echo $edit_item['id']; ?>">
      <div class="modal-body">
        <div class="grid-2">
          <div class="form-group"><label>Item Name *</label><input type="text" name="name" class="form-control" value="<?php echo htmlspecialchars($edit_item['name']); ?>" required></div>
          <div class="form-group"><label>Price (₦) *</label><input type="number" name="price" class="form-control" value="<?php echo $edit_item['price']; ?>" min="0" step="0.01" required></div>
          <div class="form-group">
            <label>Category</label>
            <select name="category_id" class="form-control">
              <option value="">— No Category —</option>
              <?php foreach($categories as $c): ?><option value="<?php echo $c['id']; ?>" <?php echo $edit_item['category_id']==$c['id']?'selected':''; ?>><?php echo htmlspecialchars($c['name']); ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Replace Photo</label>
            <?php if($edit_item['image']&&file_exists("uploads/menu/".$edit_item['image'])): ?>
            <img src="uploads/menu/<?php echo htmlspecialchars($edit_item['image']); ?>" style="height:50px;border-radius:8px;margin-bottom:6px;display:block;object-fit:cover">
            <?php endif; ?>
            <input type="file" name="image" class="form-control" accept="image/jpeg,image/png,image/webp" style="height:auto;padding:10px">
          </div>
        </div>
        <div class="form-group"><label>Description</label><textarea name="description" class="form-control"><?php echo htmlspecialchars($edit_item['description']??''); ?></textarea></div>
        <label style="display:flex;align-items:center;gap:10px;cursor:pointer;font-size:.875rem;font-weight:500">
          <input type="checkbox" name="is_available" value="1" <?php echo $edit_item['is_available']?'checked':''; ?> style="width:16px;height:16px;accent-color:var(--primary)">
          Available for ordering
        </label>
      </div>
      <div class="modal-footer">
        <a href="menu.php" class="btn btn-secondary btn-md">Cancel</a>
        <button type="submit" class="btn btn-primary btn-md">Save Changes</button>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

<?php include("includes/footer.php"); ?>
