<?php

namespace App\Http\Controllers\Api;

use App\Models\Series;
use App\Models\Season;
use App\Models\Episode;
use Illuminate\Http\Request;

class SeriesController extends BaseController
{
    // GET /api/series?page=1&per_page=10&category_id=1
    public function index(Request $request)
    {
        try {
            $itemsPerPage = min((int) $request->input('per_page', 10), 100);
            $currentPage  = $request->input('page', 1);

            $query = Series::with('category')->where('status', 0);

            if ($request->filled('category_id')) {
                $query->where('category_id', $request->category_id);
            }

            $series = $query->orderByDesc('created_at')
                ->paginate($itemsPerPage, ['*'], 'page', $currentPage);

            return $this->formatPaginatedResponse(
                $series->items(),
                'Series retrieved successfully',
                $currentPage,
                $itemsPerPage,
                $series->total()
            );
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    // GET /api/series/{id}
    public function show($id)
    {
        try {
            $series = Series::with(['category', 'seasons'])->where('status', 0)->findOrFail($id);

            return response()->json([
                'status'  => 'success',
                'message' => 'Series retrieved successfully',
                'data'    => $series,
            ]);
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    // GET /api/series/{id}/seasons
    public function seasons($id)
    {
        try {
            $series = Series::where('status', 0)->findOrFail($id);

            $seasons = Season::where('series_id', $id)
                ->where('status', 0)
                ->orderBy('season_number')
                ->get();

            return response()->json([
                'status'  => 'success',
                'message' => 'Seasons retrieved successfully',
                'data'    => $seasons,
            ]);
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    // GET /api/series/{id}/seasons/{seasonId}/episodes
    public function episodes($id, $seasonId)
    {
        try {
            $season = Season::where('id', $seasonId)
                ->where('series_id', $id)
                ->where('status', 0)
                ->firstOrFail();

            $episodes = Episode::where('season_id', $seasonId)
                ->where('series_id', $id)
                ->where('status', 0)
                ->orderBy('episode_number')
                ->get();

            return response()->json([
                'status'  => 'success',
                'message' => 'Episodes retrieved successfully',
                'data'    => $episodes,
            ]);
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    // GET /api/series/{id}/episodes/{episodeId}
    public function episodeDetail($id, $episodeId)
    {
        try {
            $episode = Episode::where('id', $episodeId)
                ->where('series_id', $id)
                ->where('status', 0)
                ->firstOrFail();

            return response()->json([
                'status'  => 'success',
                'message' => 'Episode retrieved successfully',
                'data'    => $episode,
            ]);
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    // GET /api/series/{id}/episodes/{episodeId}/view  (increment view count)
    public function incrementEpisodeView($id, $episodeId)
    {
        try {
            $episode = Episode::where('id', $episodeId)
                ->where('series_id', $id)
                ->firstOrFail();

            $episode->increment('total_views');

            return response()->json([
                'status'  => 'success',
                'message' => 'View count incremented',
            ]);
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }

    // GET /api/series/{id}/view  (increment series view count)
    public function incrementSeriesView($id)
    {
        try {
            $series = Series::findOrFail($id);
            $series->increment('total_views');

            return response()->json([
                'status'  => 'success',
                'message' => 'View count incremented',
            ]);
        } catch (\Exception $e) {
            return $this->handleException($e);
        }
    }
}
