<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use App\Models\Country;
use App\Models\LiveTv;
use App\Models\LiveTvCategory;
use App\Models\LiveTvUrl;
use App\Models\User;
use App\Traits\Mobile\ApiResponseTrait;
use Illuminate\Http\Request;

class LiveTvController extends Controller
{
    use ApiResponseTrait;
    public function liveTvLists(Request $request)
    {
        $withMedia = function ($item) {
            $item->thumbnail = apiImageFromJson($item->thumbnail, 'original_image', '');
            return $item;
        };
        $query = LiveTv::query();

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

        // Filter by category_id
        if ($request->filled('category_id')) {
            $query->where('live_tv_category_id', $request->category_id);
        }
        // Filter by country
        if ($request->filled('country_id')) {
            $query->where('country_id', $request->country_id);
        }

        $data = [
            'live_tvs' => $query->latest()->paginate(20)->through($withMedia),
            'filter' => [
                'categories' => LiveTvCategory::get(),
                'country' => Country::get()
            ]
        ];
        return $this->responseWithSuccess($data, __('live_tv_retrieved_successfully'));
    }

    public function liveTvDetails(Request $request)
    {
        $user = User::with('favoriteLiveTvs')->find($request->user_id);

        $withMedia = function ($item) {
            $item->thumbnail = apiImageFromJson($item->thumbnail, 'original_image', '');
            return $item;
        };

        $liveTv = LiveTv::where('id', $request->id) // change if needed
            ->first();

        if (!$liveTv) {
            return $this->responseWithError(__('live_tv_not_found'), 400);
        }

        $live_tv_url = LiveTvUrl::where('live_tv_id', $liveTv->id)->get()->map(function ($url) {
            return [
                'id' => $url->id,
                'stream_url' => $url->url,
                'stream_label' => $url->label,
            ];
        });

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

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

        $data = [
            'live_tv_details' => $withMedia($liveTv),
            'related_live_tvs' => (clone $latest)
                ->where('live_tv_category_id', $liveTv->live_tv_category_id)
                ->get()
                ->transform($withMedia),
            'stream' => $live_tv_url,
            'share_link' => route('live.tv.details', ['slug' => $liveTv->slug]),
        ];

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