<?php

declare(strict_types=1);

namespace Admin\Controllers;

use App\Core\Controller;

/**
 * AdminVideoTestimonialController — Admin management of video testimonials
 */
class AdminVideoTestimonialController extends AdminController
{
    /**
     * List all video testimonials.
     */
    public function index(): never
    {
        $model = $this->model('VideoTestimonial');
        $videos = $model->getAllOrdered();

        $this->adminView('video_testimonials', [
            'title'       => 'Video Testimonials',
            'currentPage' => 'video-testimonials',
            'videos'      => $videos,
        ]);
    }

    /**
     * Show create form.
     */
    public function create(): never
    {
        $courses = [];
        try {
            $courseModel = $this->model('Course');
            $courses = $courseModel->where('active', 1);
        } catch (\Throwable $e) { }

        $this->adminView('video_testimonial_form', [
            'title'       => 'Add Video Testimonial',
            'currentPage' => 'video-testimonials',
            'video'       => null,
            'courses'     => $courses,
        ]);
    }

    /**
     * Store a new video testimonial.
     */
    public function store(): never
    {
        $this->validateCsrf();

        $name       = trim($_POST['student_name'] ?? '');
        $courseName = trim($_POST['course_name'] ?? '');
        $videoUrl   = trim($_POST['video_url'] ?? '');
        $shortText  = trim($_POST['short_text'] ?? '');
        $sortOrder  = (int) ($_POST['sort_order'] ?? 0);
        $status     = (int) ($_POST['status'] ?? 1);

        if (empty($name) || empty($videoUrl)) {
            flash('error', 'Student name and video URL are required.');
            redirect(BASE_PATH . '/admin/video-testimonials/create');
        }

        // Handle thumbnail upload
        $thumbnail = $this->handleImageUpload('thumbnail', 'video_testimonials');

        // Auto-generate thumbnail from YouTube if not uploaded
        if (empty($thumbnail)) {
            $autoThumb = \App\Models\VideoTestimonial::getThumbnailUrl($videoUrl);
            if (!empty($autoThumb)) {
                $thumbnail = $autoThumb;
            }
        }

        $model = $this->model('VideoTestimonial');
        $model->create([
            'student_name' => $name,
            'course_name'  => $courseName ?: null,
            'video_url'    => $videoUrl,
            'thumbnail'    => $thumbnail,
            'short_text'   => $shortText ?: null,
            'sort_order'   => $sortOrder,
            'status'       => $status,
        ]);

        flash('success', 'Video testimonial added successfully.');
        redirect(BASE_PATH . '/admin/video-testimonials');
    }

    /**
     * Show edit form.
     */
    public function edit(int $id): never
    {
        $model = $this->model('VideoTestimonial');
        $video = $model->find($id);

        if (!$video) {
            flash('error', 'Video testimonial not found.');
            redirect(BASE_PATH . '/admin/video-testimonials');
        }

        $courses = [];
        try {
            $courseModel = $this->model('Course');
            $courses = $courseModel->where('active', 1);
        } catch (\Throwable $e) { }

        $this->adminView('video_testimonial_form', [
            'title'       => 'Edit Video Testimonial',
            'currentPage' => 'video-testimonials',
            'video'       => $video,
            'courses'     => $courses,
        ]);
    }

    /**
     * Update a video testimonial.
     */
    public function update(int $id): never
    {
        $this->validateCsrf();

        $model = $this->model('VideoTestimonial');
        $video = $model->find($id);

        if (!$video) {
            flash('error', 'Video testimonial not found.');
            redirect(BASE_PATH . '/admin/video-testimonials');
        }

        $name       = trim($_POST['student_name'] ?? '');
        $courseName = trim($_POST['course_name'] ?? '');
        $videoUrl   = trim($_POST['video_url'] ?? '');
        $shortText  = trim($_POST['short_text'] ?? '');
        $sortOrder  = (int) ($_POST['sort_order'] ?? 0);
        $status     = (int) ($_POST['status'] ?? 1);

        if (empty($name) || empty($videoUrl)) {
            flash('error', 'Student name and video URL are required.');
            redirect(BASE_PATH . "/admin/video-testimonials/{$id}/edit");
        }

        $data = [
            'student_name' => $name,
            'course_name'  => $courseName ?: null,
            'video_url'    => $videoUrl,
            'short_text'   => $shortText ?: null,
            'sort_order'   => $sortOrder,
            'status'       => $status,
        ];

        // Handle new thumbnail upload
        $thumbnail = $this->handleImageUpload('thumbnail', 'video_testimonials');
        if ($thumbnail) {
            // Delete old thumbnail (only if it's a local file, not YouTube URL)
            if (!empty($video['thumbnail']) && !str_contains($video['thumbnail'], 'youtube.com')) {
                $this->deleteImageFile($video['thumbnail']);
            }
            $data['thumbnail'] = $thumbnail;
        } elseif (empty($video['thumbnail']) || str_contains($video['thumbnail'], 'youtube.com')) {
            // Auto-generate from YouTube
            $autoThumb = \App\Models\VideoTestimonial::getThumbnailUrl($videoUrl);
            if (!empty($autoThumb)) {
                $data['thumbnail'] = $autoThumb;
            }
        }

        $model->update($id, $data);

        flash('success', 'Video testimonial updated successfully.');
        redirect(BASE_PATH . '/admin/video-testimonials');
    }

    /**
     * Toggle status (enable/disable).
     */
    public function toggleStatus(int $id): never
    {
        $this->validateCsrf();

        $model = $this->model('VideoTestimonial');
        $model->toggleStatus($id);

        flash('success', 'Status updated.');
        redirect(BASE_PATH . '/admin/video-testimonials');
    }

    /**
     * Delete a video testimonial.
     */
    public function delete(int $id): never
    {
        $this->validateCsrf();

        $model = $this->model('VideoTestimonial');
        $video = $model->find($id);

        if ($video && !empty($video['thumbnail']) && !str_contains($video['thumbnail'], 'youtube.com')) {
            $this->deleteImageFile($video['thumbnail']);
        }

        $model->delete($id);

        flash('success', 'Video testimonial deleted.');
        redirect(BASE_PATH . '/admin/video-testimonials');
    }
}
