<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Video extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'url',
        'video_type',
        'video_path',
        'sort_order',
    ];

    public function getEmbedUrlAttribute()
    {
        // If it's an uploaded video, return the storage path
        if ($this->video_type === 'upload' && $this->video_path) {
            return asset('storage/' . $this->video_path);
        }

        // Otherwise, process the URL for embedded links
        $url = $this->url;

        // YouTube
        if (strpos($url, 'youtube.com') !== false || strpos($url, 'youtu.be') !== false) {
            $videoId = '';
            if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i', $url, $match)) {
                $videoId = $match[1];
            }
            if ($videoId) {
                return "https://www.youtube.com/embed/" . $videoId;
            }
        }

        // Vimeo
        if (strpos($url, 'vimeo.com') !== false) {
            if (preg_match('/vimeo\.com\/(?:channels\/(?:\w+\/)?|groups\/(?:[^\/]*)\/videos\/|album\/(?:\d+)\/video\/|video\/|)(\d+)(?:$|\/|\?)/', $url, $match)) {
                return "https://player.vimeo.com/video/" . $match[1];
            }
        }

        return $url;
    }
}
