<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Gallery Controller
 *
 * CRUD operations for photo gallery items.
 */
class AdminGalleryController extends AdminController
{
    /**
     * List all gallery items.
     */
    public function index(array $params = []): void
    {
        requireAdmin();

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

        $this->adminView('gallery', [
            'title'        => 'Manage Gallery',
            'currentPage'  => 'gallery',
            'galleryItems' => $items,
            'editItem'     => null,
            'showForm'     => false,
        ]);
    }

    /**
     * Show the edit form for a gallery item.
     */
    public function edit(array $params = []): void
    {
        requireAdmin();

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

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

        if ($editItem === null) {
            flash('error', 'Gallery item not found.');
            redirect(BASE_PATH . '/admin/gallery');
        }

        // Also fetch all items for the list below the form
        $stmt2 = $this->db->query(
            'SELECT * FROM `gallery` ORDER BY `sort_order` ASC, `created_at` DESC'
        );
        $items = $stmt2->fetchAll() ?: [];

        $this->adminView('gallery', [
            'title'        => 'Edit Gallery Image',
            'currentPage'  => 'gallery',
            'galleryItems' => $items,
            'editItem'     => $editItem,
            'showForm'     => true,
        ]);
    }

    /**
     * Store a new gallery item.
     */
    public function store(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

        $title       = sanitize($_POST['title'] ?? '');
        $category    = sanitize($_POST['category'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $sortOrder   = (int) ($_POST['sort_order'] ?? 0);
        // Default active=1 so gallery items show on website immediately
        $active      = isset($_POST['active']) ? 1 : 1;

        if (empty($title)) {
            flash('error', 'Gallery item title is required.');
            redirect(BASE_PATH . '/admin/gallery');
        }

        $imagePath = $this->handleImageUpload('image', 'gallery');

        if ($imagePath === null) {
            flash('error', 'Gallery image is required. Please select an image file.');
            redirect(BASE_PATH . '/admin/gallery');
        }

        try {
            $stmt = $this->db->prepare(
                'INSERT INTO `gallery` (`title`, `category`, `description`, `image`, `sort_order`, `active`)
                 VALUES (:title, :category, :description, :image, :sort_order, :active)'
            );

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

            flash('success', 'Gallery item added successfully.');
        } catch (\Throwable $e) {
            error_log('Gallery create error: ' . $e->getMessage());
            $this->deleteImageFile($imagePath);
            flash('error', 'Failed to add gallery item: ' . $e->getMessage());
        }

        redirect(BASE_PATH . '/admin/gallery');
    }

    /**
     * Update an existing gallery item.
     */
    public function update(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

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

        if ($item === null) {
            flash('error', 'Gallery item not found.');
            redirect(BASE_PATH . '/admin/gallery');
        }

        $title       = sanitize($_POST['title'] ?? '');
        $category    = sanitize($_POST['category'] ?? '');
        $description = sanitize($_POST['description'] ?? '');
        $sortOrder   = (int) ($_POST['sort_order'] ?? 0);
        // Default active=1 so gallery items show on website immediately
        $active      = isset($_POST['active']) ? 1 : 1;

        if (empty($title)) {
            flash('error', 'Gallery item title is required.');
            redirect(BASE_PATH . '/admin/gallery');
        }

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

        $stmt = $this->db->prepare(
            'UPDATE `gallery` SET `title` = :title, `category` = :category, `description` = :description,
             `image` = :image, `sort_order` = :sort_order, `active` = :active WHERE `id` = :id'
        );

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

        flash('success', 'Gallery item updated successfully.');
        redirect(BASE_PATH . '/admin/gallery');
    }

    /**
     * Toggle the active status of a gallery item.
     */
    public function toggle(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

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

        if ($item === null) {
            flash('error', 'Gallery item not found.');
            redirect(BASE_PATH . '/admin/gallery');
        }

        $newStatus = ($item['active'] ?? 0) == 1 ? 0 : 1;

        $stmt = $this->db->prepare('UPDATE `gallery` SET `active` = :active WHERE `id` = :id');
        $stmt->execute([':active' => $newStatus, ':id' => $id]);

        flash('success', $newStatus ? 'Gallery item activated.' : 'Gallery item deactivated.');
        redirect(BASE_PATH . '/admin/gallery');
    }

    /**
     * Delete a gallery item.
     */
    public function delete(array $params = []): void
    {
        requireAdmin();
        $this->validateCsrf();

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

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

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

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

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