<?php
require_once __DIR__ . '/../includes/auth.php';
require_owner_or_admin();
require_once __DIR__ . '/../includes/header_admin.php';
require_once __DIR__ . '/../includes/upload.php';
$pdo = require __DIR__ . '/../config/pdo.php';

$errors = [];
$editSlider = null;

// Handle Edit Mode
if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    $stmt = $pdo->prepare('SELECT * FROM sliders WHERE id = ? LIMIT 1');
    $stmt->execute([$editId]);
    $editSlider = $stmt->fetch();
}

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Toggle Active Status
    if ($action === 'toggle') {
        $id = (int) ($_POST['id'] ?? 0);
        $stmt = $pdo->prepare('UPDATE sliders SET is_active = IF(is_active = 1, 0, 1) WHERE id = ?');
        $stmt->execute([$id]);
        flash_message('success', 'Status slider diperbarui.');
        redirect(base_url('admin/sliders.php'));
    }

    // Delete Slider
    if ($action === 'delete') {
        $id = (int) ($_POST['id'] ?? 0);
        // Get image to delete file
        $stmt = $pdo->prepare('SELECT image FROM sliders WHERE id = ?');
        $stmt->execute([$id]);
        $slider = $stmt->fetch();
        
        if ($slider && $slider['image']) {
            $filePath = __DIR__ . '/../uploads/' . $slider['image'];
            if (file_exists($filePath)) {
                unlink($filePath);
            }
        }

        $stmt = $pdo->prepare('DELETE FROM sliders WHERE id = ?');
        $stmt->execute([$id]);
        flash_message('success', 'Slider berhasil dihapus.');
        redirect(base_url('admin/sliders.php'));
    }

    // Create or Update
    if ($action === 'save') {
        $id = (int) ($_POST['id'] ?? 0);
        $title = trim($_POST['title'] ?? '');
        $description = trim($_POST['description'] ?? '');
        $link_url = trim($_POST['link_url'] ?? '');
        $sort_order = (int) ($_POST['sort_order'] ?? 0);
        $is_active = isset($_POST['is_active']) ? 1 : 0;
        
        $photo = null;

        // Check file upload
        if (isset($_FILES['image']) && $_FILES['image']['error'] !== UPLOAD_ERR_NO_FILE) {
            $upload = handle_upload($_FILES['image'], ['image/jpeg', 'image/png', 'image/webp'], 5 * 1024 * 1024, __DIR__ . '/../uploads');
            if (!$upload['ok']) {
                $errors['image'] = $upload['error'];
            } else {
                $photo = $upload['filename'];
            }
        }

        // If creating new, image is required
        if ($id === 0 && !$photo) {
            $errors['image'] = 'Foto harus diupload untuk slider baru.';
        }

        if (!$errors) {
            if ($id === 0) {
                // Insert
                $stmt = $pdo->prepare('INSERT INTO sliders (image, title, description, link_url, sort_order, is_active) VALUES (?, ?, ?, ?, ?, ?)');
                $stmt->execute([$photo, $title, $description, $link_url, $sort_order, $is_active]);
                flash_message('success', 'Slider baru berhasil ditambahkan.');
            } else {
                // Update
                $query = 'UPDATE sliders SET title = ?, description = ?, link_url = ?, sort_order = ?, is_active = ?';
                $params = [$title, $description, $link_url, $sort_order, $is_active];
                
                if ($photo) {
                    $query .= ', image = ?';
                    $params[] = $photo;
                }
                
                $query .= ' WHERE id = ?';
                $params[] = $id;

                $stmt = $pdo->prepare($query);
                $stmt->execute($params);
                flash_message('success', 'Slider berhasil diperbarui.');
            }
            redirect(base_url('admin/sliders.php'));
        }
    }
}

$sliders = $pdo->query('SELECT * FROM sliders ORDER BY sort_order ASC, created_at DESC')->fetchAll();
?>

<h2 class="fw-bold mb-4">Manajemen Slider</h2>

