<?php
// Allow cross-origin requests (CORS) if you want to access this API from different domains.
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type");

// Include database configuration
require_once 'config.php';  // This should be your DB connection file

$conn = getDbConnection();  // Connect to the MySQL database

// Retrieve and sanitize data from the POST request
$data = json_decode(file_get_contents("php://input"));

if (isset($data->username) && isset($data->password)) {
    // Sanitize inputs
    $username = trim($data->username);
    $password = $data->password;

    // Validate inputs
    if (empty($username) || empty($password)) {
        echo json_encode(array("status" => "error", "message" => "Username and password cannot be empty"));
        exit();
    }

    // Limit password length to prevent resource exhaustion (e.g., 72 characters for bcrypt)
    if (strlen($password) > 72) {
        echo json_encode(array("status" => "error", "message" => "Password is too long"));
        exit();
    }

    // Check if the username already exists
    $stmt = $conn->prepare("SELECT id FROM admin_users WHERE username = ?");
    if ($stmt === false) {
        // Handle the case where the prepare statement fails (e.g., syntax error)
        echo json_encode(array("status" => "error", "message" => "Database query error"));
        exit();
    }

    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows > 0) {
        // Username already exists
        echo json_encode(array("status" => "error", "message" => "Username already exists"));
    } else {
        // Hash the password using bcrypt
        $hashed_password = password_hash($password, PASSWORD_BCRYPT);

        // Generate a random token (32 characters long)
        $token = bin2hex(random_bytes(16));  // 16 bytes = 32 hex characters

        // Insert new admin user into the database
        $stmt = $conn->prepare("INSERT INTO admin_users (username, password, token) VALUES (?, ?, ?)");
        if ($stmt === false) {
            echo json_encode(array("status" => "error", "message" => "Failed to prepare database query"));
            exit();
        }

        $stmt->bind_param("sss", $username, $hashed_password, $token);

        if ($stmt->execute()) {
            // Admin created successfully, return success and token
            echo json_encode(array("status" => "success", "message" => "Admin registered successfully", "token" => $token));
        } else {
            // Database error while inserting admin
            echo json_encode(array("status" => "error", "message" => "Failed to register admin"));
        }
    }

    $stmt->close();
} else {
    // Invalid input (missing username or password)
    echo json_encode(array("status" => "error", "message" => "Invalid input"));
}

$conn->close();
?>

