<?php
session_start();
require_once 'db.php';

// Only allow admins
if (!isset($_SESSION['user_id']) || ($_SESSION['is_admin'] ?? 0) != 1) {
    header("Location: login.php");
    exit();
}

// Fetch products
$stmt = $conn->query("SELECT * FROM products ORDER BY created_at DESC");
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Products - Taji Yetu</title>
<link rel="icon" href="images/taji-yetu.png" type="image/png">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link rel="stylesheet" href="admin-sidebar.css">
<style>
body {
  font-family:'Segoe UI', sans-serif;
  background:#000;
  color:#fff;
  margin:0;
}

/* Buttons */
button {
  cursor:pointer;
  border:none;
  border-radius:6px;
  padding:8px 12px;
  color:#fff;
  background:#28a745;
  font-weight:bold;
  transition:0.3s;
}
button:hover { background:#218838; }

/* Desktop table */
.product-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}
.product-table th, .product-table td {
  padding: 12px;
  border-bottom: 1px solid #333;
  text-align: left;
}
.product-table th {
  background:#111;
}
.product-table td img {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

/* Mobile cards */
.mobile-list {
  display: none;
  flex-direction: column;
  gap: 6px;
  padding: 10px;
}
.mobile-list .product-card {
  width: 100%;
  box-sizing: border-box;
  background:#111;
  border-radius: 6px;
  display:flex;
  align-items:center;
  justify-content:space-between;
  padding:6px 8px;
}
.mobile-list .product-card img {
  width: 50px;
  height: 50px;
  object-fit: cover;
  margin-right: 8px;
  border-radius:6px;
}
.mobile-list .product-card .details {
  flex:1;
  min-width:0;
}
.mobile-list .product-card .details strong { display:block; margin-bottom:3px; font-size:0.9em; }
.mobile-list .product-card .actions button {
  background:#444;
  color:#fff;
  border:none;
  padding:4px 8px;
  border-radius:4px;
  margin-left:4px;
  font-size:0.85em;
  cursor:pointer;
}

/* Search & filter */
.filter-search-container {
  display:flex;
  flex-wrap:wrap;
  gap:10px;
  margin-top:10px;
  align-items:center;
}
.filter-search-container input, .filter-search-container select {
  padding:6px 10px;
  border-radius:6px;
  border:none;
  background:#222;
  color:#fff;
}
.filter-search-container input::placeholder { color:#aaa; }

/* Modals */
.modal {
  display:none;
  position:fixed;
  top:0; left:0;
  width:100%; height:100%;
  background:rgba(0,0,0,0.8);
  justify-content:center;
  align-items:center;
  z-index:2000;
}
.modal-content {
  background:#111;
  padding:20px;
  border-radius:8px;
  width:90%;
  max-width:600px;
  position:relative;
  color:#fff;
  max-height:90vh;
  overflow-y:auto;
}
.modal-close {
  position:absolute;
  top:10px; right:15px;
  font-size:18px;
  cursor:pointer;
}
.modal-content input, .modal-content select, .modal-content textarea {
  width:100%;
  margin-top:8px;
  padding:8px;
  border:none;
  border-radius:6px;
  background:#222;
  color:#fff;
}
.modal-content label { margin-top:10px; display:block; font-weight:bold; }

/* Toast */
#toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #28a745;
  color: #fff;
  padding: 12px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.3);
  display: none;
  z-index: 9999;
  font-weight: bold;
}

/* Responsive */
@media (max-width:768px) {
  .product-table { display:none; }
  .mobile-list { display:flex; }
  .main-content { margin-left:0 !important; padding:10px; }
  
  .filter-search-container {
    flex-direction: row;
    flex-wrap: wrap;
    gap:8px;
  }
  .filter-search-container > .row1, .filter-search-container > .row2 {
    display:flex;
    width:100%;
    gap:8px;
  }
  .filter-search-container > .row1 button, .filter-search-container > .row1 input {
    flex:1;
  }
  .filter-search-container > .row2 select {
    flex:1;
  }
}
</style>
</head>
<body>

<?php include "navbar.php"; ?>
<?php include "admin-sidebar.php"; ?>

