<?php

namespace App\Http\Controllers\Api;

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

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

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

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

            return $this->formatPaginatedResponse($videos->items(), 'Videos retrieved successfully', $currentPage, $itemsPerPage, $videos->total());

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

    public function getVideoById($id)
    {
        try {
            $video = Video::with('category')->findOrFail($id);

            return $this->formatResponse($video, 'Video retrieved successfully');

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

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

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

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

            return $this->formatPaginatedResponse($videos->items(), 'Videos retrieved successfully', $currentPage, $itemsPerPage, $videos->total());

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

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

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


}
