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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['seed_dummy']) && csrf_verify($_POST['csrf'] ?? null)) {
    $existing = (int)db()->query('SELECT COUNT(*) FROM projects')->fetchColumn();
    if ($existing > 0) {
        admin_flash_set('info', 'Dummy projects were not inserted because you already have projects.');
        header('Location: projects.php');
        exit;
    }

    $dummy = [
        [
            'title' => 'Residential Rooftop Solar Installation',
            'slug' => 'residential-rooftop-solar-installation',
            'category' => 'Residential',
            'description' => 'Complete on-grid rooftop solar setup including site survey, system design, installation, wiring, and commissioning for a home to reduce electricity bills.',
            'image_path' => 'assets/img/about/ab-img-3-1.jpg',
            'sort_order' => 1,
        ],
        [
            'title' => 'Commercial Solar Power Plant Setup',
            'slug' => 'commercial-solar-power-plant-setup',
            'category' => 'Commercial',
            'description' => 'End-to-end solar solution for a commercial property focused on high performance, safe installation, and long-term savings with clean energy generation.',
            'image_path' => 'assets/img/about/ab-img-3-2.jpg',
            'sort_order' => 2,
        ],
        [
            'title' => 'Solar Inverter & Battery Integration',
            'slug' => 'solar-inverter-battery-integration',
            'category' => 'Equipment',
            'description' => 'Supplying and integrating solar inverters, batteries, and charge controllers with proper sizing and configuration to ensure reliable power output.',
            'image_path' => 'assets/img/bg/service-bg-3-1.jpg',
            'sort_order' => 3,
        ],
        [
            'title' => 'System Maintenance & Performance Check',
            'slug' => 'system-maintenance-performance-check',
            'category' => 'Maintenance',
            'description' => 'Inspection, cleaning guidance, safety checks, and troubleshooting to keep your solar system delivering consistent performance over time.',
            'image_path' => 'assets/img/bg/choose-bg-2-1.jpg',
            'sort_order' => 4,
        ],
    ];

    $ins = db()->prepare(
        'INSERT INTO projects (title, slug, description, image_path, category, sort_order) VALUES (?,?,?,?,?,?)'
    );
    foreach ($dummy as $p) {
        $ins->execute([$p['title'], $p['slug'], $p['description'], $p['image_path'], $p['category'], $p['sort_order']]);
    }
    admin_flash_set('success', 'Dummy projects inserted successfully.');
    header('Location: projects.php');
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_id']) && csrf_verify($_POST['csrf'] ?? null)) {
    $id = (int)$_POST['delete_id'];
    if ($id > 0) {
        db()->prepare('DELETE FROM projects WHERE id = ?')->execute([$id]);
        admin_flash_set('success', 'Project deleted.');
    }
    header('Location: projects.php');
    exit;
}

$perPage = 12;
$q = trim((string)($_GET['q'] ?? ''));
$pageNum = max(1, (int)($_GET['page'] ?? 1));
$where = '';
$params = [];
if ($q !== '') {
    $where = 'WHERE title LIKE ? OR slug LIKE ? OR description LIKE ? OR category LIKE ?';
    $qq = '%' . $q . '%';
    $params = [$qq, $qq, $qq, $qq];
}
$stc = db()->prepare('SELECT COUNT(*) FROM projects ' . $where);
$stc->execute($params);
$total = (int)$stc->fetchColumn();
$pages = max(1, (int)ceil($total / $perPage));
if ($pageNum > $pages) {
    $pageNum = $pages;
}
$offset = ($pageNum - 1) * $perPage;
$st = db()->prepare('SELECT * FROM projects ' . $where . ' ORDER BY sort_order ASC, id ASC LIMIT ' . (int)$perPage . ' OFFSET ' . (int)$offset);
$st->execute($params);
$rows = $st->fetchAll();

$page = 'projects';
$pageTitle = 'Projects';
$pageSubtitle = 'Portfolio items shown on the website (listing and project detail pages).';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Projects', 'href' => null]];
$headerActions = '<a href="project-edit.php" class="btn btn-primary"><i class="bi bi-plus-lg me-1"></i>Add project</a>'
  . '<form method="post" class="d-inline ms-2" onsubmit="return confirm(\'Insert dummy projects? Only works when no projects exist yet.\');">'
  . '<input type="hidden" name="csrf" value="' . h(csrf_token()) . '">'
  . '<input type="hidden" name="seed_dummy" value="1">'
  . '<button type="submit" class="btn btn-outline-secondary"><i class="bi bi-magic me-1"></i>Insert dummy projects</button>'
  . '</form>';
require __DIR__ . '/includes/layout-header.php';
?>
<div class="admin-card rounded mb-3">
  <div class="card-body py-3">
    <form method="get" class="row g-2 align-items-end">
      <div class="col-md-6 col-lg-4">
        <label class="form-label small text-muted mb-1">Search</label>
        <input type="text" name="q" class="form-control" placeholder="Title, slug, category, description…" value="<?= h($q) ?>">
      </div>
      <div class="col-auto">
        <button type="submit" class="btn btn-outline-primary"><i class="bi bi-search me-1"></i>Search</button>
        <?php if ($q !== ''): ?><a href="projects.php" class="btn btn-outline-secondary">Clear</a><?php endif; ?>
      </div>
    </form>
  </div>
</div>
<div class="admin-card rounded">
  <div class="card-header py-3">All projects (<?= $total ?>)</div>
  <div class="table-responsive">
    <table class="table table-hover admin-table mb-0">
      <thead>
        <tr>
          <th>ID</th>
          <th>Image</th>
          <th>Title</th>
          <th>Category</th>
          <th>Slug</th>
          <th>Order</th>
          <th>Created</th>
          <th class="text-end">Actions</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <td class="text-muted"><?= (int)$r['id'] ?></td>
            <td><?php if (!empty($r['image_path'])): ?><img src="../<?= h((string)$r['image_path']) ?>" class="admin-thumb" alt=""><?php else: ?><span class="text-muted small">—</span><?php endif; ?></td>
            <td class="fw-semibold"><?= h((string)$r['title']) ?></td>
            <td><?= h((string)($r['category'] ?? '—')) ?></td>
            <td><code class="small"><?= h((string)$r['slug']) ?></code></td>
            <td><?= (int)$r['sort_order'] ?></td>
            <td class="small text-muted"><?= h((string)$r['created_at']) ?></td>
            <td class="text-end text-nowrap">
              <a href="project-view.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-secondary">View</a>
              <a href="project-edit.php?id=<?= (int)$r['id'] ?>" class="btn btn-sm btn-outline-primary">Edit</a>
              <form method="post" class="d-inline" onsubmit="return confirm('Delete this project?');">
                <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
                <input type="hidden" name="delete_id" value="<?= (int)$r['id'] ?>">
                <button type="submit" class="btn btn-sm btn-outline-danger">Delete</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <?php if (!$rows): ?>
    <div class="card-body text-center text-muted py-5">No projects. <a href="project-edit.php">Add one</a>.</div>
  <?php endif; ?>
</div>
<?= admin_pagination($total, $pageNum, $perPage) ?>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
