<?php
require_once '../config.php';
require_once '../../includes/Auth.php';
require_once '../../includes/Database.php';

$auth = new Auth();
$auth->requireRole('admin');
$db = new Database();

$method = $_SERVER['REQUEST_METHOD'];

try {
    if ($method === 'GET') {
        // List all slides
        $stmt = $db->query("SELECT * FROM slides ORDER BY id DESC");
        $slides = $stmt->fetchAll(PDO::FETCH_ASSOC);
        jsonResponse(['success' => true, 'slides' => $slides]);

    } elseif ($method === 'POST') {
        $input = json_decode(file_get_contents('php://input'), true);

        $id = $input['id'] ?? null;
        $title = trim($input['title']);
        $description = trim($input['description'] ?? '');
        $image_path = trim($input['image_path']);
        $is_active = isset($input['is_active']) ? (bool)$input['is_active'] : true;

        if ($id) {
            if (empty($title)) {
                throw new Exception("Title is required.");
            }
            // Update existing slide
            $sql = "UPDATE slides SET title = ?, description = ?, is_active = ?";
            $params = [$title, $description, $is_active];
            if (!empty($image_path)) {
                $sql .= ", image_path = ?";
                $params[] = $image_path;
            }
            $sql .= " WHERE id = ?";
            $params[] = $id;

            $db->query($sql, $params);
            $message = 'Slide updated successfully';
        } else {
            // Create new slide
            $db->query(
                "INSERT INTO slides (title, description, image_path, is_active) VALUES (?, ?, ?, ?)",
                [$title, $description, $image_path, $is_active]
            );
            $id = $db->lastInsertId();
            $message = 'Slide created successfully';
        }

        jsonResponse(['success' => true, 'message' => $message, 'slide_id' => $id]);

    } elseif ($method === 'DELETE') {
        $input = json_decode(file_get_contents('php://input'), true);
        $id = $input['id'] ?? null;

        if (!$id) {
            throw new Exception("Slide ID is required for deletion.");
        }

        $stmt = $db->query("DELETE FROM slides WHERE id = ?", [$id]);

        if ($stmt->rowCount() > 0) {
            jsonResponse(['success' => true, 'message' => 'Slide deleted successfully']);
        } else {
            throw new Exception("Slide not found or could not be deleted.");
        }

    } else {
        jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
    }
} catch (Exception $e) {
    jsonResponse(['success' => false, 'message' => $e->getMessage()], 500);
}
?>