<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use App\Models\Category;
use App\Models\Country;
use App\Models\Genre;
use App\Models\MovieLanguage;
use App\Models\VideoQuality;
use App\Models\Season;
use App\Models\Star;
use App\Models\TvShow;
use App\Models\User;
use App\Traits\Mobile\ApiResponseTrait;
use Carbon\Carbon;
use Illuminate\Http\Request;

class TvShowController extends Controller
{
    use ApiResponseTrait;
    public function tv_shows()
    {
        $withMedia = function ($item) {
            $item->thumbnail = apiImageFromJson($item->thumbnail, 'original_image', 'tv_shows');
            $item->poster = apiImageFromJson($item->poster, 'original_image', 'tv_shows');
            $item->is_rental = $item->price ? true : false;
            $item->rental_price = $item->price;
            $item->rental_hours = $item->hours;
            return $item;
        };
        $shows = TvShow::where('status', 1)->paginate(20)->through($withMedia);
        $data = [
            'shows' => $shows,
            'filter' => [
                'categories' => Category::get(),
                'country' => Country::get(),
                'languages' => MovieLanguage::get(),
                'genre' => Genre::get(),
                'year' => range(1975, date('Y')),
                'sort' => [
                    1 => 'paid',
                    2 => 'original'
                ]
            ]
        ];
        return $this->responseWithSuccess($data, __('tv_shows_retrieved_successfully'));
    }
    public function getActor($value)
    {
        $withMedia = function ($item) {
            $item->star_image = apiImageFromJson($item->star_image, 'original_image', 'stars');
            return $item;
        };

        $stars = [];
        foreach (json_decode($value) as $star) {
            $stars[] = $withMedia(Star::where('id', $star)->first());
        }
        return $stars;
    }
    public function tv_show_details(Request $request)
    {


        $user = User::with('favoriteTvShows')->find($request->user_id);
        $withMedia = function ($item) {
            $item->thumbnail = apiImageFromJson($item->thumbnail, 'original_image', 'movies');
            $item->poster = apiImageFromJson($item->poster, 'original_image', 'movies');
            $item->runtime = runtime($item->runtime);
            return $item;
        };
        $tvShow = TvShow::where('id', $request->id)->first();
       
        $tvShow->seasons = Season::whereJsonContains('tv_show_id', (string)$tvShow->id)
                         ->with('episodes')
                         ->orderBy('order')
                         ->get();
        $tvShow->is_favorite = $user ? $user->favoriteTvShows()->where('tv_show_id', $tvShow->id)->exists() : false;
        if (!$tvShow) {
            return $this->responseWithError(__('tv_show_not_found'), 400);
        }

        $hours = (int) $tvShow->rental_duration;
        $days = intdiv($hours, 24);
        $remainingHours = $hours % 24;

        $validity = '';

        // If exactly 1 day (24 hours)
        if ($hours === 24) {
            $validity = '1 day';
        }
        // More than 1 day
        elseif ($hours > 24) {
            $validity .= $days . ' ' . ($days === 1 ? 'day' : 'days');

            if ($remainingHours > 0) {
                $validity .= ' ' . $remainingHours . ' ' . ($remainingHours === 1 ? 'hour' : 'hours');
            }
        }
        // Less than 1 day
        else {
            $validity = $hours . ' ' . ($hours === 1 ? 'hour' : 'hours');
        }

        $latest = TvShow::where('status', 1);

        $data = [
            'shows' => $withMedia($tvShow),
            'cast' => $this->getActor($tvShow->stars),
            'director' => $this->getActor($tvShow->director),
            'writer' => $this->getActor($tvShow->writer),
            'related_tv_shows' => (clone $latest)
                ->where('video_type', $tvShow->video_type)
                ->get()
                ->transform($withMedia),
            'video_tags' => array_values(array_filter([
                VideoQuality::where('id', $tvShow->video_quality)->value('quality'),
                $tvShow->is_blockbuster ? 'Blockbuster' : null,
                get_genre($tvShow->genre, 0, 'name'),
                get_genre($tvShow->genre, 0, 'name'),
            ])),
            'rental' => [
                'price' => get_currency($tvShow->rental_price),
                'validity' => validity($tvShow->rental_duration),
                'expire_data' => Carbon::now()->copy()->addHours($tvShow->rental_duration)->format('Y-m-d H:i:s'),
            ],
            'is_rented' => is_rented('series', $tvShow->id, $request->user_id) ? true : false,
            'share_link' => route('series.details', ['slug' => $tvShow->slug]),

        ];
        return $this->responseWithSuccess($data, __('tv_show_details_retrieved_successfully'));
    }

    public function tv_show_filter(Request $request)
    {
        $withMedia = function ($item) {
            $item->thumbnail = apiImageFromJson($item->thumbnail, 'original_image', 'tv_shows');
            $item->poster = apiImageFromJson($item->poster, 'original_image', 'tv_shows');
            $item->is_favorite = auth()->user() ? auth()->user()->favoriteTvShows()->where('tv_show_id', $item->id)->exists() : false;
            return $item;
        };
        $query = TvShow::query();

        // Search by title (partial match)
        if ($request->filled('string')) {
            $query->where('title', 'like', '%' . $request->string . '%');
        }

        // Filter by category_id
        if ($request->filled('category_id')) {
            $query->where('video_type', $request->category_id);
        }
        // Filter by genre
        if ($request->filled('genre')) {
            $query->whereJsonContains('genre', (string) $request->genre);
        }
        // Filter by country
        if ($request->filled('country')) {
            $query->whereJsonContains('country', (string) $request->country);
        }
        // Filter by language
        if ($request->filled('language')) {
            $query->whereJsonContains('language', (string) $request->language);
        }
        // Filter by release date
        if ($request->filled('year')) {
            $query->whereYear('release', $request->year);
        }

        // Filter by year from created_at
        if ($request->filled('sort')) {
            if ($request->sort == 1) {
                $query->where('is_free', 1);
            } elseif ($request->sort == 2) {
                $query->where('is_original', 1);
            }
        }

        $movies = $query->latest()->paginate(20)->through($withMedia);
        return $this->responseWithSuccess(['details' => $movies], __('tv_shows_filter_results_retrieved_successfully'));
    }
}
