<?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 services 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);
    }
    $short = trim((string)($_POST['short_description'] ?? ''));
    $full = trim((string)($_POST['full_description'] ?? ''));
    $icon = trim((string)($_POST['icon_class'] ?? 'flaticon-solar-panel'));
    $sort = (int)($_POST['sort_order'] ?? 0);
    if ($title === '') {
        $error = 'Title is required.';
    } else {
        $imgPath = $row['image_path'] ?? null;
        $up = admin_save_upload('image', 'services');
        if ($up) {
            $imgPath = $up;
        }
        try {
            if ($id > 0) {
                db()->prepare(
                    'UPDATE services SET title=?, slug=?, short_description=?, full_description=?, icon_class=?, image_path=?, sort_order=? WHERE id=?'
                )->execute([$title, $slug, $short, $full, $icon, $imgPath, $sort, $id]);
                admin_flash_set('success', 'Service updated successfully.');
            } else {
                db()->prepare(
                    'INSERT INTO services (title, slug, short_description, full_description, icon_class, image_path, sort_order) VALUES (?,?,?,?,?,?,?)'
                )->execute([$title, $slug, $short, $full, $icon, $imgPath, $sort]);
                $newId = (int)db()->lastInsertId();
                admin_flash_set('success', 'Service created successfully.');
                header('Location: service-view.php?id=' . $newId);
                exit;
            }
            header('Location: service-view.php?id=' . $id);
            exit;
        } catch (Throwable $e) {
            if (str_contains($e->getMessage(), 'Duplicate')) {
                $error = 'This slug is already used. Choose a different slug.';
            } else {
                $error = 'Could not save. Please try again.';
            }
        }
    }
}

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

$page = 'services';
$pageTitle = $id ? 'Edit service' : 'New service';
$pageSubtitle = 'Fields below appear on the services list and detail pages on your website.';
$breadcrumbs = [
    ['label' => 'Dashboard', 'href' => 'index.php'],
    ['label' => 'Services', 'href' => 'services.php'],
    ['label' => $id ? 'Edit' : 'New', 'href' => null],
];
$headerActions = '<a href="services.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left me-1"></i>Back to list</a>';
if ($id > 0 && $row) {
    $headerActions .= '<a href="service-view.php?id=' . $id . '" class="btn btn-outline-primary btn-sm">View details</a>';
    $headerActions .= '<a href="../service-detail.php?slug=' . rawurlencode((string)$row['slug']) . '" class="btn btn-outline-primary btn-sm" target="_blank" rel="noopener">Preview on site</a>';
}

require __DIR__ . '/includes/layout-header.php';

$r = $row ?: [
    'title' => '', 'slug' => '', 'short_description' => '', 'full_description' => '',
    'icon_class' => 'flaticon-solar-panel', 'image_path' => '', 'sort_order' => 0,
];
if ($error) {
    echo '<div class="alert alert-danger shadow-sm">' . 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">Basic information</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" placeholder="e.g. solar-rooftop-installation" value="<?= h((string)($_POST['slug'] ?? $r['slug'])) ?>">
          <div class="form-text">Leave blank to auto-generate from the title. Used in <code>service-detail.php?slug=…</code>.</div>
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Short description</label>
          <textarea name="short_description" class="form-control" rows="3" placeholder="Shown on cards and listings"><?= h((string)($_POST['short_description'] ?? $r['short_description'])) ?></textarea>
        </div>
        <div class="mb-0">
          <label class="form-label fw-semibold">Full description</label>
          <textarea name="full_description" class="form-control" rows="10" placeholder="Full text on the service detail page"><?= h((string)($_POST['full_description'] ?? $r['full_description'])) ?></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Display &amp; ordering</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Flaticon class</label>
          <?php $iconValue = (string)($_POST['icon_class'] ?? $r['icon_class']); ?>
          <select name="icon_class" class="form-select font-monospace">
            <option value="flaticon-thunderbolt" <?= $iconValue === 'flaticon-thunderbolt' ? 'selected' : '' ?>>flaticon-thunderbolt</option>
            <option value="flaticon-solar-panel" <?= $iconValue === 'flaticon-solar-panel' ? 'selected' : '' ?>>flaticon-solar-panel</option>
            <?php if ($iconValue !== '' && $iconValue !== 'flaticon-thunderbolt' && $iconValue !== 'flaticon-solar-panel'): ?>
              <option value="<?= h($iconValue) ?>" selected><?= h($iconValue) ?> (current)</option>
            <?php endif; ?>
          </select>
          <div class="form-text">Choose a supported service icon for frontend display.</div>
        </div>
        <div class="mb-0">
          <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 class="form-text">Lower numbers appear first.</div>
        </div>
      </div>
    </div>
    <div class="admin-card rounded mb-4">
      <div class="card-header">Featured image</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">Upload image</label>
        <input type="file" name="image" class="form-control" accept="image/jpeg,image/png,image/webp,image/gif">
        <div class="form-text">JPEG, PNG, WebP or GIF. Replaces the current image.</div>
      </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 service</button>
      <a href="services.php" class="btn btn-outline-secondary">Cancel</a>
    </div>
  </div>
</form>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
