<?php
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();
$pageTitle = 'Brands Management';
$success = $error = '';
$action = $_GET['action'] ?? 'list';
$id = (int)($_GET['id'] ?? 0);

if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM brands WHERE id=?", [$id]);
  header('Location: /admin/brands.php?deleted=1'); exit;
}
if ($action === 'toggle' && $id) {
  Database::execute("UPDATE brands SET is_active = NOT is_active WHERE id=?", [$id]);
  header('Location: /admin/brands.php'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name     = trim($_POST['name'] ?? '');
  $slug     = trim($_POST['slug'] ?? '');
  $desc     = trim($_POST['description'] ?? '');
  $website  = trim($_POST['website'] ?? '');
  $country  = trim($_POST['origin_country'] ?? '');
  $category = trim($_POST['category'] ?? '');
  $sort     = (int)($_POST['sort_order'] ?? 0);
  if (!$name) { $error = 'Brand name is required.'; }
  else {
    if (!$slug) $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $name));
    $slug = preg_replace('/[^a-z0-9\-]/', '', strtolower($slug));
    $slug = trim($slug, '-');
    $logo = $_POST['existing_logo'] ?? null;
    if (!empty($_FILES['logo']['tmp_name'])) {
      $ext = strtolower(pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION));
      if (in_array($ext, ['jpg','jpeg','png','webp','svg'])) {
        $fname = 'brand_' . time() . '_' . $slug . '.' . $ext;
        move_uploaded_file($_FILES['logo']['tmp_name'], UPLOAD_PATH . '/' . $fname);
        $logo = $fname;
      }
    }
    if ($id) {
      Database::execute("UPDATE brands SET name=?,slug=?,description=?,website=?,origin_country=?,category=?,logo=?,sort_order=? WHERE id=?",
        [$name,$slug,$desc,$website,$country,$category,$logo,$sort,$id]);
      $success = 'Brand updated.';
    } else {
      $id = Database::insert("INSERT INTO brands (name,slug,description,website,origin_country,category,logo,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?,1)",
        [$name,$slug,$desc,$website,$country,$category,$logo,$sort]);
      $success = 'Brand added.'; $action = 'edit';
    }
  }
}
$brand = ($action==='edit'||$action==='new') && $id ? Database::fetchOne("SELECT * FROM brands WHERE id=?",[$id]) : null;
$brands = $action==='list' ? Database::fetchAll("SELECT * FROM brands ORDER BY sort_order,name") : [];
require_once __DIR__ . '/includes/header.php';
?>

<div class="max-w-5xl">
  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">🏷️ Brands & Principals</h1>
    <div class="flex gap-3">
      <a href="/brands.php" target="_blank" class="btn-outline text-sm px-3 py-2">View Public Page ↗</a>
      <a href="?action=new" class="btn-primary text-sm px-4 py-2">+ Add Brand</a>
    </div>
  </div>
  <?php if (isset($_GET['deleted'])): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4">Deleted.</div><?php endif; ?>
  <div class="card-dark overflow-hidden">
    <table class="w-full text-sm">
      <thead class="bg-navy-700 text-xs text-gray-400 uppercase">
        <tr><th class="px-4 py-3 text-left">Logo</th><th class="px-4 py-3 text-left">Brand</th><th class="px-4 py-3 text-left">Category</th><th class="px-4 py-3 text-left">Country</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$brands): ?><tr><td colspan="6" class="px-4 py-8 text-center text-gray-500">No brands yet. <a href="?action=new" class="text-orange-400">Add first →</a></td></tr><?php endif; ?>
        <?php foreach ($brands as $b): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3">
            <?php if ($b['logo']): ?>
            <img src="/uploads/<?= e($b['logo']) ?>" alt="<?= e($b['name']) ?>" class="h-8 object-contain">
            <?php else: ?><span class="text-xs text-gray-500">No logo</span><?php endif; ?>
          </td>
          <td class="px-4 py-3 font-medium"><?= e($b['name']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($b['category']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($b['origin_country']) ?></td>
          <td class="px-4 py-3"><a href="?action=toggle&id=<?= $b['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $b['is_active'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>"><?= $b['is_active'] ? 'Active' : 'Hidden' ?></a></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $b['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <a href="?action=delete&id=<?= $b['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Delete?')">Delete</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php else: ?>
  <div class="flex items-center gap-3 mb-6">
    <a href="/admin/brands.php" class="text-gray-400 hover:text-white text-sm">← All Brands</a>
    <h1 class="text-xl font-bold"><?= $id ? 'Edit Brand' : 'New Brand' ?></h1>
  </div>
  <?php if ($success): ?><div class="bg-green-600/10 border border-green-600/30 text-green-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($success) ?></div><?php endif; ?>
  <?php if ($error): ?><div class="bg-red-600/10 border border-red-600/30 text-red-400 text-sm px-4 py-3 rounded-lg mb-4"><?= e($error) ?></div><?php endif; ?>
  <form method="POST" enctype="multipart/form-data" class="card-dark p-6 max-w-2xl">
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Brand Name *</label>
        <input type="text" name="name" value="<?= e($brand['name'] ?? '') ?>" class="input-field" required>
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">URL Slug</label>
        <input type="text" name="slug" value="<?= e($brand['slug'] ?? '') ?>" class="input-field" placeholder="auto-generated">
      </div>
    </div>
    <div class="grid grid-cols-2 gap-4 mb-4">
      <div>
        <label class="block text-xs text-gray-400 mb-1">Category</label>
        <input type="text" name="category" value="<?= e($brand['category'] ?? '') ?>" class="input-field" list="brand-cats" placeholder="e.g. Valves">
        <datalist id="brand-cats"><option>Valves & Wellhead</option><option>Flanges & Fittings</option><option>Hydraulics</option><option>Earthmoving Spares</option><option>Control Valves</option><option>Flow Control</option></datalist>
      </div>
      <div>
        <label class="block text-xs text-gray-400 mb-1">Country of Origin</label>
        <input type="text" name="origin_country" value="<?= e($brand['origin_country'] ?? '') ?>" class="input-field" placeholder="USA">
      </div>
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Website URL</label>
      <input type="url" name="website" value="<?= e($brand['website'] ?? '') ?>" class="input-field" placeholder="https://www.example.com">
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Description</label>
      <textarea name="description" rows="3" class="input-field" placeholder="Brief description of the brand and their products..."><?= e($brand['description'] ?? '') ?></textarea>
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Sort Order</label>
      <input type="number" name="sort_order" value="<?= e($brand['sort_order'] ?? 0) ?>" class="input-field w-24" min="0">
    </div>
    <div class="mb-5">
      <label class="block text-xs text-gray-400 mb-1">Brand Logo (PNG/SVG recommended)</label>
      <?php if (!empty($brand['logo'])): ?>
      <img src="/uploads/<?= e($brand['logo']) ?>" alt="" class="h-12 mb-2 object-contain">
      <input type="hidden" name="existing_logo" value="<?= e($brand['logo']) ?>">
      <?php endif; ?>
      <input type="file" name="logo" accept="image/*,.svg" class="text-sm text-gray-400">
      <p class="text-xs text-gray-500 mt-1">Upload PNG with transparent background or SVG for best results.</p>
    </div>
    <div class="flex gap-3">
      <button type="submit" class="btn-primary px-6 py-2.5">Save Brand</button>
      <a href="/admin/brands.php" class="btn-outline px-6 py-2.5">Cancel</a>
    </div>
  </form>
  <?php endif; ?>

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