<?php
// check_login.php

// Ensure session is started first
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 1. Check if user is already logged in via Session (standard check)
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true) {
    // User is already logged in, do nothing (or redirect if necessary)
    return;
}

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

    if (empty($selector) || empty($validator)) {
        // Malformed cookie, clear it and exit
        setcookie('persistent_login', '', time() - 3600, '/');
        return;
    }

    try {
        // 3. Find token in DB by selector
        $sql = "SELECT d.user_id, d.validator_hash, d.expires_at, 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) {
            // 4. Validate the token (Time-Safe Comparison)
            $is_valid = hash_equals($device_record['validator_hash'], hash('sha256', $validator));

            if ($is_valid) {
                // Successful Persistent Login!
                $_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 Best Practice) ===
                // Generate new validator to prevent session hijacking if token is compromised
                $new_validator = bin2hex(random_bytes(32));
                $new_validator_hash = hash('sha256', $new_validator);
                $new_full_token = $selector . ':' . $new_validator;
                $expiry_days = 7;
                $expiry_timestamp = time() + (86400 * $expiry_days);
                $expires_at = date('Y-m-d H:i:s', $expiry_timestamp);

                // 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
                setcookie('persistent_login', $new_full_token, [
                    'expires' => $expiry_timestamp,
                    'path' => '/',
                    'domain' => '', 
                    'secure' => true, 
                    'httponly' => true, 
                    'samesite' => 'Lax'
                ]);

                // Redirect to dashboard immediately
                $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 (possible hijack attempt or old token)
                // Delete the record and clear the cookie
                $sql_delete = "DELETE FROM user_devices WHERE selector = ?";
                $pdo->prepare($sql_delete)->execute([$selector]);
            }
        }
    } catch (PDOException $e) {
        // Log the error
        error_log("Persistent Login Error: " . $e->getMessage());
    }

    // Always clear the cookie if we couldn't log in via token
    setcookie('persistent_login', '', time() - 3600, '/');
}