<?php

declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use PDO;

/**
 * VideoTestimonial Model
 *
 * Manages student video testimonials displayed on the homepage.
 */
class VideoTestimonial extends Model
{
    protected string $table = 'video_testimonials';

    /**
     * Get active video testimonials ordered by sort_order.
     */
    public function getActive(int $limit = 10): array
    {
        $sql = "SELECT * FROM `{$this->table}`
                WHERE `status` = 1
                ORDER BY `sort_order` ASC, `created_at` DESC
                LIMIT :limit";

        $stmt = $this->db->prepare($sql);
        $stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
        $stmt->execute();

        return $stmt->fetchAll();
    }

    /**
     * Get all video testimonials (for admin).
     */
    public function getAllOrdered(): array
    {
        $sql = "SELECT * FROM `{$this->table}`
                ORDER BY `sort_order` ASC, `created_at` DESC";

        $stmt = $this->db->prepare($sql);
        $stmt->execute();

        return $stmt->fetchAll();
    }

    /**
     * Toggle status (enable/disable).
     */
    public function toggleStatus(int $id): bool
    {
        $sql = "UPDATE `{$this->table}` SET `status` = NOT `status` WHERE `id` = :id";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([':id' => $id]);
        return $stmt->rowCount() > 0;
    }

    /**
     * Extract YouTube video ID from various URL formats.
     */
    public static function extractYoutubeId(string $url): ?string
    {
        // Standard youtube.com/watch?v=VIDEO_ID
        if (preg_match('/youtube\.com\/watch\?v=([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return $m[1];
        }
        // Short youtu.be/VIDEO_ID
        if (preg_match('/youtu\.be\/([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return $m[1];
        }
        // Embed youtube.com/embed/VIDEO_ID
        if (preg_match('/youtube\.com\/embed\/([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return $m[1];
        }
        // Already just the ID (11 chars)
        if (preg_match('/^[a-zA-Z0-9_-]{11}$/', $url)) {
            return $url;
        }
        return null;
    }

    /**
     * Generate YouTube embed URL from any YouTube URL.
     */
    public static function getEmbedUrl(string $url): string
    {
        $id = self::extractYoutubeId($url);
        if ($id) {
            return "https://www.youtube.com/embed/{$id}";
        }
        return $url; // Return as-is if not YouTube
    }

    /**
     * Generate thumbnail URL from YouTube video ID.
     */
    public static function getThumbnailUrl(string $url): string
    {
        $id = self::extractYoutubeId($url);
        if ($id) {
            return "https://img.youtube.com/vi/{$id}/hqdefault.jpg";
        }
        return '';
    }
}