<div class="main-content">
  <h2>Product Management</h2>
  <p>Welcome back, <?= $_SESSION['firstName'] ?? 'Admin' ?>. Here’s your product list.</p>
  
  <div class="filter-search-container">
    <div class="row1">
      <button onclick="openModal('addModal')"><i class="fas fa-plus"></i> Add Product</button>
      <input type="text" id="searchInput" placeholder="🔍 Search products...">
    </div>
    <div class="row2">
      <select id="filterCategory">
        <option value="">All Categories</option>
        <option value="Men">Men</option>
        <option value="Women">Women</option>
        <option value="Kids">Kids</option>
      </select>
      <select id="filterGender">
        <option value="">All Genders</option>
        <option value="Unisex">Unisex</option>
        <option value="Men">Men</option>
        <option value="Women">Women</option>
        <option value="Kids">Kids</option>
      </select>
    </div>
  </div>

  <!-- Desktop Table -->
  <table class="product-table" id="productTable">
    <thead>
      <tr>
        <th>#</th>
        <th>Image</th>
        <th>Name</th>
        <th>SKU</th>
        <th>Category</th>
        <th>Brand</th>
        <th>Gender</th>
        <th>Price</th>
        <th>Stock</th>
        <th>Sold</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="tableBody">
    <?php foreach($products as $index=>$p): ?>
      <tr data-name="<?= htmlspecialchars(strtolower($p['name'])) ?>" data-sku="<?= htmlspecialchars(strtolower($p['sku'])) ?>" data-brand="<?= htmlspecialchars(strtolower($p['brand'])) ?>" data-category="<?= htmlspecialchars($p['category']) ?>" data-gender="<?= htmlspecialchars($p['gender']) ?>">
        <td><?= $index+1 ?></td>
        <td><?php if($p['image']) echo '<img src="uploads/'.htmlspecialchars($p['image']).'" alt="">'; ?></td>
        <td><?= htmlspecialchars($p['name'] ?? '') ?></td>
        <td><?= htmlspecialchars($p['sku'] ?? '') ?></td>
        <td><?= htmlspecialchars($p['category'] ?? '') ?></td>
        <td><?= htmlspecialchars($p['brand'] ?? '') ?></td>
        <td><?= htmlspecialchars($p['gender'] ?? 'Unisex') ?></td>
        <td>Ksh <?= number_format($p['price'],2) ?></td>
        <td><?= intval($p['stock']) ?></td>
        <td><?= intval($p['sold_quantity']) ?></td>
        <td>
          <button onclick="openEditModal(<?= $p['id'] ?>)">Edit</button>
          <button onclick="openDeleteModal(<?= $p['id'] ?>)">Delete</button>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table>

  <!-- Mobile Cards -->
  <div class="mobile-list" id="mobileList">
  <?php foreach($products as $p): ?>
    <div class="product-card" data-name="<?= htmlspecialchars(strtolower($p['name'])) ?>" data-sku="<?= htmlspecialchars(strtolower($p['sku'])) ?>" data-brand="<?= htmlspecialchars(strtolower($p['brand'])) ?>" data-category="<?= htmlspecialchars($p['category']) ?>" data-gender="<?= htmlspecialchars($p['gender']) ?>">
      <img src="uploads/<?= htmlspecialchars($p['image'] ?? '') ?>" alt="">
      <div class="details">
        <strong><?= htmlspecialchars($p['name'] ?? '') ?></strong>
        Ksh <?= number_format($p['price'],2) ?>
      </div>
      <div class="actions">
        <button onclick="openEditModal(<?= $p['id'] ?>)">Edit</button>
        <button onclick="openDeleteModal(<?= $p['id'] ?>)">Delete</button>
      </div>
    </div>
  <?php endforeach; ?>
  </div>
</div>

<!-- Add Product Modal -->
<div class="modal" id="addModal">
  <div class="modal-content">
    <span class="modal-close" onclick="closeModal('addModal')">&times;</span>
    <h3>Add Product</h3>
    <form id="addForm" method="post" enctype="multipart/form-data" action="add-product.php">
      <label>Name</label>
      <input type="text" name="name" required>
      <label>SKU</label>
      <input type="text" name="sku" required>
      <label>Category</label>
      <select name="category">
        <option>Men</option><option>Women</option><option>Kids</option>
      </select>
      <label>Gender</label>
      <select name="gender">
        <option>Unisex</option><option>Men</option><option>Women</option><option>Kids</option>
      </select>
      <label>Brand</label>
      <input type="text" name="brand">
      <label>Price</label>
      <input type="number" name="price" step="0.01" required>
      <label>Stock</label>
      <input type="number" name="stock" value="1" min="1" required>
      <label>Material</label>
      <input type="text" name="material">
      <label>Sizes (comma separated)</label>
      <input type="text" name="sizes">
      <label>Colors (comma separated)</label>
      <input type="text" name="colors">
      <label>Images</label>
      <input type="file" name="images[]" multiple>
      <label>Description</label>
      <textarea name="description"></textarea>
      <button type="submit">Add Product</button>
    </form>
  </div>
</div>

<!-- Edit Product Modal -->
<div class="modal" id="editModal">
  <div class="modal-content" id="editContent">
    <span class="modal-close" onclick="closeModal('editModal')">&times;</span>
  </div>
</div>

<!-- Delete Modal -->
<div class="modal" id="deleteModal">
  <div class="modal-content">
    <span class="modal-close" onclick="closeModal('deleteModal')">&times;</span>
    <h3>Confirm Delete?</h3>
    <p>Are you sure you want to delete this product?</p>
    <button id="confirmDeleteBtn">Yes, Delete</button>
    <button onclick="closeModal('deleteModal')">Cancel</button>
  </div>
</div>

<!-- Toast -->
<div id="toast"></div>

<script>
// Modal helpers
function openModal(id){ document.getElementById(id).style.display='flex'; }
function closeModal(id){ document.getElementById(id).style.display='none'; }

// Edit modal
const products = <?= json_encode($products) ?>;

