<?php

namespace App\Http\Controllers\Api\Mobile;

use App\Http\Controllers\Controller;
use App\Models\Movie;
use App\Models\Rent;
use App\Models\RentalHistory;
use App\Traits\Mobile\ApiResponseTrait;
use Illuminate\Http\Request;
use Exception;

class RentController extends Controller
{
    protected $reviewRepo;

    use ApiResponseTrait;

    public function rentVideoList(Request $request)
    {

        try {
            $rents = RentalHistory::where('user_id', $request->user_id)->get();
            if ($rents->isEmpty()) {
                return $this->responseWithError(
                    'No rented videos found for this user.',
                    200
                );
            }
            $rents->map(function ($rent) {
                if($rent->video_type == 'movie') {
                    $movie = Movie::find($rent->video_id); // Or $rent->movie if relation exists

                    if ($movie) {
                        $rent->title = $movie->title;
                        $rent->image = isset($movie->thumbnail) ? apiImageFromJson($movie->thumbnail, 'original_image', 'movies') : 'https://placehold.co/500x570'; // or $movie->poster, etc.
                    }
                } elseif ($rent->video_type == 'tv_show') {
                    $tvShow = \App\Models\TvShow::find($rent->video_id); // Or $rent->tvShow if relation exists

                    if ($tvShow) {
                        $rent->title = $tvShow->title;
                        $rent->image = isset($tvShow->thumbnail) ? apiImageFromJson($tvShow->thumbnail, 'original_image', 'tv_shows') : 'https://placehold.co/500x570'; // or $tvShow->poster, etc.
                    }
                } elseif ($rent->video_type == 'live_tv') {
                    $liveTv = \App\Models\LiveTv::find($rent->video_id); // Or $rent->liveTv if relation exists

                    if ($liveTv) {
                        $rent->title = $liveTv->title;
                        $rent->image = apiImageFromJson($liveTv->thumbnail, 'original_image', '') ?? 'https://placehold.co/500x570'; // or $liveTv->poster, etc.
                    }
                } else {
                    $rent->title = 'Unknown Video Type';
                    $rent->image = null;
                }
    
                return $rent;
            });
            return $this->responseWithSuccess(['rents' => $rents], __('rent_retrieve_successfully'));
        } catch (Exception $e) {
            // Log::error('Review store failed', ['error' => $e->getMessage()]);
            return $this->responseWithError(
                $e->getMessage(),
                500
            );
        }
    }
}
