<?php

namespace App\Http\Controllers;

use App\AccountsPermissions;
use App\ControlAccount;
use App\MainAccount;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
use File;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use App\role_permission;
use App\SubControlAccount;
use App\TransactionAccount;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class PermissionController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    protected $role_id;
    // public function __construct()
    // {
    //     $this->middleware('auth');
    //     $this->middleware(function ($request, $next) {
    //         $this->role_id = Auth::user()->role_id;
    //         //    $slug_filter = preg_replace('/[0-9]+/', '', $request->path());
    //         //    $slug_filter = preg_replace('/[0-9]+/', '', $request->path());
    //         $ex = explode('/', $request->path());
    //         if (count($ex) >= 3) {
    //             $sliced = array_slice($ex, 0, -1);
    //         } else {
    //             $sliced = $ex;
    //         }

    //         $string = implode("/", $sliced);
    //         //                 dd($string);
    //         if (checkConstructor($this->role_id, count($ex) >= 3 ? $string . '/' : $string) == 1) {
    //             return $next($request);
    //         } else if (strpos($request->path(), 'store') !== false) {
    //             return $next($request);
    //         } else if (strpos($request->path(), 'update') !== false) {
    //             return $next($request);
    //         } else {
    //             abort(404);
    //         }
    //     });
    // }

    // public function index()
    // {
    //     $title = 'Permission';
    //     $menu = 'permission';
    //     $submenu = 'permission';
    //     $page = 'list';
    //     $roles = DB::table('roles')->get()->toArray();

    //     $permission = DB::table('role_permission')->where('role_id', request('id'))->pluck('menu_id')->toArray();

    //     $role_id = request('id') > 0 ? request('id') : 0;

    //     return view('Permission.index')->with(compact('title', 'menu','submenu', 'page', 'roles','role_id', 'permission'));
    // }

    public function index(Request $request)
    {
        $roles = Role::all();
        $role_id = $request->id ?? 0;

        $permissions = Permission::all();

        $accountPermissions = AccountsPermissions::where('role_id', $role_id)->get();

        $mainAccounts = MainAccount::with(['controlAccounts.subControlAccounts.transactionAccounts'])->get();


        $assigned_permissions = $role_id ? Role::find($role_id)->permissions->pluck('id')->toArray() : [];

        return view('Permission.index', compact('mainAccounts', 'accountPermissions', 'roles', 'role_id', 'permissions', 'assigned_permissions', 'mainAccounts'));
    }

    public function toggleTransactionAccountStatus(Request $request)
    {
        $transactionAccount = TransactionAccount::find($request->id);
        $transactionAccount->status = $request->status; // Assuming you have a 'status' column
        $transactionAccount->save();

        return response()->json(['message' => 'Status updated successfully']);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $title = 'Roles';

        $menu = 'role';
        $submenu = 'role';
        $page = 'add';

        return view('Roles.create')->with(compact('title', 'menu', 'submenu', 'page'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    // public function store(Request $request)
    // {
    //     //echo "<pre>";
    //     DB::table('role_permission')->where('role_id', request('id'))->delete();
    //     if ($request->menu_id) {
    //         for ($i = 0; $i < count($request->menu_id); $i++) {
    //             DB::table('role_permission')
    //             ->insert(['role_id' => request('id'), 'menu_id' => $request->menu_id[$i]]);
    //         }
    //     }
    //     // dd($request);exit;
    //     return back();
    // }

    public function store(Request $request, $role_id)
    {
        // Validate the request
        $validated = $request->validate([
            'permissions' => 'array',
            'permissions.*' => 'integer|exists:permissions,id',
        ]);

        $role = Role::find($role_id);

        if ($role) {
            // Sync the role's permissions with the selected permissions
            $role->syncPermissions($validated['permissions']);

            // Return success response
            return redirect()->back()->with('alert', 'Permissions updated successfully')->with('alert-class', 'success');
        }
        // dd($role);exit;

        // Handle case where role is not found
        return redirect()->back()->with('alert', 'Role not found')->with('alert-class', 'danger');
    }

    public function accstore(Request $request, $role_id)
    {
        // Validate only the accounts array; other fields are not required at this level.
        $validated = $request->validate([
            'accounts' => 'nullable|array'
        ]);

        // Find the role by its ID
        $role = Role::find($role_id);
        if (!$role) {
            return redirect()->back()->with('alert', 'Role not found')->with('alert-class', 'danger');
        }

        $permissionsToSave = [];

        if (isset($validated['accounts'])) {
            foreach ($validated['accounts'] as $account) {
                $mainAccountId = $account['mainaccount_id'] ?? null;
                $controlAccountId = $account['conaccount_id'] ?? null;
                $subControlAccountId = $account['subaccount_id'] ?? null;
                $transactionAccountId = $account['transaccount_id'] ?? null;

                // Prepare each account type for saving
                if ($mainAccountId) {
                    $mainAccount = MainAccount::find($mainAccountId);
                    if ($mainAccount) {
                        $permissionsToSave[] = [
                            'role_id' => $role_id,
                            'main_account_id' => $mainAccount->id_main_account,
                            'control_account_id' => null,
                            'sub_control_account_id' => null,
                            'transaction_account_id' => null,
                            'account_name' => $mainAccount->main_account_name,
                            'account_type' => 'MainAccount'
                        ];
                    }
                }
                if ($controlAccountId) {
                    $controlAccount = ControlAccount::find($controlAccountId);
                    if ($controlAccount) {
                        $permissionsToSave[] = [
                            'role_id' => $role_id,
                            'main_account_id' => null,
                            'control_account_id' => $controlAccount->id_control_account,
                            'sub_control_account_id' => null,
                            'transaction_account_id' => null,
                            'account_name' => $controlAccount->control_account_name,
                            'account_type' => 'ControlAccount'
                        ];
                    }
                }
                if ($subControlAccountId) {
                    $subControlAccount = SubControlAccount::find($subControlAccountId);
                    if ($subControlAccount) {
                        $permissionsToSave[] = [
                            'role_id' => $role_id,
                            'main_account_id' => null,
                            'control_account_id' => null,
                            'sub_control_account_id' => $subControlAccount->id_sub_control_account,
                            'transaction_account_id' => null,
                            'account_name' => $subControlAccount->sub_control_account_name,
                            'account_type' => 'SubControlAccount'
                        ];
                    }
                }
                if ($transactionAccountId) {
                    $transactionAccount = TransactionAccount::find($transactionAccountId);
                    if ($transactionAccount) {
                        $permissionsToSave[] = [
                            'role_id' => $role_id,
                            'main_account_id' => null,
                            'control_account_id' => null,
                            'sub_control_account_id' => null,
                            'transaction_account_id' => $transactionAccount->id_transaction_account,
                            'account_name' => $transactionAccount->transaction_account_name,
                            'account_type' => 'TransactionAccount'
                        ];
                    }
                }
            }
        }

        // Delete existing permissions for the role before adding new ones
        AccountsPermissions::where('role_id', $role_id)->delete();

        // Insert new permissions if available
        if (!empty($permissionsToSave)) {
            AccountsPermissions::insert($permissionsToSave);
            return redirect()->back()->with('alert', 'Permissions updated successfully')->with('alert-class', 'success');
        }

        return redirect()->back()->with('alert', 'No permissions were updated')->with('alert-class', 'warning');
    }




    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $title = 'Roles';
        $menu = 'role';
        $submenu = 'role';
        $page = 'edit';
        $role = DB::table('roles')->where('id_roles', $id)->first();

        return view('Roles.edit')->with(compact('title', 'menu', 'submenu', 'page', 'role'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'role' => 'required',
        ]);

        DB::table('roles')->where('id_roles', $id)->update(['role' => $request->role, 'updated_at' => date('Y-m-d H:i:s')]);

        return redirect(url('roles'));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $role = DB::table('roles')->where('id_roles', $request->id)->delete();
        Session::flash('message', 'Role has been deleted');
        return back();
    }
}
