<?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
    $selectedTable = isset($_POST['selectedTable']) ? $conn->real_escape_string(trim($_POST['selectedTable'])) : '';
    $classLinkOrPDF = isset($_POST['classLinkOrPDF']) ? $conn->real_escape_string(trim($_POST['classLinkOrPDF'])) : '';
    $type = isset($_POST['type']) ? $conn->real_escape_string(trim($_POST['type'])) : '';

    if (!empty($selectedTable) && !empty($classLinkOrPDF) && !empty($type)) {
        // Check if the selected table exists
        $checkTableSql = "SHOW TABLES LIKE '$selectedTable'";
        $tableResult = $conn->query($checkTableSql);

        if ($tableResult && $tableResult->num_rows > 0) {
            // Check if the table contains the required columns
            $checkColumnsSql = "SHOW COLUMNS FROM `$selectedTable` LIKE 'Class_link'";
            $classLinkResult = $conn->query($checkColumnsSql);

            $checkColumnsSql2 = "SHOW COLUMNS FROM `$selectedTable` LIKE 'Type'";
            $typeResult = $conn->query($checkColumnsSql2);

            if ($classLinkResult && $classLinkResult->num_rows > 0 && $typeResult && $typeResult->num_rows > 0) {
                // Check if the combination of Class_link and Type already exists
                $checkDuplicateSql = "SELECT * FROM `$selectedTable` WHERE Class_link='$classLinkOrPDF' AND Type='$type'";
                $duplicateResult = $conn->query($checkDuplicateSql);

                if ($duplicateResult && $duplicateResult->num_rows > 0) {
                    echo "This information already exists in '$selectedTable'. No need to add again.";
                } else {
                    // Insert the data into the table
                    $insertSql = "INSERT INTO `$selectedTable` (Class_link, Type) VALUES ('$classLinkOrPDF', '$type')";
                    if ($conn->query($insertSql) === TRUE) {
                        echo "Class link and type added successfully to '$selectedTable'.";
                    } else {
                        echo "Error inserting data: " . $conn->error;
                    }
                }
            } else {
                echo "You selected the wrong table.";
            }
        } else {
            echo "The selected table does not exist. Please select the correct table.";
        }
    } else {
        echo "Invalid table name, class link, or type.+$selectedTable+$classLinkOrPDF+$type";
    }
} else {
    echo "Invalid request method.";
}

$conn->close();
?>
