<?php

namespace App\Http\Controllers;

use App\Models\Invitation;
use App\Models\Reservation;
use App\Models\User;
use Illuminate\Http\Request;
use Yajra\DataTables\Facades\DataTables;

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

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

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

            if (auth()->user()->hasRole('club')) {
                $invitation_ids = auth()->user()->clubs->flatMap(function ($club) {
                    return $club->reservations->flatMap(function ($reservation) {
                        return $reservation->invitations->pluck('id');
                    });
                });
                $data = $this->module::with('player')->whereIn('id', $invitation_ids);
            } else {
                $data = $this->module::with('player');
            }

            // $sno = 1;
            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;';

                    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="#" onclick="confirmDelete(\'' . $this->data['parent_named_route'] . '\', ' . $row->id . ')" class="edit btn btn-danger btn-sm btn-equal mb-1">Delete</a>';
                    return $status . $delete . $edit;
                })
                ->addColumn('invited_by', function ($row) {
                    return optional($row->reservation->user)->name;
                })
                ->addColumn('player_name', function ($row) {
                    return $row->player->name;
                })
                ->addColumn('status', function ($row) {
                    return $row->status
                        ? '<i style="color:green;" class="menu-icon tf-icons bx bx-user-check"></i> Active'
                        : '<i style="color:red;" class="menu-icon tf-icons bx bx-user-x"></i> Inactive';
                })
                ->addColumn('created_at', function ($row) {
                    return customDateFormat($row->created_at);
                })
                ->rawColumns(['action', 'player_name', 'status', 'created_at'])
                ->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([
                'reservation_id' => 'required|string',
                'player_id' => 'required|string',
                'status'   => 'required|string',
            ]);

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

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

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

        if (auth()->user()->hasRole('club')) {
            $this->data['reservations'] = auth()->user()->clubs->flatMap(function ($club) {
                return $club->reservations->where('status', 'accepted');
            });
        } else {
            $this->data['reservations'] = Reservation::where('status', 'accepted')->get();
        }

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

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

            $validatedData = $request->validate([
                'reservation_id' => 'required|string',
                'player_id' => 'required|string',
                'status'   => 'required|string',
            ]);

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

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

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

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

        if (auth()->user()->hasRole('club')) {
            $this->data['reservations'] = auth()->user()->clubs->flatMap(function ($club) {
                return $club->reservations->where('status', 'accepted');
            });

            $user = auth()->user();
            if (!$invitation || $invitation->reservation->user_id !== $user->id) {
                abort(403, 'You do not have permission to ' . __FUNCTION__ . ' this ' . $this->data['module_name']);
            }
        } else {
            $this->data['reservations'] = Reservation::where('status', 'accepted')->get();
        }

        $this->data['invitation'] = $invitation;

        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 ? '0' : '1';
        $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');
    }
}
