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

    // Ensure necessary data is provided
    if (empty($selectedTable) || empty($encodedImage) || empty($type)) {
        echo json_encode(["status" => "error", "message" => "Invalid table name, image data, or type."]);
        exit();
    }

    // Check if the table exists
    $checkTableSql = "SHOW TABLES LIKE '$selectedTable'";
    $tableResult = $conn->query($checkTableSql);

    if ($tableResult && $tableResult->num_rows > 0) {
        // Decode the Base64 image
        $imageData = base64_decode($encodedImage);
        if ($imageData === false) {
            echo json_encode(["status" => "error", "message" => "Failed to decode image."]);
            exit();
        }

        // Save the image to the server
        $uploadDirectory = 'uploads/'; // Ensure this directory exists on your server
        if (!file_exists($uploadDirectory)) {
            mkdir($uploadDirectory, 0777, true);
        }

        $imageName = uniqid() . '.jpg'; // Generate a unique file name
        $imagePath = $uploadDirectory . $imageName;
        $imageUrl = 'https://www.venmobd.com/testClass/Auto_Database/' . $imagePath;

        if (!file_put_contents($imagePath, $imageData)) {
            echo json_encode(["status" => "error", "message" => "Failed to save the image to the server."]);
            exit();
        }

        // Check if required columns exist
        $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 for duplicate entries
            $checkDuplicateSql = "SELECT * FROM `$selectedTable` WHERE Class_link='$imageUrl' AND Type='$type'";
            $duplicateResult = $conn->query($checkDuplicateSql);

            if ($duplicateResult && $duplicateResult->num_rows > 0) {
                echo json_encode(["status" => "error", "message" => "This information already exists in '$selectedTable'. No need to add again."]);
            } else {
                // Insert the image URL and type into the database
                $insertSql = "INSERT INTO `$selectedTable` (Class_link, Type) VALUES ('$imageUrl', '$type')";
                if ($conn->query($insertSql) === TRUE) {
                    echo json_encode(["status" => "success", "message" => "Image uploaded and data inserted successfully."]);
                } else {
                    echo json_encode(["status" => "error", "message" => "Error inserting data: " . $conn->error]);
                }
            }
        } else {
            echo json_encode(["status" => "error", "message" => "Required columns not found in the selected table."]);
        }
    } else {
        echo json_encode(["status" => "error", "message" => "The selected table does not exist."]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Invalid request method."]);
}

$conn->close();
?>
