<?php
/**
 * Controller Auth - Login & Logout
 */
class AuthController {

    public function login() {
        // Sudah login → redirect ke dashboard
        if (isLoggedIn()) {
            redirect(BASE_URL . '/index.php?page=dashboard');
        }

        $error = '';

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {

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

            if (empty($username) || empty($password)) {
                $error = 'Username dan password wajib diisi.';
            } else {
                $db   = getDB();
                $stmt = $db->prepare("SELECT * FROM users WHERE username = ? LIMIT 1");
                $stmt->bind_param('s', $username);
                $stmt->execute();
                $user = stmt_get_result($stmt)->fetch_assoc();

                if ($user && password_verify($password, $user['password'])) {
                    // Regenerate session ID untuk keamanan
                    session_regenerate_id(true);

                    $_SESSION['user_id']    = $user['id'];
                    $_SESSION['user_nama']  = $user['nama_lengkap'];
                    $_SESSION['user_role']  = $user['role'];
                    $_SESSION['user_email'] = $user['email'];

                    // Update last login
                    $uid = (int)$user['id'];
                    $db->query("UPDATE users SET last_login = NOW() WHERE id = $uid");

                    redirect(BASE_URL . '/index.php?page=dashboard');
                } else {
                    $error = 'Username atau password salah.';
                    sleep(1); // anti brute-force
                }
            }
        }

        $pageTitle = 'Login';
        $csrfToken = generateCSRF(); // tetap generate untuk form
        include __DIR__ . '/../views/auth/login.php';
    }

    public function logout() {
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $params = session_get_cookie_params();
            setcookie(
                session_name(), '',
                time() - 42000,
                $params['path'],
                $params['domain'],
                $params['secure'],
                $params['httponly']
            );
        }
        session_destroy();
        redirect(BASE_URL . '/index.php?page=login');
    }
}
