<?php

namespace App\Http\Controllers\RolePermission;

use App\Http\Controllers\Controller;
use App\Models\RolePermission\PermissionCategory;
use App\Models\RolePermission\PermissionLog;
use App\Models\RolePermission\PermissionSubCategory;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Spatie\Permission\Models\Permission;

class PermissionController extends Controller
{
    public function index()
    {
        $permissions = Permission::orderBy('id', 'DESC')->get();
        return view('role-permission.permission.index', compact('permissions'));
    }

    public function create()
    {
        $permissionCategory = PermissionCategory::pluck('name', 'slug');
        return view('role-permission.permission.create', compact('permissionCategory'));
    }

    public function store(Request $request)
    {
        if ($request->submit == 'all') {
            $request->validate([
                'name' => ['required', 'string'],
                'subname' => ['required', 'string']
            ]);
        }else{
            $request->validate([
                'name' => ['required', 'string'],
                // 'action_name' => ['required', 'string'],
            ]);
        }

        // Permission::create([
        //     'name' => $full_name,
        //     'display_name' => $request->display_name,
        // ]);

        $duplicate = []; $success = [];

        $action_array = ['view', 'create', 'edit', 'delete'];

        if ($request->submit == 'single') {

            $full_name = $request->name;

            if ($request->subname) {
                $full_name .= '.' . $request->subname;
            }

            if ($request->action_name) {
                $full_name .= '.' . $request->action_name;
            }
            $check_exist = Permission::where('name', '=', $full_name)->first();

            if ($check_exist) {
                return redirect()->back()->with('warning', "Can't create this category. Because its already exist.");
            }

            $lastPermission = Permission::orderBy('id', 'DESC')->first();
            $newID = $lastPermission->id + 1;

            $newOrders = 0;
            $lastPermissionCat = PermissionCategory::orderBy('id', 'DESC')->first();
            $checkOrder = PermissionCategory::where('name', '=', "$request->name")->first();

            if ($checkOrder) {
                $newOrders = $checkOrder->orders;
            } else {
                $newOrders = $lastPermissionCat->orders + 1;
            }

            $now = now();
            $query = "INSERT INTO permissions (id, name, guard_name, display_name, orders, created_at, updated_at)
                    VALUES ('$newID', '$full_name', 'web','$request->display_name', '$newOrders', '$now', '$now')";
            DB::insert($query);
            PermissionLog::create(['sql_log' => $query]);

        } elseif ($request->submit == 'all') {

            foreach ($action_array as $action) {

                $full_name = $request->name;

                if ($request->subname) {
                    $full_name .= '.' . $request->subname;
                }


                $full_name .= '.' . $action;

                $display_name = ucfirst($action).' '.ucwords(str_replace('-', ' ',$request->subname));

                $check_exist = Permission::where('name', '=', $full_name)->first();

                if ($check_exist) {
                    array_push($duplicate,  $action);

                }else{
                    array_push($success,  $action);
                    $lastPermission = Permission::orderBy('id', 'DESC')->first();
                    $newID = $lastPermission->id + 1;

                    $newOrders = 0;
                    $lastPermissionCat = PermissionCategory::orderBy('id', 'DESC')->first();
                    $checkOrder = PermissionCategory::where('name', '=', "$request->name")->first();

                    if ($checkOrder) {
                        $newOrders = $checkOrder->orders;
                    } else {
                        $newOrders = $lastPermissionCat->orders + 1;
                    }

                    $now = now();
                    $query = "INSERT INTO permissions (id, name, guard_name, display_name, orders, created_at, updated_at)
                            VALUES ('$newID', '$full_name', 'web','$display_name', '$newOrders', '$now', '$now')";
                    DB::insert($query);
                    PermissionLog::create(['sql_log' => $query]);
                }

            }
        }

        $duplicate_str = implode(', ', $duplicate);
        $success_str = implode(', ', $success);

        if (!empty($success_str) && empty($duplicate_str)) {
            return redirect('permissions')->with('success', "Permission ($success_str) Created Successfully.");
        }

        if (empty($success_str) && !empty($duplicate_str)) {
            return redirect('permissions')->with('warning', "And $duplicate_str are already exixt.");
        }

        if (!empty($success_str) && !empty($duplicate_str)) {
            return redirect('permissions')->with('success', "Permission ($success_str) Created Successfully.")->with('warning', "And $duplicate_str are already exixt.");
        }

    }

    public function show()
    {
    }

    public function edit($id)
    {
        $permission = Permission::findById($id);
        $permissionCategories = PermissionCategory::pluck('name', 'slug');
        $nameParts = explode('.', $permission->name);
        $selectedCategory = $nameParts[0] ?? '';
        $selectedSubCategory = $nameParts[1] ?? '';
        $selectedAction = $nameParts[2] ?? '';
        return view('role-permission.permission.edit', compact('permission', 'permissionCategories', 'selectedCategory', 'selectedSubCategory', 'selectedAction'));
    }

    public function update(Request $request, Permission $permission)
    {
        $request->validate([
            'name' => ['required', 'string'],
            'display_name' => ['required', 'string']
        ]);

        $full_name = $request->name;

        if ($request->subname) {
            $full_name .= '.' . $request->subname;
        }

        if ($request->action_name) {
            $full_name .= '.' . $request->action_name;
        }

        $check_exist = Permission::where('name', '=', $full_name)->whereNot('id', $permission->id)->first();

        if($check_exist){
            return redirect()->back()->with('warning', "Can't edit this category. Because its already exist.");
        }

        $permission->update([
            'name' => $full_name,
            'display_name' => $request->display_name,
        ]);

        return redirect('permissions')->with('success', 'Permission Updated Successfully.');
    }

    public function destroy(Permission $permission)
    {
        $permission->delete();
        return redirect('permissions')->with('warning', 'Permission Deleted Successfully.');
    }

    public function userList(){
        $permissions = Permission::get();
        $user_list = User::with('branch')->whereNot('user_type', 'student')->get();
        return view('role-permission.users.index', compact('permissions', 'user_list'));
    }


    public function sqlLogList(Request $request)
    {
        $permissionLog = PermissionLog::all();
        return view('role-permission.sql-log.index', compact('permissionLog'));
    }
}
