<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Tv;

class TvController extends BaseController
{
    public function getTvList(Request $request) {
        try {
            $itemsPerPage = min((int) $request->input('per_page', 10), 100);
            $currentPage = $request->input('page', 1);

            $tvs = Tv::with('category')->where('status', 0)->orderBy('created_at', 'desc')->paginate($itemsPerPage, ['*'], 'page', $currentPage); 

            if ($tvs->isEmpty()) {
                return $this->formatPaginatedResponse([], 'No tv list found', $currentPage, $itemsPerPage, $tvs->total());
            }

            return $this->formatPaginatedResponse($tvs->items(), 'TV list retrieved successfully', $currentPage, $itemsPerPage, $tvs->total());

        }catch(\Exception $e){
            return $this->handleException($e);
        }
 
    }

    public function getTvById($id)
    {
        try {
            $tv = Tv::with('category')->findOrFail($id);

            return $this->formatResponse($tv, 'TV retrieved successfully');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    public function getTvListByCategoryId(Request $request, $categoryId)
    {
        try {
            $itemsPerPage = min((int) $request->input('per_page', 10), 100);
            $currentPage = $request->input('page', 1);

            $tvs = Tv::with('category')
                ->where('status', 0)
                ->where('tv_category_id', $categoryId)
                ->orderBy('created_at', 'desc')
                ->paginate($itemsPerPage, ['*'], 'page', $currentPage);

            if ($tvs->isEmpty()) {
                return $this->formatPaginatedResponse([], 'No tv found', $currentPage, $itemsPerPage, $tvs->total());
            }

            return $this->formatPaginatedResponse($tvs->items(), 'TV list retrieved successfully', $currentPage, $itemsPerPage, $tvs->total());

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    public function incrementViewCount($id)
    {
        try {
            $tv = Tv::findOrFail($id);
            $tv->increment('total_views');
            
            return $this->formatResponse(null, 'View count incremented successfully');

        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }
    
}
