<?php
namespace App\Repositories\Website;

use App\Models\Ads;
use App\Models\Movie;
use App\Repositories\Interfaces\Website\PlayerRepositoryInterface;
use Carbon\Carbon;
use Illuminate\Http\Request;

class PlayerRepository implements PlayerRepositoryInterface
{
    public function loadPlayerData(Request $request): array
    {
        $videoUrl = $request->video_url;
        $poster = $request->poster;
        $source_type = $request->type ?? null;
        $video = null;

        if ($request->video_type === 'movie') {
            $video = Movie::findOrFail($request->video_id);
        }

        // Handle source types
        $videoUrl = $this->processVideoUrl($videoUrl, $source_type);

        // Get Ads
        $now = Carbon::now();
        $pre_roll = $this->getAdByType('pre_roll', $now);
        $mid_roll = $this->getAdByType('mid_roll', $now);
        $post_roll = $this->getAdByType('post_roll', $now);

        return [
            'videoUrl' => $videoUrl,
            'poster' => $poster,
            'label' => $video->quality->quality ?? 'HD',
            'video' => $video,
            'pre_roll_ad' => $pre_roll,
            'mid_roll_ad' => $mid_roll,
            'post_roll_ad' => $post_roll,
        ];
    }

    protected function processVideoUrl(string $url, ?string $type): string
    {
        if ($type === 'youtube') {
            if (preg_match('/(?:youtube\.com\/.*v=|youtu\.be\/)([^&\n?#]+)/', $url, $matches)) {
                return 'https://www.youtube.com/watch?v=' . $matches[1];
            }
        }

        if ($type === 'gdrive') {
            $apiKey = get_config('google_api_key'); // or hardcode
            $fileId = null;

            if (preg_match('/\/file\/d\/([a-zA-Z0-9_-]+)/', $url, $matches)) {
                $fileId = $matches[1];
            } elseif (preg_match('/open\?id=([a-zA-Z0-9_-]+)/', $url, $matches)) {
                $fileId = $matches[1];
            }

            if ($fileId) {
                return "https://www.googleapis.com/drive/v3/files/{$fileId}?alt=media&key={$apiKey}";
            }
        }

        return $url;
    }

    public function getAdByType(string $type, $now) {
        return Ads::where('type', $type)
            ->where('status', 1)
            ->where('start_date', '<=', $now)
            ->where('end_date', '>=', $now)
            ->inRandomOrder()
            ->first();
    }
}
