<?php
require_once __DIR__ . '/auth_guard.php';
require_once __DIR__ . '/../backend/config/database.php';

$db = getDB();
$adminUserName = $_SESSION['user_name'];
$adminPage     = 'products';
$adminPageTitle= 'Manage Products';

$msg   = '';
$error = '';

// Delete
if(isset($_GET['delete'])){
    $id = $_GET['delete'];
    $db->prepare("UPDATE products SET is_active=0 WHERE id=?")->execute([$id]);
    header('Location: /stile-lpg/admin/products.php?deleted=1');
    exit;
}
if(isset($_GET['deleted'])) $msg = 'Product deleted.';

// Create / Edit
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['save_product'])){
    $id          = $_POST['pid'] ?? '';
    $name        = trim($_POST['name']??'');
    $category    = $_POST['category']??'lpg';
    $price       = (float)($_POST['price']??0);
    $description = trim($_POST['description']??'');
    $stock       = (int)($_POST['stock']??0);
    $image_url   = '';
    
    // Handle file upload
    if(isset($_FILES['product_image']) && $_FILES['product_image']['error'] === UPLOAD_ERR_OK){
        $file = $_FILES['product_image'];
        $uploadDir = __DIR__ . '/../backend/uploads/products/';
        if(!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);
        
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $allowedExts = ['jpg','jpeg','png','webp','gif'];
        if(!in_array($ext, $allowedExts)){
            $error = 'Invalid image format. Use JPG, PNG, WEBP or GIF.';
        } elseif($file['size'] > 5 * 1024 * 1024){
            $error = 'File too large. Max 5MB.';
        } else {
            $filename = 'prod_' . bin2hex(random_bytes(8)) . '.' . $ext;
            $destPath = $uploadDir . $filename;
            if(move_uploaded_file($file['tmp_name'], $destPath)){
                $image_url = '/stile-lpg/backend/uploads/products/' . $filename;
            } else {
                $error = 'Upload failed.';
            }
        }
    } elseif($id && isset($_POST['keep_image'])){
        // Keep existing image when editing
        $stmt = $db->prepare("SELECT image_url FROM products WHERE id=?");
        $stmt->execute([$id]);
        $image_url = $stmt->fetchColumn() ?: '';
    }
    
    if(!$error){
        if(!$name || $price <= 0){ $error = 'Name and price are required.'; }
        else {
            if($id){
                if($image_url){
                    $db->prepare("UPDATE products SET name=?,category=?,price=?,description=?,image_url=?,stock=? WHERE id=?")->execute([$name,$category,$price,$description,$image_url,$stock,$id]);
                } else {
                    $db->prepare("UPDATE products SET name=?,category=?,price=?,description=?,stock=? WHERE id=?")->execute([$name,$category,$price,$description,$stock,$id]);
                }
                $msg = 'Product updated!';
            } else {
                $newId = 'prd_'.bin2hex(random_bytes(8));
                $db->prepare("INSERT INTO products(id,name,category,price,description,image_url,stock,is_active,created_at)VALUES(?,?,?,?,?,?,?,1,NOW())")->execute([$newId,$name,$category,$price,$description,$image_url,$stock]);
                $msg = 'Product created!';
            }
        }
    }
}

$products = $db->query("SELECT * FROM products WHERE is_active=1 ORDER BY created_at DESC")->fetchAll(PDO::FETCH_ASSOC);

