<?php

namespace App\Entities;

use CodeIgniter\Entity\Entity;

class Pelicula extends Entity
{
    protected $casts = [
        'id_pelicula'  => 'integer',
        'id_genero'    => 'integer',
        'duracion_min' => 'integer',
        'estado'       => 'integer',
    ];

    public function getPosterUrl(): string
    {
        $url = $this->attributes['poster_url'] ?? '';
        if (empty($url)) {
            return base_url('img/placeholder-poster.jpg');
        }

        if (preg_match('#^https?://#i', $url)) {
            return $url;
        }

        return base_url('uploads/posters/' . $url);
    }

    public function getTrailerEmbedUrl(): string
    {
        $url = $this->attributes['trailer_url'] ?? '';
        if (empty($url)) {
            return '';
        }

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

        return $url;
    }

    public function estaActiva(): bool
    {
        return isset($this->attributes['estado']) && (int)$this->attributes['estado'] === 1;
    }
}
