<?php

namespace App\Http\Controllers;

use App\Models\Club;
use App\Models\Tournament;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Yajra\DataTables\Facades\DataTables;

class TournamentController extends Controller
{
    protected $module, $data = [];

    public function __construct()
    {
        $this->module = new Tournament();
        $this->data['module_name'] = 'Tournament';
        $this->data['view_directory'] = 'pages.tournament';
        $this->data['parent_named_route'] = 'tournaments';
    }

    public function index(Request $request)
    {
        if ($request->ajax()) {

            if (auth()->user()->hasRole('club')) {
                $user_clubs = auth()->user()->clubs->pluck('id');
                $data = $this->module::with('user', 'club')->whereIn('club_id', $user_clubs);
            } else {
                $data = $this->module::with('user', 'club');
            }

            return DataTables::of($data)
                ->addIndexColumn()
                ->addColumn('sno', function ($row) {
                    static $index = 0; // Static variable to keep track of the index
                    $page = request()->get('start', 0); // Get the start parameter
                    $index++;
                    return $page + $index;
                })
                ->addColumn('action', function ($row) {

                    $view = '<a href="' . route($this->data['parent_named_route'] . ".view", ['id' => $row->id]) . '" class="edit btn btn-primary btn-sm btn-equal mb-1">View</a>&nbsp;';
                    $edit = '<a href="' . route($this->data['parent_named_route'] . ".edit", ['id' => $row->id]) . '" class="edit btn btn-primary btn-sm btn-equal mb-1">Edit</a>&nbsp;';

                    // if ($row->status) {
                    //     $status = '<a href="' . route($this->data['parent_named_route'] . ".status", ['id' => $row->id]) . '" class="edit btn btn-danger btn-sm btn-equal mb-1">Deactivate</a>';
                    // } else {
                    //     $status = '<a href="' . route($this->data['parent_named_route'] . ".status", ['id' => $row->id]) . '" class="edit btn btn-success btn-sm btn-equal mb-1">Activate</a>';
                    // }

                    // $delete = '<a href="' . route($this->data['parent_named_route'] . ".delete", ['id' => $row->id]) . '" class="edit btn btn-danger btn-sm btn-equal mb-1">Delete</a>';
                    $delete = '<a href="#" onclick="confirmDelete(\'' . $this->data['parent_named_route'] . '\', ' . $row->id . ')" class="edit btn btn-danger btn-sm btn-equal mb-1">Delete</a>';

                    return $edit . $view . $delete;
                })
                ->addColumn('picture', function ($row) {

                    $picture = '<img src="' . $row->picture . '" class="" width=40px" heigt=40px"/>';

                    return $picture;
                })
                ->addColumn('user_name', function ($row) {
                    return $row->user->name;
                })
                ->addColumn('link', function ($row) {
                    return $row->link
                        ? '<a href="' . $row->link . '" target="_blank" class="edit btn btn-sm btn-equal mb-1">' . $row->link . '</a>'
                        : '<span class="text-muted">No link available</span>';
                })
                ->addColumn('club_name', function ($row) {
                    return $row->club->name;
                })
                ->addColumn('start_date', function ($row) {
                    return customDateFormat($row->start_date);
                })
                ->addColumn('start_time', function ($row) {
                    return customTimeFormat($row->start_time);
                })
                ->addColumn('end_date', function ($row) {
                    return customDateFormat($row->end_date);
                })
                ->addColumn('end_time', function ($row) {
                    return customTimeFormat($row->end_time);
                })
                ->addColumn('status', function ($row) {
                    switch ($row->status) {
                        case 0: // Pending
                            return '<i style="color:orange;" class="menu-icon tf-icons bx bx-time"></i> Pending';
                        case 1: // Active
                            return '<i style="color:green;" class="menu-icon tf-icons bx bx-check"></i> Active';
                        case 2: // Finished
                            return '<i style="color:blue;" class="menu-icon tf-icons bx bx-flag"></i> Finished';
                        default:
                            return '<i style="color:grey;" class="menu-icon tf-icons bx bx-question-mark"></i> Unknown';
                    }
                })

                ->rawColumns(['action', 'status', 'picture', 'user_name', 'club_name', 'link'])
                ->make(true);
        }

        $this->data['page'] =  'List';

        return view($this->data['view_directory'] . '.' . __FUNCTION__, $this->data);
    }

