<?php
session_start();
header('Content-Type: application/json');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header("Location: login.html");
    exit();
}

// Check session and input
if (!isset($_SESSION['reset_userid'], $_POST['new_pass'], $_POST['confirm_pass'], $_POST['username'])) {
    $response['message'] = "Session expired or invalid input.";
    echo json_encode($response);
    exit();
}

$userid = $_SESSION['reset_userid'];
$username = trim($_POST['username']);
$password = $_POST['new_pass'];
$confirmpass = $_POST['confirm_pass'];

function isValidUsername($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;
}

$validationResult = isValidUsername($username);
if ($validationResult !== true) {
    $response["message"] = $validationResult;
    echo json_encode($response);
    exit();
}

if ($password !== $confirmpass) {
    $response["message"] = "Password and confirm password do not match.";
    echo json_encode($response);
    exit();
} elseif (strlen($password) < 8) {
    $response["message"] = "Password must be at least 8 characters.";
    echo json_encode($response);
    exit();
} elseif (!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);
    exit();
}

$hashedPassword = password_hash($password, PASSWORD_BCRYPT);

try {
    require_once 'connection.php';

    $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE username = :uname AND userid != :id");
    $checkStmt->bindParam(':uname', $username);
    $checkStmt->bindParam(':id', $userid);
    $checkStmt->execute();
    $count = $checkStmt->fetchColumn();

    if ($count > 0) {
        $response["message"] = "Username already taken. Please choose another.";
        echo json_encode($response);
        exit();
    }

    $updateStmt = $pdo->prepare("UPDATE users SET password = :pwd, username = :uname WHERE userid = :id");
    $updateStmt->bindParam(':pwd', $hashedPassword);
    $updateStmt->bindParam(':uname', $username);
    $updateStmt->bindParam(':id', $userid);

    if ($updateStmt->execute()) {
        session_unset();
        session_destroy();
        $response["success"] = true;
        $response["message"] = "Password updated successfully.";
    } else {
        $response["message"] = "Failed to update password.";
    }

} catch (PDOException $e) {
    $response["message"] = "Database error: " . $e->getMessage();
}

echo json_encode($response);
