<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: /Sign&Log.php");
    exit();
}

// Basic input validation
if (empty($_POST['email'])) {
    header("Location: /Sign&Log.php?error=INVALID_EMAIL");
    exit();
}
if (empty($_POST['username'])) {
    header("Location: /Sign&Log.php?error=INVALID_USERNAME&email=" . urlencode($_POST['email']));
    exit();
}
if (empty($_POST["password"])) {
    header("Location: /Sign&Log.php?error=INVALID_PASSWORD&email=" . urlencode($_POST['email']) . "&username=" . urlencode($_POST['username']));
    exit();
}

// Sanitize and validate inputs
$input_name = trim(htmlspecialchars($_POST['username']));
$input_email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$input_password = $_POST['password'];
$role = 'Member';

// Additional validation
if (!$input_email) {
    header("Location: /Sign&Log.php?error=INVALID_EMAIL");
    exit();
}

// Password strength validation
if (strlen($input_password) < 8) {
    header("Location: /Sign&Log.php?error=WEAK_PASSWORD&email=" . urlencode($_POST['email']) . "&username=" . urlencode($input_name));
    exit();
}

// Username validation (alphanumeric and underscore only)
if (!preg_match('/^[a-zA-Z0-9_]+$/', $input_name)) {
    header("Location: /Sign&Log.php?error=INVALID_USERNAME_FORMAT&email=" . urlencode($_POST['email']));
    exit();
}

try {
    require 'connect.php';

    // Begin a transaction
    $conn->beginTransaction();

    // Check for existing username
    $stmt = $conn->prepare("CALL register_user(:username, :email, :password, :role)");
    // Hash password
    $hashed_password = password_hash($input_password, PASSWORD_ARGON2ID, [
        'memory_cost' => 65536,
        'time_cost' => 4,
        'threads' => 3
    ]);

    $stmt->bindParam(':username', $input_name, PDO::PARAM_STR);
    $stmt->bindParam(':email', $input_email, PDO::PARAM_STR);
    $stmt->bindParam(':password', $hashed_password, PDO::PARAM_STR);
    $stmt->bindParam(':role', $role, PDO::PARAM_STR);

    $stmt->execute();

    // Commit the transaction
    $conn->commit();

    // Set session variables for automatic login
    session_regenerate_id(true);
    $_SESSION['username'] = $input_name;
    $_SESSION['userid'] = $conn->lastInsertId();
    $_SESSION['role'] = $role;
    $_SESSION['last_activity'] = time();
    $_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];

    // Redirect to homepage after successful registration
    header("Location: ./HomePage.php");
    exit();

} catch (PDOException $e) {
    // Roll back the transaction if something failed
    $conn->rollBack();
    error_log("Registration error: " . $e->getMessage());
    header("Location: /Sign&Log.php?error=SERVER_ERROR");
    exit();
}


?>