// Edit prefill
$editProduct = null;
if(isset($_GET['edit'])){
    $stmt = $db->prepare("SELECT * FROM products WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $editProduct = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
<?php require_once __DIR__ . '/layout_top.php'; ?>

<?php if($msg): ?>
<div style="background:#f0fdf4;border:1.5px solid #bbf7d0;color:#16a34a;padding:.85rem 1.1rem;border-radius:12px;font-size:.875rem;font-weight:600;margin-bottom:1.5rem;display:flex;align-items:center;gap:.5rem"><svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7"/></svg><?= htmlspecialchars($msg) ?></div>
<?php endif; ?>
<?php if($error): ?>
<div style="background:#fef2f2;border:1.5px solid #fecaca;color:#dc2626;padding:.85rem 1.1rem;border-radius:12px;font-size:.875rem;font-weight:600;margin-bottom:1.5rem;display:flex;align-items:center;gap:.5rem"><svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg><?= htmlspecialchars($error) ?></div>
<?php endif; ?>

<div style="display:grid;grid-template-columns:1fr 360px;gap:2rem;align-items:start" class="prod-grid">

  <!-- Products list -->
  <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.05);overflow:hidden">
    <div style="padding:1.25rem 1.5rem;border-bottom:1px solid #f1f5f9;display:flex;align-items:center;justify-content:space-between">
      <h2 style="font-weight:800;font-size:1rem;color:#0f172a;margin:0"><?= count($products) ?> Products</h2>
      <a href="/stile-lpg/admin/products.php" style="color:#f97316;font-weight:700;font-size:.82rem">+ Add New</a>
    </div>
    <?php if(empty($products)): ?>
    <div style="text-align:center;padding:3rem;color:#94a3b8">No products yet.</div>
    <?php else: ?>
    <div style="overflow-x:auto">
      <table style="width:100%;border-collapse:collapse">
        <thead>
          <tr style="background:#f8f9fb">
            <?php foreach(['Product','Category','Price','Stock','Action'] as $h): ?>
            <th style="padding:.75rem 1.25rem;text-align:left;font-size:.72rem;font-weight:700;color:#94a3b8;text-transform:uppercase;letter-spacing:.06em"><?= $h ?></th>
            <?php endforeach; ?>
          </tr>
        </thead>
        <tbody>
          <?php foreach($products as $p): ?>
          <tr style="border-top:1px solid #f1f5f9" onmouseover="this.style.background='#fafafa'" onmouseout="this.style.background=''">
            <td style="padding:.75rem 1.25rem">
              <div style="font-weight:700;font-size:.875rem;color:#0f172a"><?= htmlspecialchars($p['name']) ?></div>
              <div style="color:#94a3b8;font-size:.75rem;overflow:hidden;white-space:nowrap;text-overflow:ellipsis;max-width:200px"><?= htmlspecialchars(substr($p['description']??'',0,60)) ?></div>
            </td>
            <td style="padding:.75rem 1.25rem">
              <span style="background:<?= $p['category']==='lpg'?'#fff7ed':'#f0fdf4' ?>;color:<?= $p['category']==='lpg'?'#d97706':'#16a34a' ?>;font-size:.72rem;font-weight:700;padding:.2rem .65rem;border-radius:20px;border:1px solid <?= $p['category']==='lpg'?'#fed7aa':'#bbf7d0' ?>"><?= strtoupper($p['category']) ?></span>
            </td>
            <td style="padding:.75rem 1.25rem;font-weight:700;color:#f97316">₦<?= number_format($p['price']) ?></td>
            <td style="padding:.75rem 1.25rem">
              <?php if(($p['category']??'') === 'accessory'): ?>
              <span style="background:<?= ($p['stock']??0)>0?'#f0fdf4':'#fef2f2' ?>;color:<?= ($p['stock']??0)>0?'#15803d':'#dc2626' ?>;font-size:.72rem;font-weight:700;padding:.2rem .65rem;border-radius:20px;border:1px solid <?= ($p['stock']??0)>0?'#bbf7d0':'#fecaca' ?>"><?= (int)($p['stock']??0) ?> units</span>
              <?php else: ?>
              <span style="color:#94a3b8;font-size:.75rem">—</span>
              <?php endif; ?>
            </td>
            <td style="padding:.75rem 1.25rem">
              <div style="display:flex;gap:.4rem">
                <a href="/stile-lpg/admin/products.php?edit=<?= urlencode($p['id']) ?>" style="background:#eff6ff;color:#2563eb;font-size:.75rem;font-weight:700;padding:.3rem .75rem;border-radius:8px;text-decoration:none">Edit</a>
                <a href="/stile-lpg/admin/products.php?delete=<?= urlencode($p['id']) ?>" onclick="return confirm('Delete this product?')" style="background:#fef2f2;color:#dc2626;font-size:.75rem;font-weight:700;padding:.3rem .75rem;border-radius:8px;text-decoration:none">Delete</a>
              </div>
            </td>
          </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
    <?php endif; ?>
  </div>

  <!-- Create / Edit form -->
  <div style="background:#fff;border-radius:20px;border:1px solid #e2e8f0;box-shadow:0 2px 12px rgba(0,0,0,.05);overflow:hidden;position:sticky;top:80px">
    <div style="background:linear-gradient(135deg,#0f172a,#1e293b);padding:1.25rem 1.5rem">
      <h3 style="color:#fff;font-weight:800;font-size:.95rem;margin:0"><?= $editProduct ? 'Edit Product' : 'Add New Product' ?></h3>
    </div>
    <form method="POST" enctype="multipart/form-data" style="padding:1.5rem;display:flex;flex-direction:column;gap:1rem">
      <input type="hidden" name="pid" value="<?= htmlspecialchars($editProduct['id']??'') ?>">
      <?php if($editProduct && $editProduct['image_url']): ?>
      <input type="hidden" name="keep_image" value="1">
      <?php endif; ?>
      <div>
        <label style="display:block;color:#475569;font-weight:700;font-size:.75rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.4rem">Name *</label>
        <input type="text" name="name" required value="<?= htmlspecialchars($editProduct['name']??'') ?>" style="font-family:inherit;font-size:.875rem;width:100%;padding:.7rem 1rem;border:2px solid #e2e8f0;border-radius:12px;outline:none" onfocus="this.style.borderColor='#f97316'" onblur="this.style.borderColor='#e2e8f0'">
      </div>
      <div>
        <label style="display:block;color:#475569;font-weight:700;font-size:.75rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.4rem">Category</label>
        <select name="category" id="categorySelect" onchange="toggleCategoryFields()" style="font-family:inherit;font-size:.875rem;width:100%;padding:.7rem 1rem;border:2px solid #e2e8f0;border-radius:12px;outline:none">
          <option value="lpg" <?= ($editProduct['category']??'lpg')==='lpg'?'selected':'' ?>>LPG Cylinder</option>
          <option value="accessory" <?= ($editProduct['category']??'')==='accessory'?'selected':'' ?>>Accessory</option>
        </select>
      </div>
      <div>
        <label style="display:block;color:#475569;font-weight:700;font-size:.75rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.4rem">Price (₦) *</label>
        <input type="number" name="price" required min="1" value="<?= htmlspecialchars($editProduct['price']??'') ?>" style="font-family:inherit;font-size:.875rem;width:100%;padding:.7rem 1rem;border:2px solid #e2e8f0;border-radius:12px;outline:none" onfocus="this.style.borderColor='#f97316'" onblur="this.style.borderColor='#e2e8f0'">
      </div>
      <!-- Stock: only for accessories -->
      <div id="stockField">
        <label style="display:block;color:#475569;font-weight:700;font-size:.75rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.4rem">Stock (units)</label>
        <input type="number" name="stock" id="stockInput" min="0" value="<?= htmlspecialchars($editProduct['stock']??'0') ?>" style="font-family:inherit;font-size:.875rem;width:100%;padding:.7rem 1rem;border:2px solid #e2e8f0;border-radius:12px;outline:none" onfocus="this.style.borderColor='#f97316'" onblur="this.style.borderColor='#e2e8f0'" placeholder="0">
        <p style="color:#94a3b8;font-size:.72rem;margin:.4rem 0 0">Set how many units are available. Stock decreases automatically when orders are placed.</p>
      </div>
      <div>
        <label style="display:block;color:#475569;font-weight:700;font-size:.75rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.4rem">Description</label>
        <textarea name="description" rows="3" style="font-family:inherit;font-size:.875rem;width:100%;padding:.7rem 1rem;border:2px solid #e2e8f0;border-radius:12px;outline:none;resize:vertical" onfocus="this.style.borderColor='#f97316'" onblur="this.style.borderColor='#e2e8f0'"><?= htmlspecialchars($editProduct['description']??'') ?></textarea>
      </div>
      <div id="imageField">
        <label style="display:block;color:#475569;font-weight:700;font-size:.75rem;letter-spacing:.05em;text-transform:uppercase;margin-bottom:.4rem">Product Image</label>
        <?php if($editProduct && $editProduct['image_url']): ?>
        <div style="margin-bottom:.75rem;border-radius:12px;overflow:hidden;border:2px solid #e2e8f0">
          <img src="<?= htmlspecialchars($editProduct['image_url']) ?>" alt="Current" style="width:100%;height:180px;object-fit:cover">
        </div>
        <p style="font-size:.75rem;color:#64748b;margin-bottom:.5rem">Keep current image or upload a new one below</p>
        <?php endif; ?>
        <input type="file" name="product_image" id="prodImageInput" accept="image/*" style="display:none" onchange="prodPreviewImage(event)">
        <label for="prodImageInput" style="display:block;cursor:pointer;background:#f8fafc;border:2px dashed #cbd5e1;border-radius:12px;padding:1.5rem;text-align:center;transition:all .2s" onmouseover="this.style.borderColor='#f97316';this.style.background='#fff7ed'" onmouseout="this.style.borderColor='#cbd5e1';this.style.background='#f8fafc'">
          <div style="margin-bottom:.5rem"><svg width="32" height="32" fill="none" stroke="#94a3b8" stroke-width="1.5" viewBox="0 0 24 24" style="margin:0 auto"><path stroke-linecap="round" stroke-linejoin="round" d="M3 16.5v2.25A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75V16.5m-13.5-9L12 3m0 0l4.5 4.5M12 3v13.5"/></svg></div>
          <div style="color:#475569;font-weight:700;font-size:.85rem;margin-bottom:.25rem">Click to upload image</div>
          <div style="color:#94a3b8;font-size:.75rem">JPG, PNG, WEBP or GIF — max 5MB</div>
        </label>
        <div id="prodPreviewContainer" style="display:none;margin-top:.75rem;position:relative;border-radius:12px;overflow:hidden;border:2px solid #e2e8f0">
          <img id="prodPreviewImg" style="width:100%;height:180px;object-fit:cover">
          <button type="button" onclick="prodClearPreview()" style="position:absolute;top:8px;right:8px;background:rgba(0,0,0,.7);color:#fff;border:none;border-radius:8px;padding:.4rem .75rem;font-size:.75rem;font-weight:700;cursor:pointer">&#x2715; Clear</button>
        </div>
      </div>
      <script>
      function prodPreviewImage(e){
        const file = e.target.files[0];
        if(file){
          const reader = new FileReader();
          reader.onload = function(e){
            document.getElementById('prodPreviewImg').src = e.target.result;
            document.getElementById('prodPreviewContainer').style.display = 'block';
          };
          reader.readAsDataURL(file);
        }
      }
      function prodClearPreview(){
        document.getElementById('prodImageInput').value = '';
        document.getElementById('prodPreviewContainer').style.display = 'none';
      }
      function toggleCategoryFields(){
        const cat = document.getElementById('categorySelect').value;
        const isAccessory = cat === 'accessory';
        document.getElementById('stockField').style.display = isAccessory ? 'block' : 'none';
        document.getElementById('imageField').style.display = isAccessory ? 'block' : 'none';
        if(!isAccessory){
          document.getElementById('stockInput').value = '0';
        }
      }
      // Run on page load to set correct initial state
      document.addEventListener('DOMContentLoaded', toggleCategoryFields);
      </script>
      <button type="submit" name="save_product" value="1" style="background:linear-gradient(135deg,#f97316,#fb923c);color:#fff;border:none;padding:.85rem;border-radius:12px;font-weight:700;font-size:.9rem;cursor:pointer;font-family:inherit;display:flex;align-items:center;justify-content:center;gap:.5rem">
        <svg width="16" height="16" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 3H5a2 2 0 00-2 2v14a2 2 0 002 2h14a2 2 0 002-2V7l-4-4z"/><path stroke-linecap="round" stroke-linejoin="round" d="M17 21v-8H7v8M7 3v4h8"/></svg>
        <?= $editProduct ? 'Update Product' : 'Create Product' ?>
      </button>
      <?php if($editProduct): ?>
      <a href="/stile-lpg/admin/products.php" style="text-align:center;color:#94a3b8;font-size:.82rem;font-weight:600;text-decoration:none">← Cancel edit</a>
      <?php endif; ?>
    </form>
  </div>
</div>

<style>@media(max-width:900px){.prod-grid{grid-template-columns:1fr!important}}</style>

<?php require_once __DIR__ . '/layout_bottom.php'; ?>
