<?php
require_once __DIR__ . '/../config.php';
requireAdmin();
$db     = getDB();
$action = $_GET['action'] ?? 'list';
$id     = (int)($_GET['id'] ?? 0);
$msg    = '';

// ── Delete ────────────────────────────────────────────────────────────────────
if ($action === 'delete' && $id) {
    $db->prepare("DELETE FROM products WHERE id=?")->execute([$id]);
    redirect(SITE_URL . '/admin/products.php?msg=deleted');
}

// ── Save (Add / Edit) ─────────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_product'])) {
    $fields = ['name','short_desc','description','price','material','finish','dimensions','weight','thickness','category_id','is_featured','status'];
    $data = [];
    foreach ($fields as $f) $data[$f] = trim($_POST[$f] ?? '');
    $data['slug']  = slugify($data['name']);
    $data['price'] = (float)$data['price'];
    $data['is_featured'] = isset($_POST['is_featured']) ? 1 : 0;

    // Image upload
    $image = $_POST['existing_image'] ?? '';
    if (!empty($_FILES['image']['name'])) {
        $ext  = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
        $allowed = ['jpg','jpeg','png','webp'];
        if (in_array($ext, $allowed)) {
            $fname = 'prod_' . time() . '_' . rand(100,999) . '.' . $ext;
            move_uploaded_file($_FILES['image']['tmp_name'], __DIR__ . '/../assets/images/' . $fname);
            $image = $fname;
        }
    }
    $data['image'] = $image;

    if ($id) {
        $set = implode(',', array_map(fn($k) => "`$k`=?", array_keys($data)));
        $stmt = $db->prepare("UPDATE products SET $set WHERE id=?");
        $stmt->execute([...array_values($data), $id]);
        $msg = 'Product updated successfully.';
    } else {
        $cols = implode(',', array_map(fn($k) => "`$k`", array_keys($data)));
        $placeholders = implode(',', array_fill(0, count($data), '?'));
        $stmt = $db->prepare("INSERT INTO products ($cols) VALUES ($placeholders)");
        $stmt->execute(array_values($data));
        $id = $db->lastInsertId();
        $msg = 'Product added successfully.';
        $action = 'edit';
    }
}

// ── Fetch for Edit ────────────────────────────────────────────────────────────
$product    = [];
if (($action === 'edit') && $id) {
    $product = $db->prepare("SELECT * FROM products WHERE id=?")->execute([$id]) ? $db->query("SELECT * FROM products WHERE id=$id")->fetch() : [];
}
$categories = $db->query("SELECT * FROM categories ORDER BY name")->fetchAll();

// ── List ──────────────────────────────────────────────────────────────────────
$products = [];
if ($action === 'list') {
    $products = $db->query("SELECT p.*,c.name AS cat FROM products p LEFT JOIN categories c ON p.category_id=c.id ORDER BY p.id DESC")->fetchAll();
}

$page_title = $action === 'list' ? 'Products' : ($id ? 'Edit Product' : 'Add Product');
include __DIR__ . '/header.php';
?>

<?php if ($msg): ?><div class="alert alert-success"><?= h($msg) ?></div><?php endif; ?>
<?php if (isset($_GET['msg']) && $_GET['msg']==='deleted'): ?><div class="alert alert-success">Product deleted.</div><?php endif; ?>

<?php if ($action === 'list'): ?>
<div class="card">
  <div class="card-header">
    <h2>All Products (<?= count($products) ?>)</h2>
    <a href="?action=add" class="btn-primary" style="padding:8px 18px;font-size:.85rem;">+ Add Product</a>
  </div>
  <div class="table-wrap">
    <table>
      <thead><tr><th>Image</th><th>Name</th><th>Category</th><th>Price</th><th>Featured</th><th>Status</th><th>Actions</th></tr></thead>
      <tbody>
        <?php foreach ($products as $p): ?>
        <tr>
          <td><img src="<?= SITE_URL ?>/assets/images/<?= h($p['image']) ?>" class="img-preview" alt=""></td>
          <td><strong><?= h($p['name']) ?></strong><br><span style="font-size:.75rem;color:var(--text-light);"><?= h($p['slug']) ?></span></td>
          <td><?= h($p['cat']) ?></td>
          <td>₹<?= number_format($p['price']) ?></td>
          <td><?= $p['is_featured'] ? '⭐' : '—' ?></td>
          <td><span class="badge badge-<?= $p['status'] ?>"><?= ucfirst($p['status']) ?></span></td>
          <td class="action-btns">
            <a href="?action=edit&id=<?= $p['id'] ?>" class="btn-action btn-edit">Edit</a>
            <a href="?action=delete&id=<?= $p['id'] ?>" class="btn-action btn-delete" data-confirm="Delete '<?= h(addslashes($p['name'])) ?>'?" onclick="return confirm(this.dataset.confirm)">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
