<?php
namespace Core\App\Controllers;

use Core\System\Request;
use Core\System\Response;
use Core\App\Models\AdminModel;
use Core\App\Controllers\DashboardController;
use Core\App\Services\Auth\LoginThrottleService;
use Core\App\Models\AdminActivityModel;

class AdminController
{
    public function login()
    {
        if (!empty($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
            Response::redirect('/admin/dashboard');
        }

        require ROOT_PATH . '/admin/templates/login.php';
    }

    public function doLogin()
    {
        $username = trim((string) Request::input('username'));
        $password = (string) Request::input('password');
        $ip = (string)($_SERVER['REMOTE_ADDR'] ?? 'unknown');
        $throttle = new LoginThrottleService();

        $throttle->assertAllowed($username, $ip);

        if ($username === '' || $password === '') {
            $_SESSION['login_error'] = __('admin.login.invalid', 'Invalid login credentials');
            Response::redirect('/admin/login');
        }

        $adminModel = new AdminModel();
        $admin = $adminModel->authenticate($username, $password);

        if (!$admin) {
            $throttle->recordFailure($username, $ip);
            try {
                \Core\App\Models\SecurityLog::log('warning', 'Failed admin login attempt', '/admin/login');
            } catch (\Throwable $e) {
            }

            $_SESSION['login_error'] = __('admin.login.invalid', 'Invalid login credentials');
            Response::redirect('/admin/login');
        }

        $throttle->clear($username, $ip);
        session_regenerate_id(true);

        $_SESSION['admin_logged_in'] = true;
        $_SESSION['admin_id']        = (int) $admin['id'];
        $_SESSION['admin_username']  = $admin['username'];
        $_SESSION['admin_role']      = $admin['role'] ?? 'owner';
        $_SESSION['admin_fingerprint'] = hash('sha256', $ip . '|' . ($_SERVER['HTTP_USER_AGENT'] ?? ''));

        // Log login activity
        try {
            (new AdminActivityModel())->log(
                (int)$admin['id'],
                'login',
                $ip,
                (string)($_SERVER['HTTP_USER_AGENT'] ?? '')
            );
            // Update last_seen_at
            (new AdminActivityModel())->updatePresence((int)$admin['id']);
        } catch (\Throwable $e) {}

        try {
            \Core\App\Models\SecurityLog::log('info', 'Admin logged in successfully', '/admin/login');
        } catch (\Throwable $e) {
        }

        Response::redirect('/admin/dashboard');
    }

    public function dashboard()
    {
        (new DashboardController())->index();
    }

    public function logout()
    {
        // Accept POST only — GET logout is vulnerable to CSRF-triggered session termination.
        // The logout links in the admin header use a small inline form with CSRF token.
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            Response::redirect('/admin/login');
            return;
        }

        \Core\System\Csrf::check();

        // Log logout activity
        $logoutAdminId = $_SESSION['admin_id'] ?? null;
        if ($logoutAdminId) {
            try {
                (new AdminActivityModel())->log(
                    (int)$logoutAdminId,
                    'logout',
                    (string)($_SERVER['REMOTE_ADDR'] ?? 'unknown'),
                    (string)($_SERVER['HTTP_USER_AGENT'] ?? '')
                );
            } catch (\Throwable $e) {}
        }

        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'] ?? '', !empty($params['secure']), !empty($params['httponly']));
        }
        session_destroy();
        Response::redirect('/admin/login');
    }
}
