<?php
$servername = "localhost";
$username = "venmobdc_Auto_DataBase_User";
$password = "hB_nf_W-^SIh";
$dbname = "venmobdc_Auto_Database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Sanitize and validate inputs
    $bbaMbaClassName = isset($_POST['bbaMbaClassName']) ? $conn->real_escape_string(trim($_POST['bbaMbaClassName'])) : '';

    if (!empty($bbaMbaClassName)) {
        // Check if the table already exists
        $checkTableSql = "SHOW TABLES LIKE '$bbaMbaClassName'";
        $result = $conn->query($checkTableSql);

        if ($result->num_rows == 0) {
            // Create a new table with the name from input_BBA_MBA and columns 'Year' and 'Table_Name'
            if (preg_match('/^[a-zA-Z0-9_ ]+$/', $bbaMbaClassName)) { // Allow spaces in the table name
                $createTableSql = "CREATE TABLE IF NOT EXISTS `$bbaMbaClassName` (
                    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    Year VARCHAR(255) NOT NULL,
                    Table_Name VARCHAR(255) NOT NULL
                )";

                if ($conn->query($createTableSql) === TRUE) {
                    echo "Table '$bbaMbaClassName' created successfully with 'Year' and 'Table_Name' columns.";
                } else {
                    echo "Error creating table: " . $conn->error;
                }

                // Ensure the 'Whice_Class' table exists
                $createWhiceClassTableSql = "CREATE TABLE IF NOT EXISTS `Whice_Class` (
                    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                    Class VARCHAR(255) NOT NULL
                )";

                if ($conn->query($createWhiceClassTableSql) === TRUE) {
                    // Insert the class name into the 'Whice_Class' table
                    $insertClassSql = "INSERT INTO `Whice_Class` (Class) VALUES ('$bbaMbaClassName')";
                    if ($conn->query($insertClassSql) === TRUE) {
                        echo "Class name '$bbaMbaClassName' added to 'Whice_Class' table.";
                    } else {
                        echo "Error inserting class name: " . $conn->error;
                    }
                } else {
                    echo "Error creating 'Whice_Class' table: " . $conn->error;
                }
            } else {
                echo "Invalid class name.";
            }
        } else {
            echo "Table '$bbaMbaClassName' already exists.";
        }
    } else {
        echo "Class name cannot be empty.";
    }
} else {
    echo "Invalid request method.";
}

$conn->close();
?>