<div class="row">
    <!-- Form Column -->
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm">
            <div class="card-body">
                <h5 class="fw-bold mb-3"><?= $editSlider ? 'Edit Slider' : 'Tambah Slider Baru'; ?></h5>
                <form method="post" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="id" value="<?= $editSlider ? (int)$editSlider['id'] : 0; ?>">
                    
                    <div class="mb-3">
                        <label class="form-label">Judul (Opsional)</label>
                        <input type="text" class="form-control" name="title" value="<?= $editSlider ? sanitize($editSlider['title']) : ''; ?>" placeholder="Contoh: Promo Ramadhan">
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Deskripsi (Opsional)</label>
                        <textarea class="form-control" name="description" rows="2" placeholder="Teks singkat di bawah judul"><?= $editSlider ? sanitize($editSlider['description']) : ''; ?></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Link URL (Opsional)</label>
                        <input type="text" class="form-control" name="link_url" value="<?= $editSlider ? sanitize($editSlider['link_url']) : ''; ?>" placeholder="index.php?page=products">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Urutan</label>
                        <input type="number" class="form-control" name="sort_order" value="<?= $editSlider ? (int)$editSlider['sort_order'] : 0; ?>">
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Upload Foto <?= $editSlider ? '(Kosongkan jika tidak ganti)' : '(Wajib)'; ?></label>
                        <input type="file" class="form-control" name="image" accept="image/*">
                        <?php if (isset($errors['image'])): ?>
                            <small class="text-danger"><?= $errors['image']; ?></small>
                        <?php endif; ?>
                        <small class="text-muted d-block mt-1">Disarankan ukuran landscape (cth: 1200x400px)</small>
                    </div>

                    <div class="form-check mb-3">
                        <input class="form-check-input" type="checkbox" name="is_active" id="activeCheck" <?= (!$editSlider || $editSlider['is_active']) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="activeCheck">Tampilkan Slider</label>
                    </div>

                    <button type="submit" class="btn btn-primary w-100"><?= $editSlider ? 'Simpan Perubahan' : 'Tambah Slider'; ?></button>
                    <?php if ($editSlider): ?>
                        <a href="<?= base_url('admin/sliders.php'); ?>" class="btn btn-outline-secondary w-100 mt-2">Batal Edit</a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
    </div>

    <!-- Table Column -->
    <div class="col-md-8">
        <div class="card shadow-sm">
            <div class="card-body table-responsive">
                <table class="table align-middle">
                    <thead>
                        <tr>
                            <th width="100">Gambar</th>
                            <th>Info Slider</th>
                            <th>Urutan</th>
                            <th>Status</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($sliders)): ?>
                            <tr><td colspan="5" class="text-center py-4 text-muted">Belum ada slider. Silakan tambah baru.</td></tr>
                        <?php else: ?>
                            <?php foreach ($sliders as $slider): ?>
                                <tr>
                                    <td>
                                        <img src="<?= base_url('uploads/' . sanitize($slider['image'])); ?>" class="rounded" style="width: 80px; height: 50px; object-fit: cover;">
                                    </td>
                                    <td>
                                        <strong><?= $slider['title'] ? sanitize($slider['title']) : '<i class="text-muted">Tanpa Judul</i>'; ?></strong><br>
                                        <small class="text-muted"><?= $slider['link_url'] ? sanitize($slider['link_url']) : '-'; ?></small>
                                    </td>
                                    <td><?= (int)$slider['sort_order']; ?></td>
                                    <td>
                                        <form method="post" class="d-inline">
                                            <input type="hidden" name="action" value="toggle">
                                            <input type="hidden" name="id" value="<?= (int)$slider['id']; ?>">
                                            <button class="btn btn-sm <?= $slider['is_active'] ? 'btn-success' : 'btn-secondary'; ?>" style="font-size: 0.7em;">
                                                <?= $slider['is_active'] ? 'Aktif' : 'Nonaktif'; ?>
                                            </button>
                                        </form>
                                    </td>
                                    <td>
                                        <a href="<?= base_url('admin/sliders.php?edit=' . (int)$slider['id']); ?>" class="btn btn-sm btn-outline-primary">
                                            <i class="bi bi-pencil me-1"></i> Edit
                                        </a>
                                        <button class="btn btn-sm btn-outline-danger" data-bs-toggle="modal" data-bs-target="#deleteSlider<?= (int)$slider['id']; ?>">
                                            <i class="bi bi-trash me-1"></i> Hapus
                                        </button>
                                    </td>
                                </tr>

                                <!-- Delete Modal -->
                                <div class="modal fade" id="deleteSlider<?= (int)$slider['id']; ?>" tabindex="-1" aria-hidden="true">
                                    <div class="modal-dialog">
                                        <div class="modal-content">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Hapus Slider</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">Yakin ingin menghapus slider ini?</div>
                                            <div class="modal-footer">
                                                <form method="post">
                                                    <input type="hidden" name="action" value="delete">
                                                    <input type="hidden" name="id" value="<?= (int)$slider['id']; ?>">
                                                    <button type="submit" class="btn btn-danger">Hapus</button>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php require_once __DIR__ . '/../includes/footer_admin.php'; ?>
