<?php
// ============================================================
// AuthController
// ============================================================

$action = $_GET['action'] ?? ($_GET['page'] ?? 'login');
$db     = Database::getInstance();

if ($action === 'logout' || $page === 'logout') {
    logActivity('logout', 'auth', 'User logged out');
    session_destroy();
    header('Location: ' . APP_URL . '/index.php?page=login');
    exit;
}

// ── OTP Verification ──────────────────────────────────────────
if ($page === 'otp') {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        verifyCsrf();
        $userId = (int)($_SESSION['otp_user_id'] ?? 0);
        $otp    = trim($_POST['otp'] ?? '');

        if ($userId && verifyOTP($userId, $otp)) {
            $stmt = $db->prepare('SELECT * FROM users WHERE user_id = ? AND is_active = 1');
            $stmt->execute([$userId]);
            $user = $stmt->fetch();

            if ($user) {
                session_regenerate_id(true);
                $_SESSION['user_id']   = $user['user_id'];
                $_SESSION['role']      = $user['role'];
                $_SESSION['name']      = $user['officer_name'];
                unset($_SESSION['otp_user_id']);
                $db->prepare('UPDATE users SET last_login = NOW() WHERE user_id = ?')->execute([$user['user_id']]);
                logActivity('login', 'auth', 'OTP verified, session started', $user['user_id']);
                setFlash('success', 'Welcome back, ' . $user['officer_name'] . '!');
                header('Location: ' . APP_URL . '/index.php?page=dashboard');
                exit;
            }
        }
        setFlash('error', 'Invalid or expired OTP. Please try again.');
    }
    include __DIR__ . '/../views/auth/otp.php';
    exit;
}

// ── Login ─────────────────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    verifyCsrf();
    $email    = sanitize($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

    $stmt = $db->prepare('SELECT * FROM users WHERE email = ? AND is_active = 1');
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if ($user && password_verify($password, $user['password'])) {
        // Generate and "send" OTP
        $otp = generateOTP();
        storeOTP($user['user_id'], $otp);
        $_SESSION['otp_user_id'] = $user['user_id'];

        // In production: send via SMS. For dev, display it.
        $_SESSION['dev_otp'] = $otp; // remove in production

        logActivity('login_attempt', 'auth', 'OTP generated for ' . $email, $user['user_id']);
        header('Location: ' . APP_URL . '/index.php?page=otp');
        exit;
    }

    setFlash('error', 'Invalid email or password.');
}

include __DIR__ . '/../views/auth/login.php';
