<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\MovieRequestStoreRequest;
use App\Http\Requests\CustomerQueryRequest;
use App\Http\Requests\Website\ReportRequest;
use App\Models\Episode;
use App\Models\LiveTv;
use App\Models\LiveTvCategory;
use App\Models\Movie;
use App\Models\Star;
use App\Models\TvShow;
use App\Models\WatchHistory;
use App\Repositories\Interfaces\Admin\CustomerQueryInterface;
use App\Repositories\Interfaces\Admin\MovieRequestInterface;
use App\Repositories\Interfaces\Admin\PageRepositoryInterface;
use App\Repositories\Interfaces\Admin\ReportInterface;
use App\Repositories\Interfaces\Website\BlogRepositoryInterface;
use App\Repositories\Interfaces\Website\HomeRepositoryInterface;
use App\Repositories\Interfaces\Website\PlayerRepositoryInterface;
use Carbon\Carbon;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use ReCaptcha\ReCaptcha;

class FrontendController extends Controller
{
    protected $homeRepository;
    protected $contactUsRepo;
    protected $moveiRequestRepo;
    protected $reportRepo;
    protected $blogRepo;
    protected $playerRepo;
    protected $pageRepository;

    public function __construct(
        CustomerQueryInterface $contactUsRepo,
        MovieRequestInterface $moveiRequestRepo,
        ReportInterface $reportRepo,
        HomeRepositoryInterface $homeRepository,
        BlogRepositoryInterface $blogRepo,
        PlayerRepositoryInterface $playerRepo,

        PageRepositoryInterface $pageRepository
    ) {
        $this->contactUsRepo = $contactUsRepo;
        $this->moveiRequestRepo = $moveiRequestRepo;
        $this->reportRepo = $reportRepo;
        $this->homeRepository = $homeRepository;
        $this->blogRepo = $blogRepo;
        $this->playerRepo = $playerRepo;
        $this->pageRepository = $pageRepository;
    }

    public function index()
    {
        $page_data = $this->homeRepository->getHomePageData();
        return view('website.index', $page_data);
    }

    public function tv_channels(Request $request)
    {
        $query = LiveTv::where('status', 1);

        // Apply search filter
        if ($request->search) {
            $query->where('title', 'like', '%' . $request->search . '%');
        }

        // Filter by categories
        if ($request->has('categories') && is_array($request->categories)) {
            $query->whereIn('live_tv_category_id', $request->categories);
        }

        // Filter by countries
        if ($request->has('countries') && is_array($request->countries)) {
            $query->whereIn('country_id', $request->countries);
        }

        $tv_channels = $query->latest()->paginate(24);
        $type = $request->type;

        if ($request->ajax()) {
            return response()->json([
                'html' => view('website.tv_channel.partials.channel_cards', compact('tv_channels'))->render(),
                'pagination' => view('website.tv_channel.partials.pagination', compact('tv_channels'))->render(),
                'showing' => 'Showing ' . ($tv_channels->firstItem() ?? 0) . ' - ' . ($tv_channels->lastItem() ?? 0) . ' of ' . $tv_channels->total() . ' Live TV'
            ]);
        }

        return view('website.tv_channel.index', compact('tv_channels', 'type'));
    }
    public function tv_channel_details($slug)
    {
        $liveTv = LiveTv::where('slug', $slug)->with('reviews')->first();
        if (! $liveTv) {
            abort(404, __('page_not_found'));
        }
        try {
            if(auth()->user()) {
                $data = [
                    'user_id' => auth()->user()->id,
                    'watchable_type' => 'live_tv',
                    'watchable_id' => $liveTv->id,
                    'duration' => 10,
                    'watched_seconds' => 7,
                    'completion_percentage' => 70,
                ];
                WatchHistory::updateOrCreate($data);
            }

            // Get Ads
            $now = Carbon::now();
            $page_data['pre_roll_ad'] = $this->playerRepo->getAdByType('pre_roll', $now);
            $page_data['mid_roll_ad'] = $this->playerRepo->getAdByType('mid_roll', $now);
            $page_data['post_roll_ad'] = $this->playerRepo->getAdByType('post_roll', $now);

            $liveTv->is_favorite = auth()->user() ? auth()->user()->favoriteLiveTvs()->where('live_tv_id', $liveTv->id)->exists() : false;

            $page_data['tv_channel'] = $liveTv;
            $page_data['related_tv_channels'] = LiveTv::where([
                'live_tv_category_id' => $liveTv->live_tv_category_id,
                'status' => 1
            ])->latest()->limit(15)->get();
            return view('website.tv_channel.details', $page_data);
        } catch (Exception $e) {
            return redirect()->back()->with('error_message', __('login_required'));
        }
    }

