<?php
session_start();
$_SESSION['username'] = '';
$_SESSION['database'] = '';
$_SESSION['userid'] = '';

$username = $_POST['username'] ?? "";
$password = $_POST['signUpPass'] ?? "";
$confirmpass = $_POST['confirmPass'] ?? "";
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: login.html");
}
function isValidUsername($username) {
    $username = trim($username);

    if (empty($username)) {
        return "Username cannot be empty.";
    }

    if (strlen($username) < 4) {
        return "Username is too short. Minimum 4 characters.";
    }
    if (strlen($username) > 20) {
        return "Username is too long. Maximum 20 characters.";
    }

    $invalidUsernames = ['test', 'admin', 'user', 'username', 'root', 'guest'];
    if (in_array(strtolower($username), $invalidUsernames)) {
        return "Username is not allowed.";
    }

    if (!preg_match('/^[a-zA-Z0-9_]+$/', $username)) {
        return "Username can only contain letters, numbers, and underscores.";
    }

    if (ctype_digit($username)) {
        return "Username cannot be only numbers.";
    }

    return true;
}

$response = [
    "success" => false,
    "message" => ""
];

// Username validation
$validationResult = isValidUsername($username);
if ($validationResult !== true) {
    echo json_encode([
        "success" => false,
        "message" => $validationResult
    ]);
    die();
}

// Password validation
if ($password !== $confirmpass) {
    $response["message"] = "Password and confirm password do not match.";
    echo json_encode($response);
    die();
}

if (strlen($password) < 8) {
    $response["message"] = "Password must be at least 8 characters.";
    echo json_encode($response);
    die();
}

if (!preg_match('/[A-Z]/', $password) ||
    !preg_match('/[a-z]/', $password) ||
    !preg_match('/[0-9]/', $password) ||
    !preg_match('/[\W]/', $password)) {
    $response["message"] = "Password must include uppercase, lowercase, number, and special character.";
    echo json_encode($response);
    die();
}

// Hash password
$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

try {
    require_once 'connection.php';

    // Step 1: Check if username already exists
    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM USERS WHERE username = ?");
    $checkStmt->execute([$username]);
    $userExists = $checkStmt->fetchColumn();

    if ($userExists) {
        $response["success"] = false;
        $response["message"] = "Username already exists. Please choose a different one.";
        echo json_encode($response);
        die();
    }

    // Step 2: Insert new user
    $stmt = $pdo->prepare("INSERT INTO USERS (password, username, databasename, uname, role) VALUES (?, ?, ?, 'User', 'User')");
    $databaseName = 'finance_table';
    $stmt->execute([$hashedPassword, $username, $databaseName]);

    $response["success"] = true;
    $response["message"] = "You are Successfully Registered.";
} catch (PDOException $e) {
    $response["success"] = false;
    $response["message"] = "Registration failed: " . $e->getMessage();
}

echo json_encode($response);
