<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend;

use App\Http\Controllers\Controller;
use App\Http\Requests\AdminRequest;
use App\Models\Admin;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use App\Helpers\NextcloudHelper;
use App\Models\FormUpCountry;
use App\Models\FormEntertaimentPresentation;
use App\Models\FormVehicleRunningCost;
use App\Models\FormOthers;
use App\Models\FormMeetingSeminar;
use App\Models\UserHasCabang;
use App\Models\Cabang;
use App\Helpers\AuditTrailHelper;
use App\Models\Region;

class AdminsController extends Controller
{
    
    public function index(): Renderable
    {
        $this->checkAuthorization(auth()->user(), ['admin.view']);
        session()->put('redirect_url', route('admin.admins.index'));

        $pageInfo = [
            'title' => 'User Access List',
            'sub_title' => 'List User Access System',
            'path' => url()->current()
        ];

        $admins = Admin::with(['region', 'cabang', 'roles', 'getRayon', 'getRegion'])->get();
        return view('backend.pages.admins.index', [
            'admins' => $admins,
            'pageInfo' => $pageInfo,
        ]);
    }

    public function create(): Renderable
    {
        $this->checkAuthorization(auth()->user(), ['admin.create']);

        $pageInfo = [
            'title' => 'Create User Access',
            'sub_title' => 'Create new User',
            'path' => url()->current()
        ];

        return view('backend.pages.admins.create', [
            'roles' => Role::all(),
            'pageInfo' => $pageInfo,
            'regions' => Region::all(),
        ]);
    }

    public function store(AdminRequest $request): RedirectResponse
    {
        $this->checkAuthorization(auth()->user(), ['admin.create']);

        $admin = Admin::create([
            'name' => $request->name,
            'password' => Hash::make($request->password),
            'username' => $request->username,
            'email' => $request->email,
            'phone' => $request->phone,
            'region_id' => $request->region_id ? $request->region_id : null,
            'rayon_id' => $request->rayon_id ? $request->rayon_id : null,
        ])->assignRole($request->roles);

        if($request->cabang_id) {
            UserHasCabang::create([
                'user_id' => $admin->id,
                'cabang_id' => $request->cabang_id
            ]);
        }

        AuditTrailHelper::AddAuditTrail('Insert', 'Added New User (' . $request->email . ') to the User Table');
        session()->flash('success', 'Admin has been created.');
        return redirect()->back();
    }

    public function edit(int $id): Renderable
    {
        $this->checkAuthorization(auth()->user(), ['admin.edit']);

        $pageInfo = [
            'title' => 'Edit User Access',
            'sub_title' => 'Update User Access data',
            'path' => url()->current()
        ];


        $admin = Admin::findOrFail($id);
        $admin->cabang_id = $admin->getMyCabangAndRegionId()['cabang'];

        return view('backend.pages.admins.edit', [
            'admin' => $admin,
            'roles' => Role::all(),
            'pageInfo' => $pageInfo,
            'regions' => Region::all(),
        ]);
    }

    public function update(AdminRequest $request, int $id): RedirectResponse
    {
        $this->checkAuthorization(auth()->user(), ['admin.edit']);
        $admin = Admin::findOrFail($id);
        $admin->update([
            'name' => $request->name,
            'email' => $request->email,
            'username' => $request->username,
            'phone' => $request->phone,
            'region_id' => $request->region_id ? $request->region_id : null,
            'rayon_id' => $request->rayon_id ? $request->rayon_id : null,
        ]);

        $admin->roles()->detach();
        if ($request->roles) {
            $admin->assignRole($request->roles);
        }

        if ($request->password) {
            $admin->password = Hash::make($request->password);
            $admin->save();
        }

        // Update the user's cabang
        if($request->cabang_id) {
            $userHasCabang = UserHasCabang::where('user_id', $admin->id)->first();
            $userHasCabang ? $userHasCabang->update(['cabang_id' => $request->cabang_id]) : UserHasCabang::create(['user_id' => $admin->id, 'cabang_id' => $request->cabang_id]);
        } else {
            UserHasCabang::where('user_id', $admin->id)->delete();
        }

        AuditTrailHelper::AddAuditTrail('Update', 'Update User Data (' . $request->email . ') in the User Table');
        session()->flash('success', 'Admin has been updated.');
        return redirect()->back();
    }

    public function expense($user_id)
    {
        $formUpCountry = FormUpCountry::where('user_id', $user_id)->get();
        $formEntertaimentPresentation = FormEntertaimentPresentation::where('user_id', $user_id)->get();
        $formVehicleRunningCost = FormVehicleRunningCost::where('user_id', $user_id)->get();
        $formOthers = FormOthers::where('user_id', $user_id)->get();
        $formMeetingSeminar = FormMeetingSeminar::where('user_id', $user_id)->get();

        // Combine all forms into a single array with keys for each form type
        $forms = [
            'form_up_country' => $formUpCountry,
            'form_entertainment_presentation' => $formEntertaimentPresentation,
            'form_vehicle_running_cost' => $formVehicleRunningCost,
            'form_others' => $formOthers,
            'form_meeting_seminar' => $formMeetingSeminar,
        ];

        session()->put('redirect_url', route('admin.admins.expense', $user_id));

        // Pass the forms and page information to the view
        return view('backend.pages.admins.expense', [
            'pageInfo' => [
                'title' => 'Form Management',
            ],
            'forms' => $forms,
        ]);
    }


    public function destroy(int $id): RedirectResponse
    {
        $this->checkAuthorization(auth()->user(), ['admin.delete']);

        $admin = Admin::findOrFail($id);
        AuditTrailHelper::AddAuditTrail('Delete', 'Deleted User (' . $admin->email . ') from the User Table');

        $admin->delete();

        session()->flash('success', 'Admin has been deleted.');
        return redirect()->back();
    }
}