<?php
// Database connection details
$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(json_encode(array('status' => 'error', 'message' => 'Connection failed: ' . $conn->connect_error)));
}

// Get `subject` and `just_chapter` from POST data
$subject = isset($_POST['subject']) ? trim($_POST['subject']) : '';
$just_chapter = isset($_POST['just_chapter']) ? trim($_POST['just_chapter']) : '';

// Validate inputs
if (empty($subject)) {
    echo json_encode(array('status' => 'error', 'message' => 'Subject not provided.'));
    exit;
}

if (empty($just_chapter)) {
    echo json_encode(array('status' => 'error', 'message' => 'Chapter not provided.'));
    exit;
}

// Step 1: Delete the table with name matching `just_chapter`
$deleteTableQuery = "DROP TABLE IF EXISTS `$just_chapter`";
if ($conn->query($deleteTableQuery) === TRUE) {
    echo json_encode(array('status' => 'success', 'message' => "Table '$just_chapter' deleted successfully."));
} else {
    echo json_encode(array('status' => 'error', 'message' => "Error deleting table '$just_chapter': " . $conn->error));
    exit;
}

// Step 2: Delete the `just_chapter` from the `subject` table in the `Chapter` column
$deleteChapterQuery = "DELETE FROM `$subject` WHERE `Chapter` = '$just_chapter'";
if ($conn->query($deleteChapterQuery) === TRUE) {
    if ($conn->affected_rows > 0) {
        echo json_encode(array('status' => 'success', 'message' => "Chapter '$just_chapter' deleted successfully from `$subject` table."));
    } else {
        echo json_encode(array('status' => 'error', 'message' => "No matching chapter '$just_chapter' found in `$subject` table."));
    }
} else {
    echo json_encode(array('status' => 'error', 'message' => "Error deleting chapter: " . $conn->error));
}

// Close the connection
$conn->close();
?>
