<?php
session_start();
require_once '../config/db.php';
require_once 'auth.php';

$pageTitle = 'Manajemen Slider';
$activePage = 'sliders';
$msg = '';

// Delete
if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("SELECT image FROM sliders WHERE id=?");
    $stmt->execute([$_GET['delete']]);
    $row = $stmt->fetch();
    if ($row && $row['image'] && file_exists(dirname(__DIR__).'/'.$row['image'])) {
        @unlink(dirname(__DIR__).'/'.$row['image']);
    }
    $pdo->prepare("DELETE FROM sliders WHERE id=?")->execute([$_GET['delete']]);
    $msg = adminAlert('Slider berhasil dihapus.');
}

// Toggle active
if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE sliders SET is_active = 1 - is_active WHERE id=?")->execute([$_GET['toggle']]);
    header('Location: sliders.php'); exit;
}

// Save (add/edit)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_POST['id'] ?? null;
    $title = trim($_POST['title']??'');
    $subtitle = trim($_POST['subtitle']??'');
    $btn_text = trim($_POST['button_text']??'');
    $btn_link = trim($_POST['button_link']??'');
    $sort = (int)($_POST['sort_order']??0);
    $active = isset($_POST['is_active']) ? 1 : 0;
    $existing_img = $_POST['existing_image'] ?? '';
    
    $image = $existing_img;
    if (!empty($_FILES['image']['name'])) {
        $uploaded = uploadFile($_FILES['image'], 'assets/images/slider');
        if ($uploaded) $image = $uploaded;
    }
    
    if ($id) {
        $pdo->prepare("UPDATE sliders SET title=?,subtitle=?,image=?,button_text=?,button_link=?,sort_order=?,is_active=? WHERE id=?")
            ->execute([$title,$subtitle,$image,$btn_text,$btn_link,$sort,$active,$id]);
        $msg = adminAlert('Slider berhasil diperbarui.');
    } else {
        $pdo->prepare("INSERT INTO sliders (title,subtitle,image,button_text,button_link,sort_order,is_active) VALUES (?,?,?,?,?,?,?)")
            ->execute([$title,$subtitle,$image,$btn_text,$btn_link,$sort,$active]);
        $msg = adminAlert('Slider berhasil ditambahkan.');
    }
}

$editItem = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM sliders WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $editItem = $stmt->fetch();
}

$items = $pdo->query("SELECT * FROM sliders ORDER BY sort_order ASC")->fetchAll();
include 'partials/header.php';
?>

<?= $msg ?>

<div class="row g-4">
    <div class="col-lg-5">
        <div class="card">
            <div class="card-header"><?= $editItem ? 'Edit Slider' : 'Tambah Slider Baru' ?></div>
            <div class="card-body">
                <form method="POST" enctype="multipart/form-data">
                    <?php if ($editItem): ?>
                        <input type="hidden" name="id" value="<?= $editItem['id'] ?>">
                        <input type="hidden" name="existing_image" value="<?= $editItem['image'] ?>">
                    <?php endif; ?>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Judul</label>
                        <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($editItem['title']??'') ?>">
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Subtitle / Deskripsi</label>
                        <textarea name="subtitle" class="form-control" rows="3"><?= htmlspecialchars($editItem['subtitle']??'') ?></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Gambar <?= $editItem ? '(biarkan kosong jika tidak ganti)' : '' ?></label>
                        <input type="file" name="image" class="form-control" <?= $editItem ? '' : 'required' ?> accept="image/*">
                        <?php if ($editItem && $editItem['image']): ?>
                            <img src="../<?= $editItem['image'] ?>" class="mt-2 rounded" style="height:80px;object-fit:cover;" onerror="this.style.display='none'">
                        <?php endif; ?>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col">
                            <label class="form-label fw-semibold">Teks Tombol</label>
                            <input type="text" name="button_text" class="form-control" value="<?= htmlspecialchars($editItem['button_text']??'') ?>">
                        </div>
                        <div class="col">
                            <label class="form-label fw-semibold">Link Tombol</label>
                            <input type="text" name="button_link" class="form-control" value="<?= htmlspecialchars($editItem['button_link']??'') ?>">
                        </div>
                    </div>
                    <div class="row g-2 mb-3">
                        <div class="col">
                            <label class="form-label fw-semibold">Urutan</label>
                            <input type="number" name="sort_order" class="form-control" value="<?= $editItem['sort_order']??0 ?>">
                        </div>
                        <div class="col d-flex align-items-end pb-1">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="is_active" id="is_active" <?= ($editItem['is_active']??1) ? 'checked' : '' ?>>
                                <label class="form-check-label fw-semibold" for="is_active">Aktif</label>
                            </div>
                        </div>
                    </div>
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-dark"><?= $editItem ? 'Update' : 'Tambah' ?></button>
                        <?php if ($editItem): ?>
                            <a href="sliders.php" class="btn btn-outline-secondary">Batal</a>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="col-lg-7">
        <div class="card">
            <div class="card-header">Daftar Slider (<?= count($items) ?>)</div>
            <div class="table-responsive">
                <table class="table mb-0 align-middle">
                    <thead class="table-light">
                        <tr><th>Gambar</th><th>Judul</th><th>Urutan</th><th>Status</th><th>Aksi</th></tr>
                    </thead>
                    <tbody>
                    <?php foreach ($items as $item): ?>
                        <tr>
                            <td><img src="../<?= $item['image'] ?>" style="width:80px;height:50px;object-fit:cover;border-radius:6px;" onerror="this.src='https://via.placeholder.com/80x50?text=No+Image'"></td>
                            <td><div class="fw-semibold"><?= htmlspecialchars($item['title']) ?></div><small class="text-muted"><?= htmlspecialchars(substr($item['subtitle']??'',0,50)) ?></small></td>
                            <td><?= $item['sort_order'] ?></td>
                            <td>
                                <a href="?toggle=<?= $item['id'] ?>" class="badge <?= $item['is_active'] ? 'badge-active' : 'badge-inactive' ?> text-decoration-none">
                                    <?= $item['is_active'] ? 'Aktif' : 'Nonaktif' ?>
                                </a>
                            </td>
                            <td>
                                <a href="?edit=<?= $item['id'] ?>" class="btn btn-sm btn-outline-primary"><i class="bi bi-pencil"></i></a>
                                <a href="?delete=<?= $item['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Hapus slider ini?')"><i class="bi bi-trash"></i></a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php include 'partials/footer.php'; ?>
