<?php
declare(strict_types=1);
require_once __DIR__ . '/includes/bootstrap.php';
require_once __DIR__ . '/includes/flash.php';
require_once __DIR__ . '/includes/upload.php';
require_admin();
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$row = null;
if ($id > 0) {
    $st = db()->prepare('SELECT * FROM projects WHERE id = ?');
    $st->execute([$id]);
    $row = $st->fetch();
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify($_POST['csrf'] ?? null)) {
    $title = trim((string)($_POST['title'] ?? ''));
    $slug = trim((string)($_POST['slug'] ?? ''));
    if ($slug === '') {
        $slug = slugify($title);
    }
    $desc = trim((string)($_POST['description'] ?? ''));
    $cat = trim((string)($_POST['category'] ?? ''));
    $sort = (int)($_POST['sort_order'] ?? 0);
    if ($title === '') {
        $error = 'Title is required.';
    } else {
        $imgPath = $row['image_path'] ?? null;
        $up = admin_save_upload('image', 'projects');
        if ($up) {
            $imgPath = $up;
        }
        try {
            if ($id > 0) {
                db()->prepare(
                    'UPDATE projects SET title=?, slug=?, description=?, image_path=?, category=?, sort_order=? WHERE id=?'
                )->execute([$title, $slug, $desc, $imgPath, $cat, $sort, $id]);
                admin_flash_set('success', 'Project updated.');
                header('Location: project-view.php?id=' . $id);
                exit;
            }
            db()->prepare(
                'INSERT INTO projects (title, slug, description, image_path, category, sort_order) VALUES (?,?,?,?,?,?)'
            )->execute([$title, $slug, $desc, $imgPath, $cat, $sort]);
            $newId = (int)db()->lastInsertId();
            admin_flash_set('success', 'Project created.');
            header('Location: project-view.php?id=' . $newId);
            exit;
        } catch (Throwable $e) {
            $error = str_contains($e->getMessage(), 'Duplicate') ? 'Slug already in use. Change the slug.' : 'Could not save.';
        }
    }
}

if ($id > 0 && !$row) {
    admin_flash_set('danger', 'Project not found.');
    header('Location: projects.php');
    exit;
}

$page = 'projects';
$pageTitle = $id ? 'Edit project' : 'New project';
$pageSubtitle = 'Shown on the portfolio grid and project detail page.';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Projects', 'href' => 'projects.php'], ['label' => $id ? 'Edit' : 'New', 'href' => null]];
$headerActions = '<a href="projects.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left me-1"></i>Back</a>';
if ($id > 0 && $row) {
    $headerActions .= '<a href="project-view.php?id=' . $id . '" class="btn btn-outline-primary btn-sm">View</a>';
    $headerActions .= '<a href="../project-detail.php?slug=' . rawurlencode((string)$row['slug']) . '" class="btn btn-outline-primary btn-sm" target="_blank" rel="noopener">Preview</a>';
}

require __DIR__ . '/includes/layout-header.php';
$r = $row ?: ['title' => '', 'slug' => '', 'description' => '', 'image_path' => '', 'category' => '', 'sort_order' => 0];
if ($error) {
    echo '<div class="alert alert-danger">' . h($error) . '</div>';
}
?>
<form method="post" enctype="multipart/form-data" class="row g-4">
  <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
  <div class="col-lg-8">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Project content</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Title <span class="text-danger">*</span></label>
          <input type="text" name="title" class="form-control" required value="<?= h((string)($_POST['title'] ?? $r['title'])) ?>">
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">URL slug</label>
          <input type="text" name="slug" class="form-control font-monospace" value="<?= h((string)($_POST['slug'] ?? $r['slug'])) ?>">
          <div class="form-text">Auto-generated from title if left blank.</div>
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Category</label>
          <input type="text" name="category" class="form-control" placeholder="e.g. Residential, Commercial" value="<?= h((string)($_POST['category'] ?? $r['category'])) ?>">
        </div>
        <div class="mb-0">
          <label class="form-label fw-semibold">Description</label>
          <textarea name="description" class="form-control" rows="12"><?= h((string)($_POST['description'] ?? $r['description'])) ?></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Image &amp; order</div>
      <div class="card-body">
        <?php if (!empty($r['image_path'])): ?>
          <div class="mb-3 text-center"><img src="../<?= h((string)$r['image_path']) ?>" class="img-fluid rounded border" style="max-height:160px;" alt=""></div>
        <?php endif; ?>
        <label class="form-label fw-semibold">Featured image</label>
        <input type="file" name="image" class="form-control mb-3" accept="image/*">
        <label class="form-label fw-semibold">Sort order</label>
        <input type="number" name="sort_order" class="form-control" value="<?= (int)($_POST['sort_order'] ?? $r['sort_order']) ?>">
      </div>
    </div>
    <div class="d-grid gap-2">
      <button type="submit" class="btn btn-primary btn-lg"><i class="bi bi-check-lg me-1"></i>Save project</button>
      <a href="projects.php" class="btn btn-outline-secondary">Cancel</a>
    </div>
  </div>
</form>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