    public function blogs(Request $request)
    {

        $blogs = $this->blogRepo->getBlogs($request);
        $top_blogs = $this->blogRepo->getTopBlogs();

        if ($request->ajax()) {
            return response()->json([
                'blogs' => view('website.blog.partials.blog_cards', compact('blogs'))->render(),
                'paginations' => view('website.blog.partials.pagination', compact('blogs'))->render(),
                'showing' => view('website.blog.partials.showing', compact('blogs'))->render(),
            ]);
        }

        return view('website.blog.index', compact('blogs', 'top_blogs'));
    }

    public function blog_details($slug = null)
    {
        $data = $this->blogRepo->getBlogDetails($slug);

        if (!$data) {
            abort(404);
        }

        $page_data = [
            'blog' => $data['blog'],
            'related_blogs' => $data['related_blogs'],
            'slug' => $slug,
        ];

        return view('website.blog.details', $page_data);
    }

    public function faqs()
    {
        $page_data = $this->homeRepository->getFaqs();
        return view('website.pages.faqs', $page_data);
    }

    public function contactUs()
    {
        try {
            return view('website.pages.contact_us');
        } catch (Exception $e) {
            Log::error('Failed to redirect contact us page', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return back()->with('error_message', 'Something went wrong while submitting your request. Please try again later.');
        }
    }


    public function contactUsPost(CustomerQueryRequest $request)
    {
        if (get_config('is_recaptcha_activated')) {
            $secret = get_config('recaptcha_secret_key');
            if (!$secret) {
                return back()->withInput()->with('error_message', __('recaptcha_secret_missing'));
            }
            $recaptcha = new ReCaptcha($secret);
            $response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
            if (!$response->isSuccess()) {
                return back()->withInput()->with('error_message', __('please_verify_that_you_are_not_a_robot'));
            }
        }
        try {
            $this->contactUsRepo->store($request->all());

            return redirect()->back()->with('success_message', __('message_sent_successfully'));
        } catch (Exception $e) {
            Log::error('Error saving contact message: ' . $e->getMessage());
            return redirect()->back()->with('error_message', __('processing_error'));
        }
    }
    public function downloadLinks(Episode $episode)
    {
        $html = '';

        if ($episode->downloadLinks->isEmpty()) {
            return '<p>' . __('no_download_links_available') . '</p>';
        }

        foreach ($episode->downloadLinks as $link) {
            $html .= '<div class="d-flex justify-content-between align-items-center mb-3">';
            $html .= '<div>';
            $html .= '<strong>' . e($link->title) . '</strong><br>';
            if ($link->resolution) {
                $html .= '<small>' . __('resolution') . ': ' . e($link->resolution) . '</small><br>';
            }
            if ($link->file_size) {
                $html .= '<small>' . __('size') . ': ' . e($link->file_size) . '</small>';
            }
            $html .= '</div>';
            $html .= '<a href="' . e($link->link) . '" class="btn btn-primary" target="_blank" download>' . __('download') . '</a>';
            $html .= '</div>';
        }

        return $html;
    }

    public function loadPlayer(Request $request)
    {
        $page_data = $this->playerRepo->loadPlayerData($request);
        return view('website.player.video_player', $page_data);
    }

    public function storeMovieRequest(MovieRequestStoreRequest $request)
    {
        if (isDemoMode()) {
           return back()->with('error_message', 'This action is disabled in demo mode.');
        }
        if (get_config('is_recaptcha_activated')) {
            $secret = get_config('recaptcha_secret_key');
            if (!$secret) {
                return back()->withInput()->with('error_message', __('recaptcha_secret_missing'));
            }
            $recaptcha = new ReCaptcha($secret);
            $response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
            if (!$response->isSuccess()) {
                return back()->withInput()->with('error_message', __('please_verify_that_you_are_not_a_robot'));
            }
        }
        try {
            $this->moveiRequestRepo->create($request->validated());

            return back()->with('success_message', 'Movie request submitted successfully!');
        } catch (Exception $e) {
            Log::error('Movie request submission failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'data' => $request->all(),
            ]);

            return back()->with('error_message', 'Something went wrong while submitting your request. Please try again later.');
        }
    }

