<?php
class LoginController extends Controller
{
    public function indexAction()
    {
        // If already logged in, punch through to Dashboard.
        if (!empty($_SESSION['user_id'])) {
            Router::redirect('Dashboard');
            return;
        }

        $vars = [
            'fb_msg'   => '',
            'username' => '',
        ];

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
            $username = trim($_POST['username'] ?? '');
            $password = (string)($_POST['password'] ?? '');
            $vars['username'] = $username;

            if ($username === '' || $password === '') {
                $vars['fb_msg'] = '<div class="alert alert-warning py-2 mb-3">Enter both username and password.</div>';
            } else {
                $db = new DB();
                $rows = $db->mySelect(
                    "SELECT c0d, username, password, full_name, user_group_id, user_group_name, status
                       FROM users
                      WHERE username = :u AND deleted = 0
                      LIMIT 1",
                    [':u' => $username]
                );
                $u = $rows[0] ?? null;

                if (!$u || $u['status'] !== 'ACTIVE' || !password_verify($password, $u['password'])) {
                    $vars['fb_msg'] = '<div class="alert alert-danger py-2 mb-3">Invalid username or password.</div>';
                } else {
                    $_SESSION['user_id']         = (int)$u['c0d'];
                    $_SESSION['username']        = $u['username'];
                    $_SESSION['full_name']       = $u['full_name'];
                    $_SESSION['user_group_id']   = (int)$u['user_group_id'];
                    $_SESSION['user_group_name'] = $u['user_group_name'];
                    $_SESSION['login_time']      = time();

                    UserGroups::loadPermsIntoSession(
                        (int)$u['user_group_id'],
                        (int)$u['c0d']
                    );

                    $db->insertUpdate(
                        "UPDATE users SET last_login_on = NOW() WHERE c0d = :id",
                        [':id' => (int)$u['c0d']]
                    );

                    Router::redirect('Dashboard');
                    return;
                }
            }
        }

        $this->view->setLayout('l_auth');
        $this->view->render('Login/index', $vars);
    }
}
