<?php

namespace App\Http\Controllers;

use App\Models\Club;
use App\Models\WorkingHour;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

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

    public function __construct()
    {
        $this->module = new WorkingHour();
        $this->data['module_name'] = 'Working Hour';
        $this->data['view_directory'] = 'pages.hour';
        $this->data['parent_named_route'] = 'hours';
    }

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

            if (auth()->user()->hasRole('club')) {
                $user_clubs = auth()->user()->clubs->pluck('id');
                $data = $this->module::with('club')->whereIn('club_id', $user_clubs);
            } else {
                $data = $this->module::with('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) {
                    $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;';
                    // $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 . $delete;
                })
                ->addColumn('club_name', function ($row) {
                    return $row->club->name;
                })
                ->addColumn('day', function ($row) {
                    return $this->module::DAYS[$row->day];
                })
                ->addColumn('opening_time', function ($row) {
                    return customTimeFormat($row->opening_time);
                })
                ->addColumn('closing_time', function ($row) {
                    return customTimeFormat($row->closing_time);
                })
                ->rawColumns(['action', 'club_name'])
                ->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|string',
                'day' => 'required|string',
                'opening_time' => 'required|date_format:H:i', // Adjust format as needed
                'closing_time'   => 'required|date_format:H:i', // Adjust format as needed
            ]);

            // Convert time to H:i:s format
            $validatedData['opening_time'] = Carbon::createFromFormat('H:i', $validatedData['opening_time'])->format('H:i:s');
            $validatedData['closing_time'] = Carbon::createFromFormat('H:i', $validatedData['closing_time'])->format('H:i:s');

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

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

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

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

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

            $validatedData = $request->validate([
                'club_id' => 'required|string',
                'day' => 'required|string',
                'opening_time' => 'required|date_format:H:i', // Adjust format as needed
                'closing_time'   => 'required|date_format:H:i', // Adjust format as needed
            ]);

            // Convert time to H:i:s format
            $validatedData['opening_time'] = Carbon::createFromFormat('H:i', $validatedData['opening_time'])->format('H:i:s');
            $validatedData['closing_time'] = Carbon::createFromFormat('H:i', $validatedData['closing_time'])->format('H:i:s');

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

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

        $this->data['hour'] = $this->module::find($id);

        if (auth()->user()->hasRole('club')) {
            $this->data['clubs'] = auth()->user()->clubs;
            if (!$this->data['hour'] || $this->data['hour']->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();
        }

        $this->data['days'] = $this->module::DAYS;

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

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