<?php
declare(strict_types=1);

namespace App\Controllers\Web;

use Core\Controller;
use Core\DB;
use Core\Session;
use Core\Tool;

final class SuperLoginController extends Controller
{
    public function middleware(): array
    {
        return [];
    }

    public function index(): void
    {
        if (Session::check()) {
            $user = Session::user();
            if (!empty($user['is_super_admin'])) {
                redirect('/SuperAdmin');
            }
        }
        $this->view->setLayout('blank');
        $this->render('super-login/index', [
            'csrf'  => Tool::generateCsrf(),
            'msg'   => Session::flash('super_msg'),
            'error' => Session::flash('super_error'),
        ]);
    }

    public function authenticate(): void
    {
        if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
            redirect('/SuperLogin');
        }
        if (!Tool::checkCsrf($_POST['_csrf'] ?? null)) {
            Session::flash('super_error', 'Session expired. Please try again.');
            redirect('/SuperLogin');
        }

        $username = trim((string) ($_POST['username'] ?? ''));
        $password = (string) ($_POST['password'] ?? '');

        if ($username === '' || $password === '') {
            Session::flash('super_error', 'Username and password are required.');
            redirect('/SuperLogin');
        }

        $user = DB::one(
            'SELECT u.*, r.code AS role_code, r.name AS role
               FROM users u
          LEFT JOIN roles r ON r.role_id = u.role_id
              WHERE u.username = :u
                AND u.is_super_admin = 1
                AND u.deleted_at IS NULL
                AND u.status = :st
              LIMIT 1',
            ['u' => $username, 'st' => 'active']
        );

        if (!$user || empty($user['password']) || !password_verify($password, $user['password'])) {
            Session::flash('super_error', 'Invalid credentials.');
            redirect('/SuperLogin');
        }

        DB::run('UPDATE users SET last_login_at = NOW() WHERE user_id = :id', ['id' => $user['user_id']]);
        Session::login($user, []);
        redirect('/SuperAdmin');
    }
}