<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Series;
use App\Models\Season;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Validator;
use DataTables;

class SeasonController extends Controller
{
    protected $user;

    public function __construct()
    {
        $this->user = Auth::guard('admin')->user();
    }

    public function index(Request $request, $seriesId)
    {
        if (is_null($this->user) || !$this->user->can('video.view')) {
            abort(403, 'Access Denied');
        }

        $series      = Series::findOrFail($seriesId);
        $headerTitle = "Seasons – {$series->title}";

        if ($request->ajax()) {
            $query = Season::where('series_id', $seriesId)->orderBy('season_number');

            return DataTables::of($query)
                ->addColumn('episodes_count', fn($s) => $s->episodes()->count())
                ->editColumn('status', fn($s) => $s->status === 0
                    ? '<span class="badge badge-success">Active</span>'
                    : '<span class="badge badge-secondary">Inactive</span>')
                ->addColumn('actions', fn($s) => view('backend.admin.seasons.partials.actions', ['season' => $s, 'seriesId' => $seriesId])->render())
                ->rawColumns(['status', 'actions'])
                ->make(true);
        }

        return view('backend.admin.seasons.index', compact('headerTitle', 'series'));
    }

    public function add($seriesId)
    {
        if (is_null($this->user) || !$this->user->can('video.create')) {
            return back()->with('error', 'Access Denied');
        }

        $series = Series::findOrFail($seriesId);

        return view('backend.admin.seasons.add', [
            'headerTitle' => 'Add Season',
            'series'      => $series,
        ]);
    }

    public function insert(Request $request, $seriesId)
    {
        if (is_null($this->user) || !$this->user->can('video.create')) {
            abort(403, 'Access Denied');
        }

        $series = Series::findOrFail($seriesId);

        $validator = Validator::make($request->all(), [
            'season_number' => "required|integer|min:1|unique:seasons,season_number,NULL,id,series_id,{$seriesId}",
            'title'         => 'nullable|string|max:255',
            'description'   => 'nullable|string',
        ], [
            'season_number.unique' => 'This season number already exists for the series.',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        Season::create([
            'series_id'     => $seriesId,
            'season_number' => $request->season_number,
            'title'         => $request->title,
            'description'   => $request->description,
        ]);

        return redirect("admin/series/{$seriesId}/seasons")->with('success', 'Season added successfully');
    }

    public function edit($seriesId, $id)
    {
        if (is_null($this->user) || !$this->user->can('video.edit')) {
            return back()->with('error', 'Access Denied');
        }

        $series = Series::findOrFail($seriesId);
        $season = Season::where('series_id', $seriesId)->findOrFail($id);

        return view('backend.admin.seasons.edit', [
            'headerTitle' => 'Edit Season',
            'series'      => $series,
            'season'      => $season,
        ]);
    }

    public function update(Request $request, $seriesId, $id)
    {
        if (is_null($this->user) || !$this->user->can('video.edit')) {
            return back()->with('error', 'Access Denied');
        }

        $season = Season::where('series_id', $seriesId)->findOrFail($id);

        $validator = Validator::make($request->all(), [
            'season_number' => "required|integer|min:1|unique:seasons,season_number,{$id},id,series_id,{$seriesId}",
            'title'         => 'nullable|string|max:255',
            'description'   => 'nullable|string',
        ], [
            'season_number.unique' => 'This season number already exists for the series.',
        ]);

        if ($validator->fails()) {
            return redirect()->back()->withErrors($validator)->withInput();
        }

        $season->season_number = $request->season_number;
        $season->title         = $request->title;
        $season->description   = $request->description;
        $season->status        = $request->status ?? 0;
        $season->save();

        return redirect("admin/series/{$seriesId}/seasons")->with('success', 'Season updated successfully');
    }

    public function delete($seriesId, $id)
    {
        if (is_null($this->user) || !$this->user->can('video.delete')) {
            return back()->with('error', 'Access Denied');
        }

        $season = Season::where('series_id', $seriesId)->findOrFail($id);
        $season->delete();

        return redirect()->back()->with('success', 'Season deleted successfully');
    }
}