    public function create(Request $request)
    {
        if ($request->isMethod('post')) {
            $validatedData = $request->validate([
                'club_id'       => 'required',
                'name'       => 'required|string|max:255',
                'description'       => 'required|string|max:255',
                'status'       => 'required|string',
                'link'       => 'required|string',
                'picture'    => 'required|image|mimes:jpeg,png,jpg', // Max size 2MB
                'start_date' => 'required|date_format:Y-m-d', // Adjust format as needed
                'end_date'   => 'required|date_format:Y-m-d',
                'start_time' => 'required|date_format:H:i', // Adjust format as needed
                'end_time'   => 'required|date_format:H:i', // Adjust format as needed
            ]);

            // Convert time to H:i:s format
            $validatedData['start_time'] = Carbon::createFromFormat('H:i', $validatedData['start_time'])->format('H:i:s');
            $validatedData['end_time'] = Carbon::createFromFormat('H:i', $validatedData['end_time'])->format('H:i:s');
            $validatedData['user_id'] = auth()->user()->id;

            if ($request->hasFile('picture')) {
                $validatedData['picture'] = $this->media($request, 'tournaments');
            }

            $tournament = $this->module->create($validatedData);

            return redirect()->route('tournaments.index')->with('success', $this->data['module_name'] . ' added successfully');
        }

        $this->data['users'] = User::all();

        if (auth()->user()->hasRole('club')) {
            $this->data['clubs'] = auth()->user()->clubs;
        } else {
            $this->data['clubs'] = Club::all();
        }

        return view($this->data['view_directory'] . '.' . __FUNCTION__, $this->data);
    }

    public function edit(Request $request, $id)
    {
        if ($request->isMethod('post')) {

            $tournament = $this->module::find($id);

            $validatedData = $request->validate([
                'club_id'       => 'required',
                'name'       => 'required|string|max:255',
                'description'       => 'required|string|max:255',
                'status'       => 'required|string',
                'link'       => 'required|string',
                'picture'    => 'nullable|image|mimes:jpeg,png,jpg', // Max size 2MB
                'start_date' => 'required|date_format:Y-m-d', // Adjust format as needed
                'end_date'   => 'required|date_format:Y-m-d',
                'start_time' => 'required|date_format:H:i', // Adjust format as needed
                'end_time'   => 'required|date_format:H:i', // Adjust format as needed
            ]);


            // Convert time to H:i:s format
            $validatedData['start_time'] = Carbon::createFromFormat('H:i', $validatedData['start_time'])->format('H:i:s');
            $validatedData['end_time'] = Carbon::createFromFormat('H:i', $validatedData['end_time'])->format('H:i:s');
            $validatedData['user_id'] = auth()->user()->id;

            if ($request->hasFile('picture')) {
                $validatedData['picture'] = $this->media($request, 'tournaments');
                if ($tournament->picture) {
                    $mediaPath = str_replace(env('UPLOAD_URL'), '', $tournament->picture);
                    if (Storage::disk(env('UPLOADS_DISK'))->exists($mediaPath)) {
                        Storage::disk(env('UPLOADS_DISK'))->delete($mediaPath);
                    }
                }
            }

            $tournament = $this->module->where('id', $id)->update($validatedData);

            return redirect()->route('tournaments.index')->with('success', $this->data['module_name'] . ' updated successfully');
        }

        $this->data['tournament'] = Tournament::find($id);
        $this->data['users'] = User::all();

        if (auth()->user()->hasRole('club')) {
            $this->data['clubs'] = auth()->user()->clubs;
            if (!$this->data['tournament'] || $this->data['tournament']->club->user->id !== auth()->user()->id) {
                abort(403, 'You do not have permission to ' . __FUNCTION__ . ' this ' . $this->data['module_name']);
            }
        } else {
            $this->data['clubs'] = Club::all();
        }

        return view($this->data['view_directory'] . '.' . __FUNCTION__, $this->data);
    }

    public function view(Request $request)
    {
        $this->data['tournament'] = $this->module::with('user', 'club', 'users')->find($request->id);

        if (auth()->user()->hasRole('club')) {
            if (!$this->data['tournament'] || $this->data['tournament']->club->user->id !== auth()->user()->id) {
                abort(403, 'You do not have permission to ' . __FUNCTION__ . ' this ' . $this->data['module_name']);
            }
        }

        $this->data['page'] = __FUNCTION__;

        return view($this->data['view_directory'] . '.' . __FUNCTION__, $this->data);
    }

    public function status($id)
    {
        $record = $this->module::find($id);
        $record->status = $record->status ? '0' : '1';
        $record->save();

        return redirect()->back()->with('success', $this->data['module_name'] . ' status updated successfully');
    }

    public function delete($id)
    {
        $recor = $this->module::find($id);

        if ($recor) {
            $recor->delete();

            return redirect()->back()->with('success', $this->data['module_name'] . ' deleted successfully');
        }

        return redirect()->back()->with('error', $this->data['module_name'] . ' not found');
    }
}
