<?php

namespace App\Http\Controllers\SaasAdmin;

use App\Http\Controllers\Controller;
use App\Models\Company;
use App\Models\User;
use App\Repositories\UserRepository;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

/**
 * Lets the root admin manage a company's own admin logins without ever
 * needing that company's password — add another admin, reset one's
 * password directly, or deactivate one. Reachable only from the SaaS
 * control panel (saas.root middleware), always scoped to the one
 * $company the URL names, never the currently-resolved tenant (there
 * isn't one — this runs on the root domain).
 */
class CompanyUserController extends Controller
{
    public function store(Request $request, Company $company): RedirectResponse
    {
        $validated = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'string', 'min:8'],
        ]);

        $admin = UserRepository::create([
            'company_id' => $company->id,
            'name' => $validated['name'],
            'email' => $validated['email'],
            'phone' => '011' . random_int(100000000, 999999999),
            'password' => Hash::make($validated['password']),
            'is_active' => true,
            'is_admin' => true,
            'email_verified_at' => now(),
        ]);
        $admin->assignRole('admin');

        return back()->with('success', __(':name added as an admin for :company.', ['name' => $admin->name, 'company' => $company->name]));
    }

    public function resetPassword(Request $request, Company $company, int $user): RedirectResponse
    {
        $target = $this->ownedUser($company, $user);

        $validated = $request->validate([
            'password' => ['required', 'string', 'min:8'],
        ]);

        $target->update(['password' => Hash::make($validated['password'])]);

        return back()->with('success', __('Password updated for :name.', ['name' => $target->name]));
    }

    public function toggleActive(Company $company, int $user): RedirectResponse
    {
        $target = $this->ownedUser($company, $user);

        if ($target->id === $company->owner_user_id) {
            return back()->with('error', __("Can't deactivate :name — they're this company's original owner account.", ['name' => $target->name]));
        }

        if ($target->trashed()) {
            $target->restore();
            $message = __(':name reactivated.', ['name' => $target->name]);
        } else {
            $target->delete();
            $message = __(':name deactivated.', ['name' => $target->name]);
        }

        return back()->with('success', $message);
    }

    /**
     * Raw-ID lookup rather than route-model binding on purpose: a
     * deactivated admin is soft-deleted, and implicit binding excludes
     * trashed rows by default — reactivating one would 404 before this
     * method ever ran. The ownership check is what actually matters here:
     * without it, the URL alone would let the root admin's own session
     * touch a user row under the wrong company if the {company} and
     * {user} in the URL ever disagreed.
     */
    private function ownedUser(Company $company, int $userId): User
    {
        $user = User::withTrashed()->findOrFail($userId);

        abort_unless($user->company_id === $company->id, 404);

        return $user;
    }
}
