<?php

declare(strict_types=1);

namespace Admin\Controllers;

/**
 * Admin Course Controller
 *
 * CRUD operations for courses with category filtering
 * and image upload support.
 */
class AdminCourseController extends AdminController
{
    /**
     * List all courses with optional category filter.
     *
     * @param array<string, string> $params Route parameters
     * @return void
     */
    public function index(array $params = []): void
    {
        requireAdmin();

        $category = $_GET['category'] ?? '';

        if ($category !== '' && in_array($category, ['computer', 'accounting', 'programming', 'design', 'other'], true)) {
            $stmt = $this->db->prepare(
                'SELECT * FROM `courses` WHERE `category` = :category ORDER BY `created_at` DESC'
            );
            $stmt->execute([':category' => $category]);
        } else {
            $stmt = $this->db->query('SELECT * FROM `courses` ORDER BY `created_at` DESC');
        }

        $courses = $stmt->fetchAll() ?: [];

        // Get distinct categories for filter
        $stmt = $this->db->query('SELECT DISTINCT `category` FROM `courses` ORDER BY `category` ASC');
        $categories = $stmt->fetchAll() ?: [];

        $this->adminView('courses', [
            'title'       => 'Manage Courses',
            'currentPage' => 'courses',
            'courses'     => $courses,
            'categories'  => $categories,
            'editCourse'  => null,
        ]);
    }

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

        $stmt = $this->db->query('SELECT DISTINCT `category` FROM `courses` ORDER BY `category` ASC');
        $categories = $stmt->fetchAll() ?: [];

        $this->adminView('courses', [
            'title'       => 'Add New Course',
            'currentPage' => 'courses',
            'courses'     => [],
            'categories'  => $categories,
            'editCourse'  => null,
            'showForm'    => true,
        ]);
    }

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

        $name       = sanitize($_POST['name'] ?? '');
        $category   = sanitize($_POST['category'] ?? 'computer');
        $duration   = sanitize($_POST['duration'] ?? '');
        $fee        = (float) ($_POST['fee'] ?? 0);
        $description = $_POST['description'] ?? '';
        $syllabus   = $_POST['syllabus'] ?? '';
        $content    = $_POST['content'] ?? $description; // content defaults to description
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
        $active     = isset($_POST['active']) ? 1 : 0;

        if (empty($name)) {
            flash('error', 'Course name is required.');
            redirect(BASE_PATH . '/admin/courses/create');
        }

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

        // Check if 'content' column exists in courses table
        $hasContentColumn = $this->columnExists('courses', 'content');

        if ($hasContentColumn) {
            $stmt = $this->db->prepare(
                'INSERT INTO `courses` (`name`, `category`, `duration`, `fee`, `description`, `syllabus`, `content`, `image`, `is_featured`, `active`)
                 VALUES (:name, :category, :duration, :fee, :description, :syllabus, :content, :image, :is_featured, :active)'
            );
            $stmt->execute([
                ':name'        => $name,
                ':category'    => $category,
                ':duration'    => $duration,
                ':fee'         => $fee,
                ':description' => $description,
                ':syllabus'    => $syllabus,
                ':content'     => $content,
                ':image'       => $imagePath,
                ':is_featured' => $isFeatured,
                ':active'      => $active,
            ]);
        } else {
            $stmt = $this->db->prepare(
                'INSERT INTO `courses` (`name`, `category`, `duration`, `fee`, `description`, `syllabus`, `image`, `is_featured`, `active`)
                 VALUES (:name, :category, :duration, :fee, :description, :syllabus, :image, :is_featured, :active)'
            );
            $stmt->execute([
                ':name'        => $name,
                ':category'    => $category,
                ':duration'    => $duration,
                ':fee'         => $fee,
                ':description' => $description,
                ':syllabus'    => $syllabus,
                ':image'       => $imagePath,
                ':is_featured' => $isFeatured,
                ':active'      => $active,
            ]);
        }

        flash('success', 'Course created successfully.');
        redirect(BASE_PATH . '/admin/courses');
    }

    /**
     * Show the edit course 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 `courses` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $editCourse = $stmt->fetch() ?: null;

        if ($editCourse === null) {
            flash('error', 'Course not found.');
            redirect(BASE_PATH . '/admin/courses');
        }

        $stmt = $this->db->query('SELECT DISTINCT `category` FROM `courses` ORDER BY `category` ASC');
        $categories = $stmt->fetchAll() ?: [];

        $this->adminView('courses', [
            'title'       => 'Edit Course',
            'currentPage' => 'courses',
            'courses'     => [],
            'categories'  => $categories,
            'editCourse'  => $editCourse,
            'showForm'    => true,
        ]);
    }

    /**
     * Update an existing course.
     *
     * @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 `courses` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $course = $stmt->fetch() ?: null;

        if ($course === null) {
            flash('error', 'Course not found.');
            redirect(BASE_PATH . '/admin/courses');
        }

        $name       = sanitize($_POST['name'] ?? '');
        $category   = sanitize($_POST['category'] ?? 'computer');
        $duration   = sanitize($_POST['duration'] ?? '');
        $fee        = (float) ($_POST['fee'] ?? 0);
        $description = $_POST['description'] ?? '';
        $syllabus   = $_POST['syllabus'] ?? '';
        $content    = $_POST['content'] ?? $description; // content defaults to description
        $isFeatured = isset($_POST['is_featured']) ? 1 : 0;
        $active     = isset($_POST['active']) ? 1 : 0;

        if (empty($name)) {
            flash('error', 'Course name is required.');
            redirect(BASE_PATH . '/admin/courses/' . $id . '/edit');
        }

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

        // Check if 'content' column exists
        $hasContentColumn = $this->columnExists('courses', 'content');

        if ($hasContentColumn) {
            $stmt = $this->db->prepare(
                'UPDATE `courses` SET `name` = :name, `category` = :category, `duration` = :duration,
                 `fee` = :fee, `description` = :description, `syllabus` = :syllabus, `content` = :content,
                 `image` = :image, `is_featured` = :is_featured, `active` = :active WHERE `id` = :id'
            );
            $stmt->execute([
                ':name'        => $name,
                ':category'    => $category,
                ':duration'    => $duration,
                ':fee'         => $fee,
                ':description' => $description,
                ':syllabus'    => $syllabus,
                ':content'     => $content,
                ':image'       => $imagePath,
                ':is_featured' => $isFeatured,
                ':active'      => $active,
                ':id'          => $id,
            ]);
        } else {
            $stmt = $this->db->prepare(
                'UPDATE `courses` SET `name` = :name, `category` = :category, `duration` = :duration,
                 `fee` = :fee, `description` = :description, `syllabus` = :syllabus,
                 `image` = :image, `is_featured` = :is_featured, `active` = :active WHERE `id` = :id'
            );
            $stmt->execute([
                ':name'        => $name,
                ':category'    => $category,
                ':duration'    => $duration,
                ':fee'         => $fee,
                ':description' => $description,
                ':syllabus'    => $syllabus,
                ':image'       => $imagePath,
                ':is_featured' => $isFeatured,
                ':active'      => $active,
                ':id'          => $id,
            ]);
        }

        flash('success', 'Course updated successfully.');
        redirect(BASE_PATH . '/admin/courses');
    }

    /**
     * Delete a course.
     *
     * @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 course first to delete its image file
        $stmt = $this->db->prepare('SELECT * FROM `courses` WHERE `id` = :id LIMIT 1');
        $stmt->execute([':id' => $id]);
        $course = $stmt->fetch() ?: null;

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

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

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