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

if ($action === 'delete' && $id) {
  Database::execute("DELETE FROM projects WHERE id=?", [$id]);
  header('Location: /admin/projects.php?deleted=1'); exit;
}
if ($action === 'toggle' && $id) {
  Database::execute("UPDATE projects SET is_active = NOT is_active WHERE id=?", [$id]);
  header('Location: /admin/projects.php'); exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $title       = trim($_POST['title'] ?? '');
  $slug        = trim($_POST['slug'] ?? '');
  $clientName  = trim($_POST['client_name'] ?? '');
  $industry    = trim($_POST['industry'] ?? '');
  $scope       = trim($_POST['scope'] ?? '');
  $desc        = trim($_POST['description'] ?? '');
  $body        = trim($_POST['body'] ?? '');
  $compDate    = trim($_POST['completion_date'] ?? '') ?: null;
  $featured    = isset($_POST['is_featured']) ? 1 : 0;
  $sort        = (int)($_POST['sort_order'] ?? 0);
  if (!$title) { $error = 'Title is required.'; }
  else {
    if (!$slug) $slug = strtolower(preg_replace('/[^a-z0-9]+/i', '-', $title));
    $slug = preg_replace('/[^a-z0-9\-]/', '', strtolower($slug));
    $slug = trim($slug, '-');
    $image = $_POST['existing_image'] ?? null;
    $clientLogo = $_POST['existing_client_logo'] ?? null;
    foreach ([['image', &$image, 'proj_'], ['client_logo', &$clientLogo, 'cl_']] as [$field, &$var, $prefix]) {
      if (!empty($_FILES[$field]['tmp_name'])) {
        $ext = strtolower(pathinfo($_FILES[$field]['name'], PATHINFO_EXTENSION));
        if (in_array($ext, ['jpg','jpeg','png','webp','svg'])) {
          $fname = $prefix . time() . '_' . rand(100,999) . '.' . $ext;
          move_uploaded_file($_FILES[$field]['tmp_name'], UPLOAD_PATH . '/' . $fname);
          $var = $fname;
        }
      }
    }
    if ($id) {
      Database::execute("UPDATE projects SET title=?,slug=?,client_name=?,client_logo=?,industry=?,scope=?,description=?,body=?,image=?,completion_date=?,is_featured=?,sort_order=? WHERE id=?",
        [$title,$slug,$clientName,$clientLogo,$industry,$scope,$desc,$body,$image,$compDate,$featured,$sort,$id]);
      $success = 'Project updated.';
    } else {
      $id = Database::insert("INSERT INTO projects (title,slug,client_name,client_logo,industry,scope,description,body,image,completion_date,is_featured,sort_order,is_active) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,1)",
        [$title,$slug,$clientName,$clientLogo,$industry,$scope,$desc,$body,$image,$compDate,$featured,$sort]);
      $success = 'Project added.'; $action = 'edit';
    }
  }
}
$project = ($action==='edit'||$action==='new') && $id ? Database::fetchOne("SELECT * FROM projects WHERE id=?",[$id]) : null;
$projects = $action==='list' ? Database::fetchAll("SELECT * FROM projects ORDER BY sort_order,id DESC") : [];
include __DIR__ . '/includes/header.php';
?>