    public function movieReport(ReportRequest $request)
    {
        if (isDemoMode()) {
           return back()->with('error_message', 'This action is disabled in demo mode.');
        }
        if (get_config('is_recaptcha_activated')) {
            $secret = get_config('recaptcha_secret_key');
            if (!$secret) {
                return back()->withInput()->with('error_message', __('recaptcha_secret_missing'));
            }
            $recaptcha = new ReCaptcha($secret);
            $response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
            if (!$response->isSuccess()) {
                return back()->withInput()->with('error_message', __('please_verify_that_you_are_not_a_robot'));
            }
        }
        try {
            $this->reportRepo->create($request->validated());

            return back()->with('success_message', __('report_submitted_successfully'));
        } catch (\Throwable $e) {
            Log::error('Failed to submit movie report', [
                'error' => $e->getMessage(),
                'user_id' => auth()->user()->id ?? null,
                'input' => $request->all(),
            ]);

            return back()->with('error_message', __('something_went_wrong_please_try_again'));
        }
    }
    public function page(Request $request, $link)
    {
        $page = $this->pageRepository->findByLink($link);
        if (!$page) {
            abort(404, __('page_not_found'));
        }
        $lang = $request->lang ?? app()->getLocale();

        $data = [
            'lang' => $request->lang ?? app()->getLocale(),
            'page_info' => $this->pageRepository->getByLang($page->id, $lang),
        ];

        return view('website.page', $data);
    }

    public function live_tv_category($slug)
    {
        $category = LiveTvCategory::where('slug', $slug)->first();
        if (!$category) {
            abort(404, __('page_not_found'));
        }
        $tv_channels = LiveTv::where('live_tv_category_id', $category->id)->latest()->paginate(24);
        $type = $category->live_tv_category;

        return view('website.tv_channel.index', compact('category', 'type', 'tv_channels'));
    }

    public function artist_details($slug = null)
    {
        $page_data['artist'] = Star::where('slug', $slug)->first();
        if (!$page_data['artist']) {
            abort(404, __('page_not_found'));
        }
        $page_data['movies'] = Movie::whereJsonContains('stars', (string)$page_data['artist']->id)
            ->where('status', 1)
            ->orderBy('created_at', 'desc')
            ->take(30)
            ->get();
        $page_data['tv_series'] = TvShow::whereJsonContains('stars', (string)$page_data['artist']->id)
            ->where('status', 1)
            ->orderBy('created_at', 'desc')
            ->take(30)
            ->get();

        return view('website.pages.artist_details', $page_data);
    }

    public function artist_list(Request $request)
    {
        $query = Star::query();

        if ($request->search) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        $artists = $query->latest()->paginate(24);

        if ($request->ajax()) {
            return response()->json([
                'html' => view('website.movie.partials.artist_cards', compact('artists'))->render(),
                'pagination' => view('website.movie.partials.pagination', compact('artists'))->render(),
                'showing' => 'Showing ' . ($artists->firstItem() ?? 0) . ' - ' . ($artists->lastItem() ?? 0) . ' of ' . $artists->total() . ' Artists'
            ]);
        }

        return view('website.pages.artist_list', compact('artists'));
    }
}
