<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class VideoTutorial extends Model
{
    protected $fillable = [
        'title',
        'description',
        'video_url',
        'thumbnail_url',
        'category',
        'duration',
        'sort_order',
        'is_published',
    ];

    protected function casts(): array
    {
        return [
            'is_published' => 'boolean',
            'sort_order'   => 'integer',
        ];
    }

    protected $appends = ['embed_url', 'auto_thumbnail'];

    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    /**
     * Convert a YouTube or Vimeo watch URL into an embeddable URL.
     */
    public function getEmbedUrlAttribute(): string
    {
        $url = $this->video_url ?? '';

        // YouTube
        if (preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/', $url, $m)) {
            return "https://www.youtube.com/embed/{$m[1]}?rel=0&modestbranding=1";
        }

        // Vimeo
        if (preg_match('/vimeo\.com\/(?:video\/)?(\d+)/', $url, $m)) {
            return "https://player.vimeo.com/video/{$m[1]}";
        }

        return $url;
    }

    /**
     * Return a usable thumbnail URL — custom if set, else auto-derived from YouTube.
     */
    public function getAutoThumbnailAttribute(): ?string
    {
        if ($this->thumbnail_url) {
            return $this->thumbnail_url;
        }

        if (preg_match('/(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/)([a-zA-Z0-9_-]{11})/', $this->video_url ?? '', $m)) {
            return "https://img.youtube.com/vi/{$m[1]}/mqdefault.jpg";
        }

        return null;
    }
}
