<?php

namespace App\Http\Controllers;

use App\Models\MenuModel;
use App\Models\RightsDetailModel;
use App\Models\RightsModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class RightsController extends Controller
{

    public function index()
    {
        if (Auth::user()->user_flg == 'SU') {
            $staffs = User::whereIn('user_flg', ["S", "A"])
                ->where('branch_id', session('branch_id'))->orderBy('id', 'desc')
                ->get();
        } else if (Auth::user()->user_flg == 'A') {
            $staffs = User::where('user_flg', 'S')
                ->where('branch_id', session('branch_id'))->orderBy('id', 'desc')
                ->get();
        }

        $all_staffs = User::where('user_flg', 'S')
            ->where('branch_id', session('branch_id'))->orderBy('id', 'desc')
            ->get();

        $menuItems = MenuModel::where('oprntl_flag', 'A')->get();
        $modules = [];
        foreach ($menuItems as $item) {
            $modules[$item->name] = false;
        }

        return view('rights.index', compact('staffs', 'all_staffs', 'modules'));
    }

    public function edit($id)
    {
        $staff = User::findOrFail($id);
        $menuItems = MenuModel::where('oprntl_flag', 'A')->get();

        $modules = [];
        $assignedModules = [];

        foreach ($menuItems as $item) {
            $modules[$item->name] = false;
        }

        if ($staff->rights_id) {
            $menus = RightsDetailModel::with('menu')->where('rights_id', $staff->rights_id)->get();

            foreach ($menus as $item) {
                if (array_key_exists($item->menu->name, $modules)) {
                    $assignedModules[$item->menu->name] = true;
                }
            }
        }

        return view('rights.edit', compact('staff', 'modules', 'assignedModules'));
    }

    public function getModalData($staff_id, $rights_sid = null)
    {
        $menuItems = MenuModel::where('oprntl_flag', 'A')->get();
        $modules = [];
        foreach ($menuItems as $item) {
            $modules[$item->name] = false;
        }

        if ($rights_sid) {
            $menus = RightsDetailModel::with('menu')->where('rights_id', $rights_sid)->get();

            foreach ($menus as $items) {
                if (array_key_exists($items->menu->name, $modules)) {
                    $modules[$items->menu->name] = true;
                }
            }

            return response()->json([
                'rights_edit' => true,
                'rights_id' => $rights_sid,
                'modules' => $modules
            ]);
        } else {
            return response()->json([
                'rights_edit' => false,
                'modules' => $modules
            ]);
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'modules' => 'required|array',
            'id' => 'required|exists:users,id'
        ]);
    
        DB::beginTransaction();
        try {
            $menus = DB::table('menu')->get();
            $screen_ids = [];

            foreach ($request->modules as $index => $module) {
                if (!$module)
                    continue;
                if ($menu = $menus->firstWhere('name', $index)) {
                    $screen_ids[] = $menu->id;
                }
            }

            $user = User::findOrFail($request->id);

            if ($user->rights_id) {

                $rights_id = $user->rights_id;
                RightsDetailModel::where('rights_id', $rights_id)->delete();
                $message = 'Rights updated successfully!';
            } else {
                $rights_type = '';
                if ($user->user_flg == 'A') {
                    $rights_type = 'admin';
                } elseif ($user->user_flg == 'S') {
                    $rights_type = 'staff';
                }

                $rights = RightsModel::create(['rights_type' => $rights_type, 'created_by' => Auth::id()]);
                $rights_id = $rights->id;
                $user->rights_id = $rights_id;
                $user->save();
                $message = 'Rights added successfully!';
            }

            foreach ($screen_ids as $menu_id) {
                RightsDetailModel::create([
                    'rights_id' => $rights_id,
                    'menu_id' => $menu_id,
                ]);
            }

            DB::commit();
            return redirect()->route('rights-index')->with('success', $message);
        } catch (\Exception $e) {
            DB::rollBack();
            Log::info('while Updating Roghts' . $e);
            return redirect()->back()->with('error', 'Something went wrong! Please try again');
        }
    }
}