<?php
// Initialize secure session
require_once '../config/security.php';
initSecureSession();
session_start();

require_once '../config/database.php';

// Check for remember me cookie
if (!isset($_SESSION['user_id']) && isset($_COOKIE['remember_token'])) {
    $conn = getDBConnection();
    $token = $_COOKIE['remember_token'];

    // Validate token format (should be 64 characters hex)
    if (preg_match('/^[a-f0-9]{64}$/i', $token)) {
        $hashed_token = hash('sha256', $token);

        $stmt = $conn->prepare("SELECT user_id, expires_at FROM remember_tokens WHERE token_hash = ? AND expires_at > NOW()");
        $stmt->bind_param("s", $hashed_token);
        $stmt->execute();
        $result = $stmt->get_result();

        if ($result->num_rows == 1) {
            $token_data = $result->fetch_assoc();
            $user_id = $token_data['user_id'];

            // Get user data
            $user_stmt = $conn->prepare("SELECT id, username, user_type, full_name, email FROM users WHERE id = ?");
            $user_stmt->bind_param("i", $user_id);
            $user_stmt->execute();
            $user_result = $user_stmt->get_result();

            if ($user_result->num_rows == 1) {
                $user = $user_result->fetch_assoc();

                // Set session variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['user_type'] = $user['user_type'];
                $_SESSION['full_name'] = $user['full_name'];
                $_SESSION['email'] = $user['email'];

                // Regenerate session ID for security
                session_regenerate_id(true);

                // Redirect based on user type
                if ($user['user_type'] == 'student') {
                    header('Location: ../student/dashboard.php');
                } elseif ($user['user_type'] == 'admin') {
                    header('Location: ../admin/dashboard.php');
                } else {
                    header('Location: ../instructor/dashboard.php');
                }
                exit();
            }
            $user_stmt->close();
        }
        $stmt->close();
    }
    $conn->close();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Validate CSRF token
    requireCSRFToken();

    $username = trim($_POST['username']);
    $password = $_POST['password'];
    $user_type = $_POST['user_type'];
    $remember_me = isset($_POST['remember_me']) && $_POST['remember_me'] == '1';

    if (empty($username) || empty($password) || empty($user_type)) {
        header('Location: ../index.php?error=invalid');
        exit();
    }

    // Rate limiting - prevent brute force attacks
    if (!isset($_SESSION['login_attempts'])) {
        $_SESSION['login_attempts'] = 0;
        $_SESSION['last_attempt_time'] = time();
    }

    // Reset attempts if more than 15 minutes have passed
    if (time() - $_SESSION['last_attempt_time'] > 900) {
        $_SESSION['login_attempts'] = 0;
    }

    // Block if too many attempts
    if ($_SESSION['login_attempts'] >= 5) {
        $wait_time = 900 - (time() - $_SESSION['last_attempt_time']);
        if ($wait_time > 0) {
            header('Location: ../index.php?error=blocked&wait=' . ceil($wait_time / 60));
            exit();
        } else {
            $_SESSION['login_attempts'] = 0;
        }
    }

    $conn = getDBConnection();

    // Prepare statement to prevent SQL injection
    $stmt = $conn->prepare("SELECT id, username, password, user_type, full_name, email FROM users WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();

        // Verify password
        if (password_verify($password, $user['password'])) {
            // Check if user type matches (or if user is admin)
            if ($user['user_type'] == $user_type || $user['user_type'] == 'admin') {
                // Reset login attempts
                $_SESSION['login_attempts'] = 0;

                // Set session variables
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['user_type'] = $user['user_type'];
                $_SESSION['full_name'] = $user['full_name'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['login_time'] = time();
                $_SESSION['user_ip'] = $_SERVER['REMOTE_ADDR'];
                $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];

                // Regenerate session ID to prevent session fixation
                session_regenerate_id(true);

                // Handle Remember Me
                if ($remember_me) {
                    // Generate secure random token
                    $token = bin2hex(random_bytes(32)); // 64 character hex string
                    $hashed_token = hash('sha256', $token);

                    // Create remember_tokens table if not exists
                    $conn->query("CREATE TABLE IF NOT EXISTS remember_tokens (
                        id INT AUTO_INCREMENT PRIMARY KEY,
                        user_id INT NOT NULL,
                        token_hash VARCHAR(64) NOT NULL,
                        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                        expires_at TIMESTAMP NOT NULL,
                        INDEX(token_hash),
                        INDEX(user_id)
                    )");

                    // Delete old tokens for this user
                    $delete_stmt = $conn->prepare("DELETE FROM remember_tokens WHERE user_id = ?");
                    $delete_stmt->bind_param("i", $user['id']);
                    $delete_stmt->execute();
                    $delete_stmt->close();

                    // Insert new token (expires in 30 days)
                    $expires = date('Y-m-d H:i:s', strtotime('+30 days'));
                    $token_stmt = $conn->prepare("INSERT INTO remember_tokens (user_id, token_hash, expires_at) VALUES (?, ?, ?)");
                    $token_stmt->bind_param("iss", $user['id'], $hashed_token, $expires);
                    $token_stmt->execute();
                    $token_stmt->close();

                    // Set cookie (30 days, httponly, secure if HTTPS)
                    setcookie('remember_token', $token, [
                        'expires' => time() + (30 * 24 * 60 * 60),
                        'path' => '/',
                        'domain' => '',
                        'secure' => isset($_SERVER['HTTPS']),
                        'httponly' => true,
                        'samesite' => 'Strict'
                    ]);
                }

                // Redirect based on user type
                if ($user['user_type'] == 'student') {
                    header('Location: ../student/dashboard.php');
                } elseif ($user['user_type'] == 'admin') {
                    header('Location: ../admin/dashboard.php');
                } else {
                    header('Location: ../instructor/dashboard.php');
                }
                exit();
            } else {
                $_SESSION['login_attempts']++;
                $_SESSION['last_attempt_time'] = time();
                header('Location: ../index.php?error=type');
                exit();
            }
        } else {
            $_SESSION['login_attempts']++;
            $_SESSION['last_attempt_time'] = time();
            header('Location: ../index.php?error=invalid');
            exit();
        }
    } else {
        $_SESSION['login_attempts']++;
        $_SESSION['last_attempt_time'] = time();
        header('Location: ../index.php?error=invalid');
        exit();
    }

    $stmt->close();
    $conn->close();
} else {
    header('Location: ../index.php');
    exit();
}
?>
