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

if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM client_logos WHERE id=?", [$id]);
  header('Location: /admin/client-logos.php?deleted=1'); exit;
}
if ($action === 'toggle' && $id) {
  Database::execute("UPDATE client_logos SET is_active = NOT is_active WHERE id=?", [$id]);
  header('Location: /admin/client-logos.php'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $name     = trim($_POST['name'] ?? '');
  $website  = trim($_POST['website'] ?? '');
  $industry = trim($_POST['industry'] ?? '');
  $sort     = (int)($_POST['sort_order'] ?? 0);
  if (!$name) { $error = 'Client name is required.'; }
  else {
    $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 = 'client_' . time() . '_' . rand(100,999) . '.' . $ext;
        move_uploaded_file($_FILES['logo']['tmp_name'], UPLOAD_DIR . $fname);
        $logo = $fname;
      }
    }
    if ($id) {
      Database::execute("UPDATE client_logos SET name=?,logo=?,website=?,industry=?,sort_order=? WHERE id=?",
        [$name,$logo,$website,$industry,$sort,$id]);
      $success = 'Client logo updated.';
    } else {
      if (!$logo) { $error = 'Please upload a logo image.'; }
      else {
        Database::execute("INSERT INTO client_logos (name,logo,website,industry,sort_order,is_active) VALUES (?,?,?,?,?,1)",
          [$name,$logo,$website,$industry,$sort]);
        $success = 'Client logo added.'; $id = Database::lastInsertId(); $action = 'edit';
      }
    }
  }
}
$client = ($action==='edit'||$action==='new') && $id ? Database::fetchOne("SELECT * FROM client_logos WHERE id=?",[$id]) : null;
$clients = $action==='list' ? Database::fetchAll("SELECT * FROM client_logos ORDER BY sort_order,id") : [];
include dirname(__DIR__) . '/includes/admin-header.php';
?>

<div class="p-6 max-w-4xl">
  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-4">
    <div>
      <h1 class="text-xl font-bold">🏢 Client Logos</h1>
      <p class="text-sm text-gray-400 mt-1">Logos are displayed in the "Trusted By" section on the homepage.</p>
    </div>
    <a href="?action=new" class="btn-primary text-sm px-4 py-2">+ Add Client</a>
  </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; ?>
  <?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; ?>

  <!-- Logo Preview -->
  <?php if ($clients): ?>
  <div class="card-dark p-5 mb-6">
    <h3 class="text-xs font-semibold text-orange-400 uppercase mb-3">Preview on Dark Background</h3>
    <div class="flex flex-wrap gap-6 items-center">
      <?php foreach ($clients as $c): if (!$c['is_active']) continue; ?>
      <div class="text-center opacity-60 hover:opacity-100 transition-opacity">
        <img src="/uploads/<?= e($c['logo']) ?>" alt="<?= e($c['name']) ?>" class="h-10 object-contain filter brightness-90">
        <div class="text-xs text-gray-500 mt-1"><?= e($c['name']) ?></div>
      </div>
      <?php endforeach; ?>
    </div>
  </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">Client Name</th><th class="px-4 py-3 text-left">Industry</th><th class="px-4 py-3 text-left">#</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$clients): ?><tr><td colspan="6" class="px-4 py-8 text-center text-gray-500">No clients yet. <a href="?action=new" class="text-orange-400">Add first client →</a></td></tr><?php endif; ?>
        <?php foreach ($clients as $c): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3"><img src="/uploads/<?= e($c['logo']) ?>" alt="<?= e($c['name']) ?>" class="h-8 object-contain max-w-[80px]"></td>
          <td class="px-4 py-3 font-medium"><?= e($c['name']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($c['industry'] ?: '—') ?></td>
          <td class="px-4 py-3 text-gray-500"><?= $c['sort_order'] ?></td>
          <td class="px-4 py-3"><a href="?action=toggle&id=<?= $c['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $c['is_active'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>"><?= $c['is_active'] ? 'Shown' : 'Hidden' ?></a></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $c['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <a href="?action=delete&id=<?= $c['id'] ?>" class="text-xs text-red-400 hover:underline" onclick="return confirm('Remove this client logo?')">Remove</a>
          </td>
        </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>

  <?php else: ?>
  <div class="flex items-center gap-3 mb-6">
    <a href="/admin/client-logos.php" class="text-gray-400 hover:text-white text-sm">← All Clients</a>
    <h1 class="text-xl font-bold"><?= $id ? 'Edit Client Logo' : 'Add Client Logo' ?></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-lg">
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Client / Company Name *</label>
      <input type="text" name="name" value="<?= e($client['name'] ?? '') ?>" class="input-field" required placeholder="e.g. OGDCL">
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Industry</label>
      <input type="text" name="industry" value="<?= e($client['industry'] ?? '') ?>" class="input-field" placeholder="e.g. Oil & Gas E&P">
    </div>
    <div class="mb-4">
      <label class="block text-xs text-gray-400 mb-1">Website (optional)</label>
      <input type="url" name="website" value="<?= e($client['website'] ?? '') ?>" class="input-field" placeholder="https://www.ogdcl.com">
    </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($client['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">Logo Image * (PNG transparent recommended)</label>
      <?php if (!empty($client['logo'])): ?>
      <img src="/uploads/<?= e($client['logo']) ?>" class="h-12 mb-2 object-contain bg-gray-700 p-1 rounded">
      <input type="hidden" name="existing_logo" value="<?= e($client['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">PNG with transparent background looks best on the dark site. Recommended width: 200px.</p>
    </div>
    <div class="flex gap-3">
      <button type="submit" class="btn-primary px-6 py-2.5">Save</button>
      <a href="/admin/client-logos.php" class="btn-outline px-6 py-2.5">Cancel</a>
    </div>
  </form>
  <?php endif; ?>
</div>

<?php include dirname(__DIR__) . '/includes/admin-footer.php'; ?>
