<?php

namespace App\Http\Controllers;

use App\Models\Club;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Yajra\DataTables\Facades\DataTables;

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

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

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

            if (auth()->user()->hasRole('club')) {
                $data = $this->module::with('user')->where('user_id', auth()->user()->id);
            } else {
                $data = $this->module::with('user');
            }

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

                    return $view . $edit . $status . $delete;
                })
                ->addColumn('logo', function ($row) {
                    return '<img src="' . $row->logo . '" class="" width=40px" heigt=40px"/>';
                })
                ->addColumn('user_name', function ($row) {
                    return $row->user->name;
                })
                ->addColumn('view_courts', function ($row) {
                    if ($row->courts->isNotEmpty()) {
                        return '<a href="' . route('courts.index', ['club_id' => $row->id]) . '">View Courts</a>';
                    }
                    return '<a href="' . route('courts.create') . '">Create Court</a>';
                    // return 'No Court Yet';
                })
                ->addColumn('reviews', function ($row) {
                    return $row->reviews()->count();
                })
                ->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';
                })
                ->rawColumns(['action', 'status', 'logo', 'reviews', 'view_courts'])
                ->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([
                'name'       => 'required|string',
                'logo'       => 'nullable|image|mimes:jpeg,png,jpg',
                'location'       => 'required|string',
                'latitude'       => 'required|string',
                'longitude'       => 'required|string',
                'description'       => 'required|string',
                'total_courts' => 'required|integer',
            ]);

            if ($request->hasFile('logo')) {
                $validatedData['logo'] = $this->uploadLogo($request, 'clubs');
            }
            $validatedData['user_id'] = Auth::id();

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

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

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

            $validatedData = $request->validate([
                'name'       => 'required|string',
                'logo'       => 'nullable|image|mimes:jpeg,png,jpg',
                'location'       => 'required|string',
                'latitude'       => 'required|string',
                'longitude'       => 'required|string',
                'description'       => 'required|string',
                'total_courts' => 'required|integer',
            ]);

            if ($request->hasFile('logo')) {
                $validatedData['logo'] = $this->uploadLogo($request, 'clubs');
                if ($club->logo) {
                    $mediaPath = str_replace(env('UPLOAD_URL'), '', $club->logo);
                    if (Storage::disk(env('UPLOADS_DISK'))->exists($mediaPath)) {
                        Storage::disk(env('UPLOADS_DISK'))->delete($mediaPath);
                    }
                }
            }
            
            $validatedData['amenities'] = $this->extractTagifyValues($request->input('amenities'));
            $validatedData['surfaces']   = $this->extractTagifyValues($request->input('surface'));
            $validatedData['nets']       = $this->extractTagifyValues($request->input('net'));

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

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

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

        if (auth()->user()->hasRole('club')) {

            $user = auth()->user();

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

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

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

    public function view(Request $request)
    {
        $club = $this->module::with('user', 'features', 'tournaments')->find($request->id);

        if (auth()->user()->hasRole('club')) {

            $user = auth()->user();

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

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

        $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();

        if ($record->status) {
            $modelHasRoles = DB::table('model_has_roles')
                ->where('model_id', $record->user_id)
                ->where('model_type', 'App\Models\User')
                ->where('role_id', 4)
                ->first();

            if (!$modelHasRoles) {
                DB::table('model_has_roles')->insert([
                    'model_id' => $record->user_id,
                    'model_type' => 'App\Models\User',
                    'role_id' => 4,
                ]);
            }
        }

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