<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use App\Http\Requests\ContactUsRequest;
use App\Http\Requests\CustomerQueryRequest;
use App\Http\Resources\MovieMinimalResource;
use App\Models\Blog;
use App\Models\Category;
use App\Models\Country;
use App\Models\Faq;
use App\Models\Genre;
use App\Models\LiveTv;
use App\Models\LiveTvCategory;
use App\Models\Movie;
use App\Models\Star;
use App\Models\TvShow;
use App\Repositories\Interfaces\Admin\CustomerQueryInterface;
use App\Traits\Mobile\ApiResponseTrait;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Pagination\LengthAwarePaginator;

class PageController extends Controller
{
    use ApiResponseTrait;

    protected $contactUsRepo;

    public function __construct(CustomerQueryInterface $contactUsRepo)
    {
        $this->contactUsRepo = $contactUsRepo;
    }
    public function home()
    {
        // Base queries
        $movies = Movie::where('status', 1);
        $tv_shows = TvShow::where('status', 1);
        $live_tvs = LiveTv::where('status', 1);


        // DRY: Decode thumbnail & poster from JSON string to actual URL
        $decodeMediaFields = function ($item) {
            $item->thumbnail = apiImageFromJson($item->thumbnail, 'original_image', '');
            $item->poster = apiImageFromJson($item->poster, 'original_image', '');
            return $item;
        };
        $blogMediaFields = function ($item) {
            $item->image = apiImageFromJson($item->image, 'original_image', '');
            $item->author = adminInfo('first_name') . ' ' . adminInfo('last_name');
            return $item;
        };
        $starMediaFields = function ($item) {
            $item->star_image = apiImageFromJson($item->star_image, 'original_image', '');
            return $item;
        };
        $decodeTags = function ($item) {
            $item->video_tags = array_values(array_filter([
                $item->quality->quality ?? null,
                get_genre($item->genre, 0, 'name'),
            ]));
            return $item;
        };

        // Wrapper that applies both
        $decodeMediaAndTags = function ($item) use ($decodeMediaFields, $decodeTags) {
            $item = $decodeMediaFields($item);
            $item = $decodeTags($item);
            return $item;
        };
        // Movies
        $new_release = MovieMinimalResource::collection((clone $movies)->latest()->get()->transform($decodeMediaFields));
        $trending = MovieMinimalResource::collection((clone $movies)->where('is_trending', 1)->get()->transform($decodeMediaFields));
        $sliders = MovieMinimalResource::collection((clone $movies)->where('status', 1)->orderBy('id', 'DESC')->limit(10)->get()->transform($decodeMediaAndTags));
        $recommended_movies = MovieMinimalResource::collection((clone $movies)->where('is_recommended', 1)->get()->transform($decodeMediaFields));
        $featured_movies = MovieMinimalResource::collection((clone $movies)->where('is_featured', 1)->get()->transform($decodeMediaFields));

        // TV
        $featured_tv_channels = (clone $live_tvs)->where('featured', 1)->latest()->get()->transform($decodeMediaFields);
        $tv_shows_latest = (clone $tv_shows)->latest()->get()->transform($decodeMediaFields);
        $popular_tv_shows = (clone $tv_shows)->orderBy('total_view', 'DESC')->get()->transform($decodeMediaFields);

        // Others
        $top_artists = Star::where('star_type', 'actor')->where('status', 1)->latest()->get()->transform($starMediaFields);
        $latest_blogs = Blog::where('status', 1)->latest()->get()->transform($blogMediaFields);
        $genres = Genre::where('status', 1)->get();
        // Response structure
        $data = [
            'sliders' => $sliders,
            'genres' => $genres,
            'new_release_movies' => $new_release,
            'trending_movies' => $trending,
            'recommended_movies' => $recommended_movies,
            'featured_movies' => $featured_movies,
            'popular_tv_shows' => $popular_tv_shows,
            'promo_videos' => '',
            'history_sliders' => '',
            'featured_tv_channels' => $featured_tv_channels,
            'tv_shows' => $tv_shows_latest,
            'top_artists' => $top_artists,
            'latest_blogs' => $latest_blogs,
            'privacy_policy' => get_config('privacy_policy_link'),
            'payment_policy' => get_config('payment_policy_link'),
            'terms_and_conditions' => get_config('terms_and_conditions'),
            'countries' => Country::where('status', 1)->get(),
            'live_tv_categories' => LiveTvCategory::where('status', 1)->get()
        ];

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

    public function allGenre()
    {
        $data = [
            'genres' => Genre::where('status', 1)->get()
        ];
        return $this->responseWithSuccess($data, __('home_page_data_retrieved_successfully'));
    }
    public function contactUsPost(CustomerQueryRequest $request)
    {
        try {
            $data = $this->contactUsRepo->store($request->all());

            return $this->responseWithSuccess($data, __('message_sent_successfully'));
        } catch (Exception $e) {
            Log::error('Error saving contact message: ' . $e->getMessage());
            return $this->responseWithError(__('processing_error'), 500);
        }
    }

    public function globalSearch(Request $request)
    {
        $search = $request->input('search');
        $category = $request->input('category');
        $country = $request->input('country', []);
        $genre = $request->input('genre', []);
        $year = $request->input('year');
        $type = $request->input('type');

        $perPage = max((int) $request->input('per_page', 10), 1);
        $page = max((int) $request->input('page', 1), 1);

        // Prepare base queries
        $movieQuery = $this->buildSearchQuery(Movie::query(), $search, $category, $country, $genre, $year);
        $tvQuery = $this->buildSearchQuery(TvShow::query(), $search, $category, $country, $genre, $year);
        $liveTvQuery = LiveTv::query()->where('status', 1)
            ->when($search, fn($q) => $q->where('tv_name', 'like', "%$search%"))
            ->when($category, fn($q) => $q->where('live_tv_category_id', $category))
            ->when(is_array($country) && !empty($country), function ($q) use ($country) {
                foreach ($country as $c) {
                    $q->where('country_id', $c);
                }
            });


        if (!empty($type)) {
            if ($type === 'movie') {
                $tvQuery = null;
                $liveTvQuery = null;
            } elseif ($type === 'tv_show') {
                $movieQuery = null;
                $liveTvQuery = null;
            } elseif ($type === 'live_tv') {
                $movieQuery = null;
                $tvQuery = null;
            }
        }

        // Fetch and tag results

        $movies = $movieQuery ? $movieQuery->get()->each->setAttribute('type', 'movie') : collect();
        $tvshows = $tvQuery ? $tvQuery->get()->each->setAttribute('type', 'tvshow') : collect();
        $liveTvs = $liveTvQuery ? $liveTvQuery->get()->each->setAttribute('type', 'live_tv') : collect();

        // Combine and paginate
        $combined = $movies->concat($tvshows)->sortByDesc('release_date')->values();
        $combined = $combined->concat($liveTvs)->sortByDesc('release_date')->values();

        $paginated = new LengthAwarePaginator(
            $combined?->forPage($page, $perPage)->values(),
            $combined?->count(),
            $perPage,
            $page,
            [
                'path' => url()->current(),
                'query' => request()->query(),
            ]
        );

        return $this->responseWithSuccess([
            'searched_data' => $paginated,
            'filter' => [
                'categories' => Category::all(),
                'country' => Country::all(),
                'genre' => Genre::all(),
                'year' => range(1975, date('Y')),
            ]
        ], __('search_data_retrieved_successfully'));
    }

    /**
     * Build the dynamic query for Movie or TVShow
     */
    private function buildSearchQuery($query = null, $search = null, $category = null, $country = null, $genre = null, $year = null)
    {
        return $query->where('status', 1)
            ->when($search, fn($q) => $q->where('title', 'like', "%$search%"))
            ->when($category, fn($q) => $q->where('video_type', $category))
            ->when(is_array($country) && !empty($country), function ($q) use ($country) {
                $q->whereNotNull('country')
                    ->whereRaw('JSON_VALID(country)');
                foreach ($country as $c) {
                    $q->whereJsonContains('country', $c);
                }
            })
            ->when(is_array($genre) && !empty($genre), function ($q) use ($genre) {
                $q->whereNotNull('genre')
                    ->whereRaw('JSON_VALID(genre)');
                foreach ($genre as $g) {
                    $q->whereJsonContains('genre', $g);
                }
            })
            ->when($year, fn($q) => $q->whereYear('release', $year));
    }

    public function faqs()
    {
        $faqs = Faq::where('status', 1)->get()->groupBy('type');

        return $this->responseWithSuccess($faqs, __('faq_data_retrieved_successfully'));
    }
}