</div>

<?php else: // Add / Edit form ?>
<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:18px;">
  <a href="products.php" style="color:var(--blue-main);font-size:.88rem;">← Back to Products</a>
</div>
<div class="card">
  <div class="card-header"><h2><?= $id ? 'Edit Product' : 'Add New Product' ?></h2></div>
  <div class="card-body">
    <form method="POST" enctype="multipart/form-data">
      <input type="hidden" name="save_product" value="1">
      <input type="hidden" name="existing_image" value="<?= h($product['image'] ?? '') ?>">
      <div class="form-grid">
        <div class="form-group">
          <label>Product Name *</label>
          <input type="text" name="name" value="<?= h($product['name'] ?? '') ?>" required placeholder="e.g. Classic Pro Single Bowl">
        </div>
        <div class="form-group">
          <label>Category</label>
          <select name="category_id">
            <option value="">-- Select Category --</option>
            <?php foreach ($categories as $c): ?>
            <option value="<?= $c['id'] ?>" <?= ($product['category_id'] ?? '') == $c['id'] ? 'selected' : '' ?>><?= h($c['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label>Price (₹)</label>
          <input type="number" name="price" step="0.01" value="<?= h($product['price'] ?? '0') ?>">
        </div>
        <div class="form-group">
          <label>Material</label>
          <input type="text" name="material" value="<?= h($product['material'] ?? '') ?>" placeholder="SS 304 (18/8)">
        </div>
        <div class="form-group">
          <label>Finish</label>
          <input type="text" name="finish" value="<?= h($product['finish'] ?? '') ?>" placeholder="Matt Finish">
        </div>
        <div class="form-group">
          <label>Dimensions</label>
          <input type="text" name="dimensions" value="<?= h($product['dimensions'] ?? '') ?>" placeholder="760×455×220 mm">
        </div>
        <div class="form-group">
          <label>Weight</label>
          <input type="text" name="weight" value="<?= h($product['weight'] ?? '') ?>" placeholder="4.2 kg">
        </div>
        <div class="form-group">
          <label>Thickness</label>
          <input type="text" name="thickness" value="<?= h($product['thickness'] ?? '') ?>" placeholder="1.2 mm">
        </div>
        <div class="form-group full">
          <label>Short Description</label>
          <input type="text" name="short_desc" value="<?= h($product['short_desc'] ?? '') ?>" placeholder="Brief product description">
        </div>
        <div class="form-group full">
          <label>Full Description</label>
          <textarea name="description" rows="5" placeholder="Detailed product description..."><?= h($product['description'] ?? '') ?></textarea>
        </div>
        <div class="form-group">
          <label>Product Image</label>
          <input type="file" name="image" accept="image/*">
          <?php if (!empty($product['image'])): ?>
          <img src="<?= SITE_URL ?>/assets/images/<?= h($product['image']) ?>" class="img-preview" style="margin-top:8px;width:120px;height:90px;" alt="">
          <?php endif; ?>
        </div>
        <div class="form-group">
          <label>Status</label>
          <select name="status">
            <option value="active" <?= ($product['status'] ?? 'active') === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= ($product['status'] ?? '') === 'inactive' ? 'selected' : '' ?>>Inactive</option>
          </select>
          <label style="margin-top:12px;display:flex;align-items:center;gap:8px;cursor:pointer;">
            <input type="checkbox" name="is_featured" value="1" <?= !empty($product['is_featured']) ? 'checked' : '' ?>> Mark as Featured
          </label>
        </div>
      </div>
      <div style="display:flex;gap:12px;margin-top:8px;">
        <button type="submit" class="btn-primary"><i class="fas fa-save"></i> Save Product</button>
        <a href="products.php" class="btn-secondary">Cancel</a>
      </div>
    </form>
  </div>
</div>
<?php endif; ?>

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