<?php
// check_persistent_login.php
// Must be included early in your index.php or controller file.

// No need to session_start() here if your main index/controller does it.
// If run standalone, uncomment the following:
/*
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
*/

// Check if user is already logged in via Session (standard check)
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
    return; // Already logged in, no need to check token
}

// Check for Persistent Login Cookie
if (isset($_COOKIE['persistent_login']) && !empty($_COOKIE['persistent_login'])) {
    
    require_once 'config/database.php';
    require_once 'includes/auth_utils.php'; // For token functions
    
    // Split the token (e.g., "selector:validator")
    $token_parts = explode(':', $_COOKIE['persistent_login'], 2);

    if (count($token_parts) !== 2) {
        clear_persistent_cookie();
        return;
    }
    list($selector, $validator) = $token_parts;

    try {
        // 1. Find token in DB by selector and check expiry
        $sql = "SELECT d.user_id, d.validator_hash, u.username, u.full_name, u.role
                FROM user_devices d 
                JOIN users u ON d.user_id = u.id 
                WHERE d.selector = ? AND d.expires_at > NOW()";
        $stmt = $pdo->prepare($sql);
        $stmt->execute([$selector]);
        $device_record = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($device_record) {
            // 2. Validate the token (Time-Safe Comparison)
            $is_valid = hash_equals($device_record['validator_hash'], hash('sha256', $validator));

            if ($is_valid) {
                // SUCCESS: Log the user in
                $_SESSION['loggedin'] = true;
                $_SESSION['user_id'] = $device_record['user_id'];
                $_SESSION['username'] = $device_record['username'];
                $_SESSION['full_name'] = $device_record['full_name'];
                $_SESSION['user_role'] = $device_record['role'];

                // --- TOKEN ROTATION (Security) ---
                $expiry_days = 7;
                $expiry_timestamp = time() + (86400 * $expiry_days);
                $expires_at = date('Y-m-d H:i:s', $expiry_timestamp);
                
                $new_validator = generate_secure_token(32);
                $new_validator_hash = hash('sha256', $new_validator);
                $new_full_token = $selector . ':' . $new_validator;

                // Update DB with new validator hash and expiry
                $sql_update = "UPDATE user_devices SET validator_hash = ?, expires_at = ? WHERE selector = ?";
                $pdo->prepare($sql_update)->execute([$new_validator_hash, $expires_at, $selector]);

                // Set new cookie
                set_persistent_cookie($new_full_token, $expiry_timestamp);

                // Redirect to dashboard
                $redirect_map = [
                    'student' => 'index.php?page=student_dashboard',
                    'admin' => 'index.php?page=admin_landing',
                    'instructor' => 'index.php?page=admin_landing',
                ];
                $redirect_url = $redirect_map[$device_record['role']] ?? 'index.php?page=home';

                header("Location: " . $redirect_url);
                exit();
            } else {
                // Invalid Validator - potential hijack/old token
                $sql_delete = "DELETE FROM user_devices WHERE selector = ?";
                $pdo->prepare($sql_delete)->execute([$selector]);
            }
        }
    } catch (PDOException $e) {
        error_log("Persistent Login Error: " . $e->getMessage());
    }
    
    // Clear the cookie if verification failed for any reason
    clear_persistent_cookie();
}
// If the script reaches here, no persistent login was found or it failed.