<?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 banners WHERE id = ?');
    $st->execute([$id]);
    $row = $st->fetch();
}
$uploadIni = ini_get('upload_max_filesize') ?: '8M';
$postIni = ini_get('post_max_size') ?: '8M';
$maxVideoBytes = min(admin_ini_bytes('upload_max_filesize'), admin_ini_bytes('post_max_size'));

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (admin_post_body_too_large()) {
        $cl = (int) ($_SERVER['CONTENT_LENGTH'] ?? 0);
        $postMb = max(0.1, round(admin_ini_bytes('post_max_size') / 1048576, 1));
        $upMb = max(0.1, round(admin_ini_bytes('upload_max_filesize') / 1048576, 1));
        $reqMb = round($cl / 1048576, 1);
        $error = 'The upload never reached the app: this request is about ' . $reqMb . ' MB but PHP is set to accept at most ~' . $postMb . ' MB per request (post_max_size) and ~' . $upMb . ' MB per file (upload_max_filesize). After uploading the updated `.user.ini` / `.htaccess` from the project root, wait a few minutes or restart PHP, then try again. If it still fails, ask your host to raise both limits to 64M or higher.';
    } elseif (!csrf_verify($_POST['csrf'] ?? null)) {
        $error = 'Security check failed. Please reload the page and try again.';
    } else {
    $title = trim((string)($_POST['title'] ?? ''));
    $sub = trim((string)($_POST['subtitle'] ?? ''));
    $hl = trim((string)($_POST['highlight_html'] ?? ''));
    $isVideo = !empty($_POST['is_video']) ? 1 : 0;
    $videoPath = trim((string)($_POST['video_path'] ?? ''));
    $sort = (int)($_POST['sort_order'] ?? 0);
    $active = !empty($_POST['is_active']) ? 1 : 0;
    if ($title === '') {
        $error = 'Title is required.';
    } else {
        if ($isVideo && !empty($_FILES['video_file']['name'])) {
            $videoUp = admin_save_video_upload('video_file');
            if (!$videoUp['ok']) {
                $error = $videoUp['error'];
            } else {
                $videoPath = $videoUp['path'];
            }
        }
        if ($error === '' && $isVideo && $videoPath === '' && $row && !empty($row['video_path'])) {
            $videoPath = (string)$row['video_path'];
        }
        if ($error === '' && $isVideo && $videoPath === '') {
            $error = 'Video background needs an uploaded MP4/WebM file or a path to an existing file (e.g. assets/img/slider/solar.mp4).';
        }

        $imgPath = $row['image_path'] ?? null;
        if (!$isVideo) {
            $up = admin_save_upload('image', 'banners');
            if ($up) {
                $imgPath = $up;
            }
        } elseif ($row) {
            $imgPath = $row['image_path'] ?? null;
        }

        $storeVideoPath = $isVideo ? ($videoPath !== '' ? $videoPath : null) : null;

        if ($error === '') {
            if ($id > 0) {
                db()->prepare(
                    'UPDATE banners SET title=?, subtitle=?, highlight_html=?, image_path=?, is_video=?, video_path=?, sort_order=?, is_active=? WHERE id=?'
                )->execute([$title, $sub, $hl, $imgPath, $isVideo, $storeVideoPath, $sort, $active, $id]);
                admin_flash_set('success', 'Banner updated.');
            } else {
                db()->prepare(
                    'INSERT INTO banners (title, subtitle, highlight_html, image_path, is_video, video_path, sort_order, is_active) VALUES (?,?,?,?,?,?,?,?)'
                )->execute([$title, $sub, $hl, $imgPath, $isVideo, $storeVideoPath, $sort, $active]);
                admin_flash_set('success', 'Banner slide created.');
            }
            header('Location: banners.php');
            exit;
        }
    }
    }
}
if ($id > 0 && !$row) {
    admin_flash_set('danger', 'Banner not found.');
    header('Location: banners.php');
    exit;
}
$page = 'banners';
$pageTitle = $id ? 'Edit hero slide' : 'New hero slide';
$pageSubtitle = 'Content appears on the homepage hero; thumbnails sync with the carousel.';
$breadcrumbs = [['label' => 'Dashboard', 'href' => 'index.php'], ['label' => 'Hero banners', 'href' => 'banners.php'], ['label' => $id ? 'Edit' : 'New', 'href' => null]];
$headerActions = '<a href="banners.php" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left me-1"></i>All slides</a>';
require __DIR__ . '/includes/layout-header.php';
$r = $row ?: [
    'title' => '', 'subtitle' => '', 'highlight_html' => '', 'image_path' => '',
    'is_video' => 0, 'video_path' => '', 'sort_order' => 0, 'is_active' => 1,
];
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-7">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Slide copy</div>
      <div class="card-body">
        <div class="mb-3">
          <label class="form-label fw-semibold">Title line <span class="text-danger">*</span></label>
          <input type="text" name="title" class="form-control" required value="<?= h((string)($_POST['title'] ?? $r['title'])) ?>">
          <div class="form-text">First line of the headline (before the highlight).</div>
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Highlight HTML (optional)</label>
          <input type="text" name="highlight_html" class="form-control font-monospace small" value="<?= h((string)($_POST['highlight_html'] ?? $r['highlight_html'])) ?>">
          <div class="form-text">e.g. <code>&lt;span class="theme-text1"&gt;Bilaspur&lt;/span&gt;</code></div>
        </div>
        <div class="mb-0">
          <label class="form-label fw-semibold">Subtitle</label>
          <textarea name="subtitle" class="form-control" rows="4"><?= h((string)($_POST['subtitle'] ?? $r['subtitle'])) ?></textarea>
        </div>
      </div>
    </div>
  </div>
  <div class="col-lg-5">
    <div class="admin-card rounded mb-4">
      <div class="card-header">Background</div>
      <div class="card-body">
        <div class="form-check form-switch mb-3">
          <input class="form-check-input" type="checkbox" name="is_video" id="isv" value="1" <?= !empty($_POST['is_video'] ?? $r['is_video']) ? 'checked' : '' ?>>
          <label class="form-check-label" for="isv">Use video background</label>
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Upload video (MP4 or WebM)</label>
          <input type="file" name="video_file" id="bannerVideoFile" class="form-control" accept="video/mp4,video/webm,.mp4,.webm" data-max-bytes="<?= (int) $maxVideoBytes ?>">
          <p class="form-text mb-1">Saves to <code class="admin-code">uploads/banners/</code>. This host allows up to <strong><?= h($uploadIni) ?></strong> per file and <strong><?= h($postIni) ?></strong> per request.</p>
          <details class="admin-details-hint mt-2">
            <summary>File too large? Server / upload limits</summary>
            <p class="small text-muted mb-0 mt-2">Re-upload the project&rsquo;s <code class="admin-code">.user.ini</code> and <code class="admin-code">.htaccess</code> (64M) if this page still shows 8M, then wait a few minutes or restart PHP. On Nginx, set <code class="admin-code">client_max_body_size 64m;</code></p>
          </details>
        </div>
        <div class="mb-3">
          <label class="form-label fw-semibold">Or video path (optional)</label>
          <input type="text" name="video_path" class="form-control font-monospace small" placeholder="assets/img/slider/solar.mp4" value="<?= h((string)($_POST['video_path'] ?? $r['video_path'])) ?>">
          <?php if (!empty($r['video_path'])): ?>
            <div class="form-text">Current: <code class="small"><?= h((string)$r['video_path']) ?></code></div>
          <?php endif; ?>
        </div>
        <label class="form-label fw-semibold">Background image</label>
        <?php if (!empty($r['image_path'])): ?><div class="mb-2"><img src="../<?= h((string)$r['image_path']) ?>" class="img-fluid rounded border" style="max-height:120px;" alt=""></div><?php endif; ?>
        <input type="file" name="image" class="form-control" accept="image/*">
        <div class="form-text">Used when video is off.</div>
      </div>
    </div>
    <div class="admin-card rounded mb-4">
      <div class="card-header">Publishing</div>
      <div class="card-body">
        <div class="mb-3">
          <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 class="form-check form-switch">
          <input class="form-check-input" type="checkbox" name="is_active" id="act" value="1" <?= !empty($_POST['is_active'] ?? $r['is_active']) ? 'checked' : '' ?>>
          <label class="form-check-label" for="act">Active (visible on site)</label>
        </div>
      </div>
    </div>
    <button type="submit" class="btn btn-primary btn-lg w-100 mb-2" id="bannerSaveBtn"><i class="bi bi-check-lg me-1"></i>Save slide</button>
    <a href="banners.php" class="btn btn-outline-secondary w-100">Cancel</a>
  </div>
</form>
<script>
(function () {
  var inp = document.getElementById('bannerVideoFile');
  var btn = document.getElementById('bannerSaveBtn');
  if (!inp || !btn) return;
  var max = parseInt(inp.getAttribute('data-max-bytes') || '0', 10) || 0;
  inp.addEventListener('change', function () {
    var f = inp.files && inp.files[0];
    if (!f || !max) return;
    if (f.size > max) {
      alert('This file is about ' + (f.size / 1048576).toFixed(1) + ' MB. PHP on this server is limited to about ' + (max / 1048576).toFixed(1) + ' MB (see the note under the field). Compress the video or raise upload_max_filesize / post_max_size.');
      inp.value = '';
    }
  });
})();
</script>
<?php require __DIR__ . '/includes/layout-footer.php'; ?>
