<?php

namespace App\Controllers\Admin;

use App\Models\Control\AdminUserModel;

/**
 * Manage platform-operator logins. Deliberately no self-service signup
 * (see `php spark admin:create`) — this is the web equivalent, gated
 * behind an existing admin session, the same "you need a trusted account
 * to create the next one" bootstrapping every auth system in this app
 * follows (tenant UserController is manager-gated the same way).
 */
class AdminUserController extends BaseAdminController
{
    public function index()
    {
        return view('admin/admins/index', [
            'pageTitle' => 'Admins & Users',
            'activeNav' => 'admins',
            'admins'    => (new AdminUserModel())->orderBy('full_name', 'asc')->findAll(),
        ]);
    }

    public function new()
    {
        return view('admin/admins/new', [
            'pageTitle' => 'New Admin',
            'activeNav' => 'admins',
        ]);
    }

    public function create()
    {
        $rules = [
            'full_name' => 'required|max_length[150]',
            'email'     => 'required|valid_email|is_unique[admin_users.email]',
            'password'  => 'required|min_length[8]',
        ];

        if (! $this->validate($rules)) {
            return redirect()->back()->withInput()->with('validation', $this->validator);
        }

        $admins = new AdminUserModel();
        $id = $admins->insert([
            'full_name'     => $this->request->getPost('full_name'),
            'email'         => $this->request->getPost('email'),
            'password_hash' => password_hash($this->request->getPost('password'), PASSWORD_DEFAULT),
            'role'          => 'super_admin',
            'is_active'     => 1,
        ], true);

        if ($id === false) {
            return $this->redirectWithModelErrors($admins);
        }

        $this->logAdminActivity('admins', "Created admin login for {$this->request->getPost('email')}.");

        return redirect()->to('/admin/admins')->with('success', 'Admin created.');
    }

    public function toggleActive(int $id)
    {
        $admins = new AdminUserModel();
        $admin  = $admins->find($id);

        if ($admin === null) {
            return redirect()->to('/admin/admins')->with('error', 'Admin not found.');
        }

        if ($admin->id === $this->currentAdminId() && $admin->is_active) {
            return redirect()->to('/admin/admins')->with('error', 'You cannot deactivate your own account.');
        }

        $admins->update($id, ['is_active' => $admin->is_active ? 0 : 1]);

        $this->logAdminActivity('admins', ($admin->is_active ? 'Deactivated' : 'Activated') . " admin {$admin->email}.");

        return redirect()->to('/admin/admins')->with('success', 'Admin updated.');
    }
}
