<?php

namespace App\Http\Controllers\Admin;

use App\Models\Role;
use App\Models\User;
use App\Models\Department;
use App\Models\ServiceName;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use App\Models\ApprovalRequestHierarchy;
use App\Http\Controllers\Admin\Controller;
use App\Http\Requests\Admin\StoreApprovalRequestHierarchiesRequest;
use App\Http\Requests\Admin\UpdateApprovalRequestHierarchiesRequest;

class ApprovalRequestHierarchiesController extends Controller
{

    public function __construct()
    {
        $this->middleware('permission:approval-request-hierarchies.view')->only('index');
        $this->middleware('permission:approval-request-hierarchies.create')->only('store');
        $this->middleware('permission:approval-request-hierarchies.edit')->only(['edit','update']);
        $this->middleware('permission:approval-request-hierarchies.delete')->only('destroy');
    }
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $approval_request_hierarchies = ApprovalRequestHierarchy::latest()->get();
        $departments = Department::all();

        $designations = [];
        $services = ServiceName::whereDoesntHave('hierarchy')->orderBy('service_name')->get();


        return view('admin.approval_request_hierarchies')->with(
            [
                'approval_request_hierarchies' => $approval_request_hierarchies,
                'departments' => $departments,
                'designations' => $designations,
                'services' => $services
            ]
        );
    }


    public function store(StoreApprovalRequestHierarchiesRequest $request)
    {

        try
        {
            DB::beginTransaction();
            $input = $request->validated();
            $fillableFields = (new ApprovalRequestHierarchy)->getFillable();
            ApprovalRequestHierarchy::create(Arr::only($input, $fillableFields));
            DB::commit();

            return response()->json(['success'=> 'Approval Request Hierarchy created successfully!']);
        }
        catch(\Exception $e)
        {
            return $this->respondWithAjax($e, 'creating', 'Leave');
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {

    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(ApprovalRequestHierarchy $approvalRequestHierarchy)
    {
        $departments = Department::all();
        $services = ServiceName::all();

        // Fetch all department-wise roles (designations)
        $departmentRoles = [];
        foreach($departments as $dept){
            $users = User::whereHas('departmentUsers', function($q) use ($dept){
                $q->where('department_id', $dept->id);
            })->with('roles')->get();

            $roles = collect();
            foreach($users as $user){
                $roles = $roles->merge($user->roles);
            }
            $departmentRoles[$dept->id] = $roles->unique('name')->values();
        }

        return response()->json([
            'approvalRequestHierarchy' => $approvalRequestHierarchy,
            'departments' => $departments,
            'services' => [$approvalRequestHierarchy->requestserviceName],
            'departmentRoles' => $departmentRoles
        ]);
    }


    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateApprovalRequestHierarchiesRequest $request, ApprovalRequestHierarchy $approvalRequestHierarchy)
    {
        try
        {
            DB::beginTransaction();
            $input = $request->validated();
            $fillableFields = (new ApprovalRequestHierarchy)->getFillable();
            $approvalRequestHierarchy->update( Arr::only( $input,$fillableFields));
            DB::commit();
            return response()->json(['success'=> 'Approval Request Hierarchy updated successfully!']);
        }
        catch(\Exception $e)
        {
            return $this->respondWithAjax($e, 'updating', 'Leave');
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(ApprovalRequestHierarchy $approvalRequestHierarchy)
    {
        try
        {
            DB::beginTransaction();
            $approvalRequestHierarchy->delete();
            DB::commit();
            return response()->json(['success'=> 'Leave Request Hierarchy deleted successfully!']);
        }
        catch(\Exception $e)
        {
            return $this->respondWithAjax($e, 'deleting', 'Leave');
        }
    }

    public function getDesignations($department_id)
    {
        $users = User::whereHas('departmentUsers', function($q) use ($department_id) {
            $q->where('department_id', $department_id);
        })->with('roles')->get();
        $roles = collect();
        foreach ($users as $user) {
            $roles = $roles->merge($user->roles);
        }
        $uniqueRoles = $roles->unique('name')->values();
        return response()->json($uniqueRoles);
    }


}
