<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Validation\Rules\Password;

class EmployeeController extends Controller
{
    private function ensureCanManageRole(?string $targetRole = null): void
    {
        $user = auth()->user();
        if (! $user) {
            abort(403);
        }

        if ($targetRole === 'admin' && ! $user->isOwner()) {
            abort(403, 'Only the owner can create or promote admin accounts.');
        }
    }

    public function index()
    {
        $employees = User::whereIn('role', ['admin', 'employee'])
            ->withCount(['leads as total_leads' => fn ($q) => $q->select(\DB::raw('count(*)'))])
            ->orderBy('name')
            ->paginate(20);

        return view('admin.employees.index', compact('employees'));
    }

    public function create()
    {
        return view('admin.employees.create');
    }

    public function store(Request $request)
    {
        $data = $request->validate([
            'name'     => 'required|string|max:150',
            'email'    => 'required|email|unique:users,email',
            'phone'    => 'nullable|string|max:30',
            'role'     => 'required|in:admin,employee',
            'password' => ['required', Password::min(8)],
        ]);

        $this->ensureCanManageRole($data['role']);

        User::create([
            'name'      => $data['name'],
            'email'     => $data['email'],
            'phone'     => $data['phone'] ?? null,
            'role'      => $data['role'],
            'password'  => bcrypt($data['password']),
            'is_active' => true,
        ]);

        return redirect()->route('admin.employees.index')
            ->with('success', "Team member \"{$data['name']}\" created.");
    }

    public function edit(User $employee)
    {
        abort_if($employee->isOwner() && ! auth()->user()->isOwner(), 403);
        return view('admin.employees.edit', compact('employee'));
    }

    public function update(Request $request, User $employee)
    {
        abort_if($employee->isOwner() && ! auth()->user()->isOwner(), 403);

        $data = $request->validate([
            'name'      => 'required|string|max:150',
            'email'     => "required|email|unique:users,email,{$employee->id}",
            'phone'     => 'nullable|string|max:30',
            'role'      => 'required|in:admin,employee',
            'is_active' => 'boolean',
            'password'  => ['nullable', Password::min(8)],
        ]);

        if ($employee->isAdmin() && ! $employee->isEmployee() && ! auth()->user()->isOwner()) {
            abort(403, 'Only the owner can edit admin accounts.');
        }

        $this->ensureCanManageRole($data['role']);

        $update = [
            'name'      => $data['name'],
            'email'     => $data['email'],
            'phone'     => $data['phone'] ?? null,
            'role'      => $data['role'],
            'is_active' => $request->boolean('is_active', true),
        ];

        if (! empty($data['password'])) {
            $update['password'] = bcrypt($data['password']);
        }

        $employee->update($update);

        return redirect()->route('admin.employees.index')
            ->with('success', "Team member \"{$employee->name}\" updated.");
    }

    public function destroy(User $employee)
    {
        abort_if($employee->id === auth()->id(), 403, 'Cannot delete yourself.');
        abort_if($employee->isOwner(), 403, 'Cannot delete the owner account.');

        $employee->update(['is_active' => false]);

        return redirect()->route('admin.employees.index')
            ->with('success', "\"{$employee->name}\" has been deactivated.");
    }
}