<div class="p-6 max-w-5xl">
  <?php if ($action === 'list'): ?>
  <div class="flex items-center justify-between mb-6">
    <h1 class="text-xl font-bold">🏗️ Projects & Case Studies</h1>
    <div class="flex gap-3">
      <a href="/projects.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 Project</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">Title</th><th class="px-4 py-3 text-left">Client</th><th class="px-4 py-3 text-left">Industry</th><th class="px-4 py-3 text-left">Date</th><th class="px-4 py-3 text-left">Featured</th><th class="px-4 py-3 text-left">Status</th><th class="px-4 py-3"></th></tr>
      </thead>
      <tbody>
        <?php if (!$projects): ?><tr><td colspan="7" class="px-4 py-8 text-center text-gray-500">No projects yet. <a href="?action=new" class="text-orange-400">Add first →</a></td></tr><?php endif; ?>
        <?php foreach ($projects as $p): ?>
        <tr class="border-t border-navy-600 hover:bg-navy-800">
          <td class="px-4 py-3 font-medium max-w-xs truncate"><?= e($p['title']) ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($p['client_name'] ?: '—') ?></td>
          <td class="px-4 py-3 text-gray-400"><?= e($p['industry'] ?: '—') ?></td>
          <td class="px-4 py-3 text-gray-400 text-xs"><?= $p['completion_date'] ? date('M Y', strtotime($p['completion_date'])) : '—' ?></td>
          <td class="px-4 py-3"><?= $p['is_featured'] ? '<span class="text-xs text-orange-400">★ Yes</span>' : '—' ?></td>
          <td class="px-4 py-3"><a href="?action=toggle&id=<?= $p['id'] ?>" class="text-xs px-2 py-1 rounded-full font-semibold <?= $p['is_active'] ? 'bg-green-600/10 text-green-400' : 'bg-gray-600/10 text-gray-400' ?>"><?= $p['is_active'] ? 'Active' : 'Hidden' ?></a></td>
          <td class="px-4 py-3 flex gap-2">
            <a href="?action=edit&id=<?= $p['id'] ?>" class="text-xs text-orange-400 hover:underline">Edit</a>
            <a href="?action=delete&id=<?= $p['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/projects.php" class="text-gray-400 hover:text-white text-sm">← All Projects</a>
    <h1 class="text-xl font-bold"><?= $id ? 'Edit Project' : 'New Project / Case Study' ?></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="grid grid-cols-1 lg:grid-cols-3 gap-6">
    <div class="lg:col-span-2 space-y-5">
      <div class="card-dark p-5">
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Project Title *</label>
          <input type="text" name="title" value="<?= e($project['title'] ?? '') ?>" class="input-field" required placeholder="e.g. API 6A Valve Package — OGDCL Tal Block">
        </div>
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Scope (1 line)</label>
          <input type="text" name="scope" value="<?= e($project['scope'] ?? '') ?>" class="input-field" placeholder="e.g. 48 API 6A gate valves, 2–4 inch, 5000 PSI WP">
        </div>
        <div>
          <label class="block text-xs text-gray-400 mb-1">Short Description (shown on listing)</label>
          <textarea name="description" rows="3" class="input-field" placeholder="Brief description..."><?= e($project['description'] ?? '') ?></textarea>
        </div>
      </div>
      <div class="card-dark p-5">
        <label class="block text-xs text-gray-400 mb-1">Full Case Study (HTML supported, optional)</label>
        <textarea name="body" rows="12" class="input-field font-mono text-xs" placeholder="<h2>Challenge</h2><p>...</p><h2>Solution</h2>..."><?= e($project['body'] ?? '') ?></textarea>
      </div>
    </div>
    <div class="space-y-5">
      <div class="card-dark p-5">
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Client Name</label>
          <input type="text" name="client_name" value="<?= e($project['client_name'] ?? '') ?>" class="input-field" 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($project['industry'] ?? '') ?>" class="input-field" list="ind-list">
          <datalist id="ind-list"><option>Oil & Gas</option><option>Mining</option><option>Pipeline</option><option>Refinery</option><option>Earthmoving</option><option>Asphalt Plants</option><option>Construction</option></datalist>
        </div>
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Completion Date</label>
          <input type="date" name="completion_date" value="<?= e($project['completion_date'] ?? '') ?>" class="input-field">
        </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($project['sort_order'] ?? 0) ?>" class="input-field" min="0">
        </div>
        <div>
          <label class="flex items-center gap-2 cursor-pointer">
            <input type="checkbox" name="is_featured" value="1" <?= !empty($project['is_featured']) ? 'checked' : '' ?> class="w-4 h-4 accent-orange-600">
            <span class="text-sm">Featured project</span>
          </label>
        </div>
      </div>
      <div class="card-dark p-5">
        <div class="mb-4">
          <label class="block text-xs text-gray-400 mb-1">Project Image</label>
          <?php if (!empty($project['image'])): ?><img src="/uploads/<?= e($project['image']) ?>" class="w-full h-24 object-cover rounded mb-1"><input type="hidden" name="existing_image" value="<?= e($project['image']) ?>"><?php endif; ?>
          <input type="file" name="image" accept="image/*" class="text-xs text-gray-400">
        </div>
        <div>
          <label class="block text-xs text-gray-400 mb-1">Client Logo</label>
          <?php if (!empty($project['client_logo'])): ?><img src="/uploads/<?= e($project['client_logo']) ?>" class="h-8 mb-1 object-contain"><input type="hidden" name="existing_client_logo" value="<?= e($project['client_logo']) ?>"><?php endif; ?>
          <input type="file" name="client_logo" accept="image/*" class="text-xs text-gray-400">
        </div>
      </div>
      <div class="flex gap-3">
        <button type="submit" class="btn-primary flex-1 py-2.5">Save Project</button>
        <a href="/admin/projects.php" class="btn-outline px-4 py-2.5">Cancel</a>
      </div>
    </div>
  </form>
  <?php endif; ?>
</div>

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