<?php

namespace App\Http\Controllers\Admin;

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

class SeriesController extends Controller
{
    protected $user;

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

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

        $headerTitle = 'Series List';

        if ($request->ajax()) {
            $query = Series::with('category')->latest();

            return DataTables::of($query)
                ->addColumn('category_name', fn($s) => $s->category?->name ?? 'N/A')
                ->editColumn('thumbnail_image', function ($s) {
                    return $s->thumbnail_image
                        ? '<img src="' . asset($s->thumbnail_image) . '" style="width:40px;height:60px;object-fit:cover">'
                        : 'N/A';
                })
                ->editColumn('status', fn($s) => $s->status === 0
                    ? '<span class="badge badge-success">Active</span>'
                    : '<span class="badge badge-secondary">Inactive</span>')
                ->addColumn('seasons_count', fn($s) => $s->seasons()->count())
                ->addColumn('actions', fn($s) => view('backend.admin.series.partials.actions', compact('s'))->render())
                ->rawColumns(['thumbnail_image', 'status', 'actions'])
                ->make(true);
        }

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

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

        return view('backend.admin.series.add', [
            'headerTitle' => 'Add New Series',
            'categories'  => Category::all(),
        ]);
    }

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

        $validator = Validator::make($request->all(), [
            'title'           => 'required|string|max:255',
            'category_id'     => 'required|exists:categories,id',
            'thumbnail_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'description'     => 'nullable|string',
        ]);

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

        $thumbPath = $this->handleUploadedFile($request->file('thumbnail_image'), 'assets/uploads/series/images/');

        Series::create([
            'title'           => $request->title,
            'category_id'     => $request->category_id,
            'thumbnail_image' => $thumbPath,
            'description'     => $request->description,
        ]);

        return redirect('admin/series')->with('success', 'Series created successfully');
    }

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

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

        return view('backend.admin.series.edit', [
            'headerTitle' => 'Edit Series',
            'series'      => $series,
            'categories'  => Category::all(),
        ]);
    }

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

        $series = Series::findOrFail($request->series_id);

        $validator = Validator::make($request->all(), [
            'title'           => 'required|string|max:255',
            'category_id'     => 'required|exists:categories,id',
            'thumbnail_image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'description'     => 'nullable|string',
        ]);

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

        if ($request->hasFile('thumbnail_image')) {
            $this->deleteFile($series->thumbnail_image);
            $series->thumbnail_image = $this->handleUploadedFile($request->file('thumbnail_image'), 'assets/uploads/series/images/');
        }

        $series->title       = $request->title;
        $series->category_id = $request->category_id;
        $series->description = $request->description;
        $series->status      = $request->status ?? 0;
        $series->save();

        return redirect('admin/series')->with('success', 'Series updated successfully');
    }

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

        $series = Series::findOrFail($id);
        $this->deleteFile($series->thumbnail_image);
        $series->delete();

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

    // -------------------------------------------------------------------------

    private function handleUploadedFile($file, $directory)
    {
        if ($file && $file->isValid()) {
            $fileName = Str::uuid() . '.' . $file->getClientOriginalExtension();
            $file->move(public_path($directory), $fileName);
            return $directory . $fileName;
        }
        return null;
    }

    private function deleteFile($filePath)
    {
        if ($filePath && file_exists(public_path($filePath))) {
            unlink(public_path($filePath));
        }
    }
}
