<?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 = (int)($_GET['id'] ?? 0);
$row = null;
if ($id > 0) {
    $st = db()->prepare('SELECT * FROM clients WHERE id = ?');
    $st->execute([$id]);
    $row = $st->fetch();
}
$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_verify($_POST['csrf'] ?? null)) {
    $name = trim((string)($_POST['name'] ?? ''));
    $url = trim((string)($_POST['website_url'] ?? ''));
    $sort = (int)($_POST['sort_order'] ?? 0);
    if ($name === '') {
        $error = 'Name is required.';
    } else {
        $logo = $row['logo_path'] ?? null;
        $up = admin_save_upload('logo', 'clients');
        if ($up) {
            $logo = $up;
        }
        if ($id > 0) {
            db()->prepare('UPDATE clients SET name=?, logo_path=?, website_url=?, sort_order=? WHERE id=?')
                ->execute([$name, $logo, $url ?: null, $sort, $id]);
            admin_flash_set('success', 'Client updated.');
            header('Location: client-view.php?id=' . $id);
            exit;
        }
        db()->prepare('INSERT INTO clients (name, logo_path, website_url, sort_order) VALUES (?,?,?,?)')
            ->execute([$name, $logo, $url ?: null, $sort]);
        $nid = (int)db()->lastInsertId();
        admin_flash_set('success', 'Client added.');
        header('Location: client-view.php?id=' . $nid);
        exit;
    }
}
if ($id > 0 && !$row) {
    admin_flash_set('danger', 'Not found.');
    header('Location: clients.php');
    exit;
}
$page = 'clients';
$pageTitle = $id ? 'Edit client' : 'New client';
$pageSubtitle = 'Name and optional logo for the clients section.';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Clients', 'href' => 'clients.php'], ['label' => $id ? 'Edit' : 'New', 'href' => null]];
$headerActions = '<a href="clients.php" class="btn btn-outline-secondary btn-sm">Back to list</a>';
if ($id && $row) {
    $headerActions .= '<a href="client-view.php?id=' . $id . '" class="btn btn-outline-primary btn-sm">View</a>';
}
require __DIR__ . '/includes/layout-header.php';
$r = $row ?: ['name' => '', 'logo_path' => '', 'website_url' => '', '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">
      <div class="card-header">Client information</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Name <span class="text-danger">*</span></label>
          <input type="text" name="name" class="form-control" required value="<?= h((string)($_POST['name'] ?? $r['name'])) ?>">
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Website URL</label>
          <input type="url" name="website_url" class="form-control" placeholder="https://" value="<?= h((string)($_POST['website_url'] ?? $r['website_url'])) ?>">
        </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>
      </div>
    </div>
  </div>
  <div class="col-lg-4">
    <div class="admin-card rounded mb-3">
      <div class="card-header">Logo</div>
      <div class="card-body">
        <?php if (!empty($r['logo_path'])): ?><div class="mb-3 text-center"><img src="../<?= h((string)$r['logo_path']) ?>" style="max-height:100px;" alt=""></div><?php endif; ?>
        <input type="file" name="logo" class="form-control" accept="image/*">
        <div class="form-text">PNG/SVG-style logos work best on a transparent or white background.</div>
      </div>
    </div>
    <button type="submit" class="btn btn-primary btn-lg w-100 mb-2"><i class="bi bi-check-lg me-1"></i>Save</button>
    <a href="clients.php" class="btn btn-outline-secondary w-100">Cancel</a>
  </div>
</form>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
