<?php

namespace App\Http\Controllers\Admin;

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

class SliderController 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('slider.view')) {
            abort(403, 'Access Denied: You do not have permission to view sliders.');
        }

        $headerTitle = 'Slider List';

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

            return DataTables::of($query)
                        ->addColumn('category_name', function ($slider) {
                            return $slider->category ? $slider->category->name : 'N/A';
                        })
                        ->editColumn('status', function($slider) {
                            return $slider->status === 0 
                                ? '<span class="badge badge-success">Active</span>' 
                                : '<span class="badge badge-secondary">Inactive</span>';
                        })
                        ->addColumn('actions', function($slider) {
                            return view('backend.admin.sliders.partials.actions', compact('slider'))->render();
                        })
                        ->rawColumns(['category_name', 'status', 'actions'])
                        ->make(true);
        }

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

    public function add() {
        if (is_null($this->user) || !$this->user->can('slider.create')) {
            return back()->with('error', 'Access Denied: You do not have permission to create new slider.');
        }

        $data['headerTitle'] = 'Add New Slider';
        $data['categories'] = Category::all();

        return view('backend.admin.sliders.add', $data);
    }

    public function insert(Request $request) {
        if (is_null($this->user) || !$this->user->can('slider.create')) {
            abort(403, 'Access Denied: You do not have permission to create new slider.');
        }

        $rules = [
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id', 
            'thumbnail_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'video_type' => 'required|in:upload,youtube,radio,other',
            'video' => 'nullable|required_if:video_type,upload',
            'youtube_url' => 'nullable|required_if:video_type,youtube|url|max:255',
            'radio_url' => 'nullable|required_if:video_type,radio|url|max:255',
            'other_url' => 'nullable|required_if:video_type,other|url|max:255',
            'description' => 'required|string',
        ];

        $customMessage = [
            'category_id.required' => 'Please select a category',
            'video.required_if' => 'Please upload a video',
            'youtube_url.required_if' => 'YouTube URL is required',
            'radio_url.required_if' => 'Radio URL is required',
            'other_url.required_if' => 'Other URL is required',
        ];

        $validator = Validator::make($request->all(), $rules, $customMessage);

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

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

        $videoURL = null;
        if ($request->video_type == 'upload' && $request->hasFile('video')) {
            $videoURL = $this->handleUploadedFile($request->file('video'), 'assets/uploads/sliders/videos/');
        }

        $slider = new Slider;
        $slider->title = $request->title;
        $slider->category_id = $request->category_id;
        $slider->thumbnail_image = $thumbnailImageURL;
        $slider->video_type = $request->video_type;
        $slider->description = $request->description;

        switch ($request->video_type) {
            case 'upload':
                $slider->video = $videoURL;
                $slider->youtube_url = null;
                $slider->radio_url = null;
                $slider->other_url = null;
                break;
            case 'youtube':
                $slider->video = null;
                $slider->youtube_url = $request->youtube_url;
                $slider->radio_url = null;
                $slider->other_url = null;
                break;
            case 'radio':
                $slider->video = null;
                $slider->youtube_url = null;
                $slider->radio_url = $request->radio_url;
                $slider->other_url = null;
                break;
            case 'other':
                $slider->video = null;
                $slider->youtube_url = null;
                $slider->radio_url = null;
                $slider->other_url = $request->other_url;
                break;
        }

        $slider->save();

        return redirect('admin/sliders')->with("success", "Slider successfully added");
    }

    public function edit($id) {
        if (is_null($this->user) || !$this->user->can('slider.edit')) {
            return back()->with('error', 'Access Denied: You do not have permission to edit slider.');
        }

        $data['slider'] = Slider::find($id);

        if(!empty($data['slider'])) {
            $data['headerTitle'] = 'Edit Slider';
            $data['categories'] = Category::all();

            return view('backend.admin.sliders.edit', $data);
        }else {
            abort(404);
        }
    }

    public function update(Request $request) {
        if (is_null($this->user) || !$this->user->can('slider.edit')) {
            return back()->with('error', 'Access Denied: You do not have permission to edit slider.');
        }

        $slider = Slider::find($request->slider_id);
        if (!$slider) {
            return redirect()->back()->with('error', 'Slider not found.');
        }

        $rules = [
            'title' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id', 
            'thumbnail_image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg,webp|max:2048',
            'video_type' => 'required|in:upload,youtube,radio,other',
            'video' => $request->has('video') ? 'required' : 'nullable',
            'youtube_url' => 'nullable|required_if:video_type,youtube|url|max:255',
            'radio_url' => 'nullable|required_if:video_type,radio|url|max:255',
            'other_url' => 'nullable|required_if:video_type,other|url|max:255',
            'description' => 'required|string',
        ];

        $customMessage = [
            'video.required' => 'Please upload a video',
            'youtube_url.required_if' => 'YouTube URL is required',
            'radio_url.required_if' => 'Radio URL is required',
            'other_url.required_if' => 'Other URL is required',
        ];

        $validator = Validator::make($request->all(), $rules, $customMessage);

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

        if ($request->hasFile('thumbnail_image')) {
            $this->deleteFile($slider->thumbnail_image);

            $thumbnailImageURL = $this->handleUploadedFile($request->file('thumbnail_image'), 'assets/uploads/sliders/images/');
            $slider->thumbnail_image = $thumbnailImageURL;
        }

        if ($request->video_type == 'upload' && $request->hasFile('video')) {
            $this->deleteFile($slider->video);

            $videoURL = $this->handleUploadedFile($request->file('video'), 'assets/uploads/sliders/videos/');
            $slider->video = $videoURL;
        }

        $slider->title = $request->title;
        $slider->category_id = $request->category_id;
        $slider->video_type = $request->video_type;
        $slider->description = $request->description;
        $slider->status = $request->status;

        switch ($request->video_type) {
            case 'upload':
                $slider->youtube_url = null;
                $slider->radio_url = null;
                $slider->other_url = null;
                break;
            case 'youtube':
                $this->deleteFile($slider->video);
                $slider->video = null;
                $slider->youtube_url = $request->youtube_url;
                $slider->radio_url = null;
                $slider->other_url = null;
                break;
            case 'radio':
                $this->deleteFile($slider->video);
                $slider->video = null;
                $slider->youtube_url = null;
                $slider->radio_url = $request->radio_url;
                $slider->other_url = null;
                break;
            case 'other':
                $this->deleteFile($slider->video);
                $slider->video = null;
                $slider->youtube_url = null;
                $slider->radio_url = null;
                $slider->other_url = $request->other_url;
                break;
        }

        $slider->save();

        return redirect('admin/sliders')->with("success", "Slider successfully updated");
    }

    public function delete($id)
    {
        if (is_null($this->user) || !$this->user->can('slider.delete')) {
            return back()->with('error', 'Access Denied: You do not have permission to delete slider.');
        }

        $slider = Slider::find($id);
        if (!$slider) {
            return redirect()->back()->with('error', 'Slider not found.');
        }

        $this->deleteFile($slider->thumbnail_image);
        $this->deleteFile($slider->video);

        $slider->delete();

        return redirect()->back()->with(['success' => 'Slider successfully deleted']);
    }
    

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

    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;
    }

    
}
