<?php

namespace App\Http\Controllers;

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

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

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

    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')->where('rateable_type', Club::class)->whereIn('rateable_id', $user_clubs);
            }

            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('user_name', function ($row) {
                    return $row->user->name;
                })

                ->addColumn('rating', function ($row) {
                    return $row->rating;
                })
                ->rawColumns(['action', 'user_name', 'rating'])
                ->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',
                'day'       => 'required|string|max:255',
                'review_date' => 'required|date_format:Y-m-d', // Adjust format as needed
                'start_time' => 'required|date_format:H:i', // Adjust format as needed
                'end_time'   => 'required|date_format:H:i', // Adjust format as needed
            ]);

            $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::id();
            $validatedData['status'] = 'accepted';

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

            return redirect()->route('reviews.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')) {

            $validatedData = $request->validate([
                'club_id'       => 'required',
                'day'       => 'required|string|max:255',
                'review_date' => 'required|date_format:Y-m-d', // Adjust format as needed
                'start_time' => 'required|date_format:H:i', // Adjust format as needed
                'end_time'   => 'required|date_format:H:i', // Adjust format as needed
                'status'   => 'required|string',
            ]);


            // 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::id();

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

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

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

        if (auth()->user()->hasRole('club')) {
            $this->data['clubs'] = auth()->user()->clubs;
            if (!$this->data['review'] || $this->data['review']->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;
        $this->data['statuses'] = $this->module::STATUS;
        return view($this->data['view_directory'] . '.' . __FUNCTION__, $this->data);
    }

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

        $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 == 'accepted' ? 'cancelled' : 'accepted';
        $record->save();

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

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

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

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

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