function openEditModal(id) {
  const p = products.find(x => x.id == id);
  if(!p) return;
  
  const editContent = document.getElementById('editContent');

  // Get sizes safely
  let sizesValue = '';
  try { sizesValue = p.sizes ? JSON.parse(p.sizes).join(',') : ''; } catch(e){}

  // Get attributes safely
  let attrHTML = '';
  if(p.attributes){
    try {
      const attrs = JSON.parse(p.attributes);
      for(const key in attrs){
        attrHTML += `<div style="display:flex;gap:4px;margin-top:4px;">
          <input type="text" name="attr_name[]" value="${key}" placeholder="Attribute Name" style="flex:1;">
          <input type="text" name="attr_value[]" value="${attrs[key]}" placeholder="Attribute Value" style="flex:1;">
        </div>`;
      }
    } catch(e){}
  }

  editContent.innerHTML = `
    <span class="modal-close" onclick="closeModal('editModal')">&times;</span>
    <h3>Edit Product: ${p.name}</h3>
    <form id="editForm" method="post" enctype="multipart/form-data" action="edit-product.php">
      <input type="hidden" name="id" value="${p.id}">
      <label>Name</label><input type="text" name="name" value="${p.name ?? ''}" required>
      <label>SKU</label><input type="text" name="sku" value="${p.sku ?? ''}" required>
      <label>Category</label>
      <select name="category">
        <option ${p.category=='Men'?'selected':''}>Men</option>
        <option ${p.category=='Women'?'selected':''}>Women</option>
        <option ${p.category=='Kids'?'selected':''}>Kids</option>
      </select>
      <label>Gender</label>
      <select name="gender">
        <option ${p.gender=='Unisex'?'selected':''}>Unisex</option>
        <option ${p.gender=='Men'?'selected':''}>Men</option>
        <option ${p.gender=='Women'?'selected':''}>Women</option>
        <option ${p.gender=='Kids'?'selected':''}>Kids</option>
      </select>
      <label>Brand</label><input type="text" name="brand" value="${p.brand ?? ''}">
      <label>Price</label><input type="number" name="price" step="0.01" value="${p.price ?? 0}" required>
      <label>Stock</label><input type="number" name="stock" value="${p.stock > 0 ? p.stock : 1}" required>
      <label>Material</label><input type="text" name="material" value="${p.material ?? ''}">
      <label>Sizes</label><input type="text" name="sizes" value="${sizesValue}">
      <div id="editAttrBox">${attrHTML}</div>
      <label>Images</label><input type="file" name="images[]" multiple>
      <label>Description</label><textarea name="description">${p.description ?? ''}</textarea>
      <button type="submit">Save Changes</button>
    </form>
  `;
  
  openModal('editModal');
}

// Delete modal
let deleteId = null;
function openDeleteModal(id){ deleteId=id; openModal('deleteModal'); }
document.getElementById('confirmDeleteBtn').addEventListener('click', ()=>{
  if(deleteId) window.location.href=`delete-product.php?id=${deleteId}`;
});

// Toast
function showToast(msg, duration=3000){
    const toast = document.getElementById('toast');
    toast.textContent = msg;
    toast.style.display = 'block';
    setTimeout(()=>{ toast.style.display='none'; }, duration);
}
const urlParams = new URLSearchParams(window.location.search);
if(urlParams.get('added') === '1'){ showToast('Product Added!'); }
if(urlParams.get('updated') === '1'){
    const updatedId = urlParams.get('id');
    const updatedProduct = products.find(p => p.id == updatedId);
    showToast(`Changes Saved for: ${updatedProduct ? updatedProduct.name : 'Product'}`);
}

// Search & Filter
const searchInput = document.getElementById('searchInput');
const filterCategory = document.getElementById('filterCategory');
const filterGender = document.getElementById('filterGender');
searchInput.addEventListener('input', applyFilters);
filterCategory.addEventListener('change', applyFilters);
filterGender.addEventListener('change', applyFilters);

function applyFilters(){
  const search = searchInput.value.toLowerCase();
  const category = filterCategory.value;
  const gender = filterGender.value;

  document.querySelectorAll('#tableBody tr').forEach(row=>{
    const name = row.dataset.name;
    const sku = row.dataset.sku;
    const brand = row.dataset.brand;
    const rowCategory = row.dataset.category;
    const rowGender = row.dataset.gender;

    const matchesSearch = name.includes(search) || sku.includes(search) || brand.includes(search);
    const matchesCategory = !category || rowCategory === category;
    const matchesGender = !gender || rowGender === gender;

    row.style.display = (matchesSearch && matchesCategory && matchesGender) ? '' : 'none';
  });

  document.querySelectorAll('#mobileList .product-card').forEach(card=>{
    const name = card.dataset.name;
    const sku = card.dataset.sku;
    const brand = card.dataset.brand;
    const rowCategory = card.dataset.category;
    const rowGender = card.dataset.gender;

    const matchesSearch = name.includes(search) || sku.includes(search) || brand.includes(search);
    const matchesCategory = !category || rowCategory === category;
    const matchesGender = !gender || rowGender === gender;

    card.style.display = (matchesSearch && matchesCategory && matchesGender) ? '' : 'none';
  });
}
</script>

</body>
</html>
