<?php

namespace App\Http\Controllers\Admin;

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

class TvController 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: You do not have permission to view tv list.');
        }

        $headerTitle = 'TV List';

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

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

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

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

        $data['headerTitle'] = 'Add New TV';
        $data['categories'] = TvCategory::all();

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

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

        $rules = [
            'title' => 'required|string|max:255',
            'tv_category_id' => 'required|exists:tv_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 = [
            'tv_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/tv/images/');

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

        $tv = new Tv;
        $tv->title = $request->title;
        $tv->tv_category_id = $request->tv_category_id;
        $tv->thumbnail_image = $thumbnailImageURL;
        $tv->video_type = $request->video_type;
        $tv->description = $request->description;

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

        $tv->save();

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

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

        $data['tv'] = Tv::find($id);

        if(!empty($data['tv'])) {
            $data['headerTitle'] = 'Edit TV';
            $data['categories'] = TvCategory::all();

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

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

        $tv = Tv::find($request->tv_id);
        if (!$tv) {
            return redirect()->back()->with('error', 'TV not found.');
        }

        $rules = [
            'title' => 'required|string|max:255',
            'tv_category_id' => 'required|exists:tv_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($tv->thumbnail_image);

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

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

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

        $tv->title = $request->title;
        $tv->tv_category_id = $request->tv_category_id;
        $tv->video_type = $request->video_type;
        $tv->description = $request->description;
        $tv->status = $request->status;

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

        $tv->save();

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

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

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

        $this->deleteFile($tv->thumbnail_image);
        $this->deleteFile($tv->video);
 
        $tv->delete();

        return redirect()->back()->with(['success' => 'TV 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;
    }
}
