<?php
include 'dbconn.php';

// Retrieve POST data
$corporate = $_POST['corporate'];
$scheme = trim($_POST['scheme']); // Trim whitespace

// Check if scheme is provided
if (empty($scheme)) {
    // Generate a scheme based on corporate name
    $words = explode(" ", $corporate);
    $suggestedScheme = "";
    
    // Create the initial scheme using the first letters
    foreach ($words as $word) {
        $suggestedScheme .= strtoupper($word[0]);
    }
    $suggestedScheme = substr($suggestedScheme, 0, 3); // Take first three letters
    
    // Ensure the suggested scheme is unique
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM corporate WHERE scheme = ?");
    $stmt->bind_param("s", $suggestedScheme);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();

    // Append a number if the suggested scheme is not unique
    $suffix = 1;
    while ($result['count'] > 0) {
        $suggestedScheme = substr($suggestedScheme, 0, 2) . $suffix; // Change to a new scheme
        $stmt->bind_param("s", $suggestedScheme);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $suffix++;
    }

    echo json_encode(["isUnique" => false, "suggestedScheme" => $suggestedScheme]);
} else {
    // Check if scheme already exists
    $stmt = $conn->prepare("SELECT COUNT(*) as count FROM corporate WHERE scheme = ?");
    $stmt->bind_param("s", $scheme);
    $stmt->execute();
    $result = $stmt->get_result()->fetch_assoc();
    $isUnique = $result['count'] == 0;

    if (!$isUnique) {
        // Suggest a unique scheme based on corporate name if the provided scheme exists
        $words = explode(" ", $corporate);
        $suggestedScheme = "";
        foreach ($words as $word) {
            $suggestedScheme .= strtoupper($word[0]);
        }
        $suggestedScheme = substr($suggestedScheme, 0, 3);

        // Check if suggested scheme is also unique, add number if not
        $stmt->bind_param("s", $suggestedScheme);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();

        $suffix = 1;
        while ($result['count'] > 0) {
            $suggestedScheme = substr($suggestedScheme, 0, 2) . $suffix;
            $stmt->bind_param("s", $suggestedScheme);
            $stmt->execute();
            $result = $stmt->get_result()->fetch_assoc();
            $suffix++;
        }

        echo json_encode(["isUnique" => false, "suggestedScheme" => $suggestedScheme]);
    } else {
        echo json_encode(["isUnique" => true]);
    }
}

$stmt->close();
$conn->close();
?>
