<?php

namespace App\Controllers\Admin;

use App\Models\Control\AdminUserModel;

/**
 * Login/logout for platform operators — completely separate from
 * App\Controllers\AuthController (tenant staff). Session keys are
 * admin*-prefixed on purpose so a super-admin session can never be
 * mistaken for (or accidentally grant) a tenant staff session, and
 * vice versa — see App\Filters\AdminAuth.
 */
class AdminAuthController extends BaseAdminController
{
    public function showLogin()
    {
        if (session('adminIsLoggedIn')) {
            return redirect()->to('/admin');
        }

        return view('admin/auth/login', ['pageTitle' => 'Platform Login']);
    }

    public function attemptLogin()
    {
        $rules = [
            'email'    => 'required|valid_email',
            'password' => 'required',
        ];

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

        $email    = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $admin = (new AdminUserModel())->verifyCredentials($email, $password);

        if ($admin === null) {
            return redirect()->back()->withInput()->with('error', 'Invalid email or password.');
        }

        $session = session();
        $session->regenerate();
        $session->set([
            'adminIsLoggedIn' => true,
            'adminUserId'     => $admin->id,
            'adminUserName'   => $admin->full_name,
            'adminUserEmail'  => $admin->email,
            'adminUserRole'   => $admin->role,
        ]);

        (new AdminUserModel())->touchLastLogin($admin->id);

        $this->logAdminActivity('auth', "{$admin->full_name} logged in.");

        return redirect()->to('/admin')->with('success', 'Welcome back, ' . $admin->full_name . '.');
    }

    public function logout()
    {
        if (session('adminIsLoggedIn')) {
            $this->logAdminActivity('auth', session('adminUserName') . ' logged out.');
        }

        session()->destroy();

        return redirect()->to('/admin/login')->with('success', 'You have been logged out.');
    }
}
