<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Slider Controller
 *
 * CRUD operations for homepage carousel sliders
 * with image upload handling.
 */
class AdminSliderController extends AdminController
{
    /**
     * List all sliders.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query(
            'SELECT * FROM `sliders` ORDER BY `sort_order` ASC, `created_at` DESC'
        );
        $sliders = $stmt->fetchAll() ?: [];

        $this->adminView('sliders', [
            'title'       => 'Manage Sliders',
            'currentPage' => 'sliders',
            'sliders'     => $sliders,
            'editSlider'  => null,
        ]);
    }

    /**
     * Show the create slider form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function create(array $params = []): void
    {
        requireAdmin();

        $stmt = $this->db->query(
            'SELECT * FROM `sliders` ORDER BY `sort_order` ASC, `created_at` DESC'
        );
        $sliders = $stmt->fetchAll() ?: [];

        $this->adminView('sliders', [
            'title'      => 'Add New Slider',
            'currentPage' => 'sliders',
            'sliders'    => $sliders,
            'editSlider' => null,
            'showForm'   => true,
        ]);
    }

    /**
     * Store a new slider.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function store(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $title      = sanitize($_POST['title'] ?? '');
        $subtitle   = sanitize($_POST['subtitle'] ?? '');
        $link       = sanitize($_POST['link'] ?? '');
        $sortOrder  = (int) ($_POST['sort_order'] ?? 0);
        $active     = isset($_POST['active']) ? 1 : 0;

        if (empty($title)) {
            flash('error', 'Slider title is required.');
            redirect(BASE_PATH . '/admin/sliders/create');
        }

        // Handle image upload
        $imagePath = $this->handleImageUpload('image', 'sliders');

        if ($imagePath === null) {
            flash('error', 'Slider image is required.');
            redirect(BASE_PATH . '/admin/sliders/create');
        }

        $stmt = $this->db->prepare(
            'INSERT INTO `sliders` (`title`, `subtitle`, `image`, `link`, `sort_order`, `active`)
             VALUES (:title, :subtitle, :image, :link, :sort_order, :active)'
        );

        $stmt->execute([
            ':title'      => $title,
            ':subtitle'   => $subtitle,
            ':image'      => $imagePath,
            ':link'       => $link,
            ':sort_order' => $sortOrder,
            ':active'     => $active,
        ]);

        flash('success', 'Slider created successfully.');
        redirect(BASE_PATH . '/admin/sliders');
    }

    /**
     * Show the edit slider form.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function edit(array $params = []): void
    {
        requireAdmin();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('SELECT * FROM `sliders` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $editSlider = $stmt->fetch() ?: null;

        if ($editSlider === null) {
            flash('error', 'Slider not found.');
            redirect(BASE_PATH . '/admin/sliders');
        }

        $stmt = $this->db->query(
            'SELECT * FROM `sliders` ORDER BY `sort_order` ASC, `created_at` DESC'
        );
        $sliders = $stmt->fetchAll() ?: [];

        $this->adminView('sliders', [
            'title'       => 'Edit Slider',
            'currentPage' => 'sliders',
            'sliders'     => $sliders,
            'editSlider'  => $editSlider,
            'showForm'    => true,
        ]);
    }

    /**
     * Update an existing slider.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        $stmt = $this->db->prepare('SELECT * FROM `sliders` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $slider = $stmt->fetch() ?: null;

        if ($slider === null) {
            flash('error', 'Slider not found.');
            redirect(BASE_PATH . '/admin/sliders');
        }

        $title      = sanitize($_POST['title'] ?? '');
        $subtitle   = sanitize($_POST['subtitle'] ?? '');
        $link       = sanitize($_POST['link'] ?? '');
        $sortOrder  = (int) ($_POST['sort_order'] ?? 0);
        $active     = isset($_POST['active']) ? 1 : 0;

        if (empty($title)) {
            flash('error', 'Slider title is required.');
            redirect(BASE_PATH . '/admin/sliders/' . $id . '/edit');
        }

        // Handle optional image replacement
        $imagePath = $this->handleImageUpload('image', 'sliders');
        if ($imagePath !== null) {
            // New image uploaded — delete the old one
            $this->deleteImageFile($slider['image'] ?? null);
        } else {
            $imagePath = $slider['image'];
        }

        $stmt = $this->db->prepare(
            'UPDATE `sliders` SET `title` = :title, `subtitle` = :subtitle, `image` = :image,
             `link` = :link, `sort_order` = :sort_order, `active` = :active WHERE `id` = :id'
        );

        $stmt->execute([
            ':title'      => $title,
            ':subtitle'   => $subtitle,
            ':image'      => $imagePath,
            ':link'       => $link,
            ':sort_order' => $sortOrder,
            ':active'     => $active,
            ':id'         => $id,
        ]);

        flash('success', 'Slider updated successfully.');
        redirect(BASE_PATH . '/admin/sliders');
    }

    /**
     * Delete a slider.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $id = (int) ($params['id'] ?? 0);

        // Fetch the slider first to delete its image file
        $stmt = $this->db->prepare('SELECT * FROM `sliders` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $slider = $stmt->fetch() ?: null;

        if ($slider !== null) {
            $this->deleteImageFile($slider['image'] ?? null);
        }

        $stmt = $this->db->prepare('DELETE FROM `sliders` WHERE `id` = :id');
        $stmt->execute([':id' => $id]);

        if ($stmt->rowCount() > 0) {
            flash('success', 'Slider deleted successfully.');
        } else {
            flash('warning', 'Slider not found or already deleted.');
        }
        redirect(BASE_PATH . '/admin/sliders');
    }
}
