<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\RoleProfile;
use App\Models\User;
use App\Services\ActivityLogger;
use App\Services\BranchService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class StaffController extends Controller
{
    public function index(BranchService $branches): View
    {
        $branchState = $branches->formState(auth()->user());

        return view('tenant.staff.index', [
            'staff' => User::with('roleProfile')->where('tenant_id', auth()->user()->tenant_id)->where('role', '!=', User::ROLE_CUSTOMER)->latest()->paginate(15),
            'branches' => $branchState['branches'],
            'showBranchField' => $branchState['showBranchField'],
            'defaultBranchId' => $branchState['defaultBranchId'],
            'roleProfiles' => RoleProfile::where('tenant_id', auth()->user()->tenant_id)->where('is_active', true)->orderBy('name')->get(),
            'roles' => collect(User::ROLES)->except([User::ROLE_SUPER_ADMIN, User::ROLE_CUSTOMER]),
        ]);
    }

    public function store(Request $request, BranchService $branches): RedirectResponse
    {
        $tenant = $request->user()->tenant;
        $plan = $tenant->plan;
        $staffCount = User::where('tenant_id', $tenant->id)->where('role', '!=', User::ROLE_CUSTOMER)->count();

        if ($plan && $staffCount >= $plan->staff_limit) {
            return back()->with('warning', 'Your plan staff limit has been reached.');
        }

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'unique:users,email'],
            'phone' => ['nullable', 'string', 'max:50'],
            'branch_id' => [
                'nullable',
                Rule::exists('branches', 'id')
                    ->where('tenant_id', $tenant->id)
                    ->where('is_active', true),
            ],
            'role' => ['required', Rule::in([User::ROLE_TENANT_ADMIN, User::ROLE_MANAGER, User::ROLE_LOAN_OFFICER, User::ROLE_ACCOUNTANT])],
            'role_profile_id' => [
                'nullable',
                Rule::exists('role_profiles', 'id')->where('tenant_id', $tenant->id),
            ],
            'password' => ['required', 'string', 'min:8'],
            'status' => ['required', 'in:active,inactive'],
        ]);
        $validated['role_profile_id'] = $validated['role_profile_id'] ?? null;
        $validated['branch_id'] = $branches->resolveSubmittedBranchId($request);

        $user = User::create($validated + ['tenant_id' => $tenant->id]);
        ActivityLogger::log('staff_created', $user->name.' was added as '.$user->roleLabel().'.', $user);

        return back()->with('status', 'Staff member added.');
    }

    public function update(Request $request, User $staff, BranchService $branches): RedirectResponse
    {
        abort_unless($staff->tenant_id === $request->user()->tenant_id, 404);

        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone' => ['nullable', 'string', 'max:50'],
            'branch_id' => [
                'nullable',
                Rule::exists('branches', 'id')
                    ->where('tenant_id', $request->user()->tenant_id)
                    ->where('is_active', true),
            ],
            'role' => ['required', Rule::in([User::ROLE_TENANT_ADMIN, User::ROLE_MANAGER, User::ROLE_LOAN_OFFICER, User::ROLE_ACCOUNTANT])],
            'role_profile_id' => [
                'nullable',
                Rule::exists('role_profiles', 'id')->where('tenant_id', $request->user()->tenant_id),
            ],
            'status' => ['required', 'in:active,inactive'],
        ]);
        $validated['role_profile_id'] = $validated['role_profile_id'] ?? null;
        $validated['branch_id'] = $branches->resolveSubmittedBranchId($request, $staff->branch_id);

        $staff->update($validated);

        return back()->with('status', 'Staff member updated.');
    }

    public function destroy(User $staff): RedirectResponse
    {
        abort_unless($staff->tenant_id === auth()->user()->tenant_id, 404);
        abort_if($staff->id === auth()->id(), 422, 'You cannot deactivate your own account.');

        $staff->update(['status' => 'inactive']);

        return back()->with('status', 'Staff member deactivated.');
    }
}
