<?php
// Gunakan file konfigurasi koneksi Anda
require_once 'config.php'; // Pastikan path-nya benar

header('Content-Type: application/json');

$action = $_POST['action'] ?? '';

// --- FUNGSI HELPER UNTUK KEAMANAN ---
function sanitize_name($name) {
    // Hanya izinkan huruf, angka, dan underscore.
    return preg_replace('/[^a-zA-Z0-9_]/', '', $name);
}

switch($action) {
    case 'get_all_tables':
        $result = $conn->query("SHOW TABLES");
        $tables = [];
        while ($row = $result->fetch_array()) {
            $tables[] = ['name' => $row[0]];
        }
        echo json_encode(['success' => true, 'data' => $tables]);
        break;

    case 'get_table_structure':
        $tableName = sanitize_name($_POST['tableName'] ?? '');
        if(empty($tableName)) die(json_encode(['success' => false, 'message' => 'Table name not provided.']));

        $result = $conn->query("DESCRIBE `$tableName`");
        if(!$result) die(json_encode(['success' => false, 'message' => $conn->error]));

        $columns = [];
        while ($row = $result->fetch_assoc()) {
            // Parsing tipe data dan panjangnya
            preg_match('/(\w+)(?:\((.+)\))?/', $row['Type'], $matches);
            $type = $matches[1] ?? '';
            $length = $matches[2] ?? '';

            $columns[] = [
                'name' => $row['Field'],
                'type' => strtoupper($type),
                'length' => $length,
                'nullable' => ($row['Null'] === 'YES'),
                'default' => $row['Default'],
                'index' => ($row['Key'] === 'PRI' ? 'PRIMARY' : ($row['Key'] === 'UNI' ? 'UNIQUE' : ($row['Key'] === 'MUL' ? 'INDEX' : ''))),
                'autoIncrement' => (strpos($row['Extra'], 'auto_increment') !== false)
            ];
        }
        echo json_encode(['success' => true, 'data' => $columns]);
        break;

    case 'delete_table':
        $tableName = sanitize_name($_POST['tableName'] ?? '');
        if(empty($tableName)) die(json_encode(['success' => false, 'message' => 'Table name not provided.']));

        if ($conn->query("DROP TABLE `$tableName`")) {
            echo json_encode(['success' => true, 'message' => "Table '$tableName' deleted successfully."]);
        } else {
            echo json_encode(['success' => false, 'message' => "Error deleting table: " . $conn->error]);
        }
        break;

    case 'save_table':
        // Logika untuk CREATE dan ALTER TABLE
        // Ini adalah bagian yang paling kompleks dan memerlukan validasi ketat
        $isCreating = filter_var($_POST['isCreating'] ?? false, FILTER_VALIDATE_BOOLEAN);
        $editorData = json_decode($_POST['editorData'] ?? '{}', true);

        $tableName = sanitize_name($editorData['tableName']);
        $originalTableName = sanitize_name($editorData['originalTableName']);
        $columns = $editorData['columns'];

        if (empty($tableName)) die(json_encode(['success' => false, 'message' => 'Table name is required.']));

        $sql_parts = [];
        foreach ($columns as $col) {
            $colName = sanitize_name($col['name']);
            if(empty($colName)) continue;

            $part = "`$colName` " . strtoupper($col['type']);
            if(!empty($col['length'])) {
                $part .= "({$conn->real_escape_string($col['length'])})";
            }
            $part .= $col['nullable'] ? ' NULL' : ' NOT NULL';
            if ($col['default'] !== null && $col['default'] !== '') {
                if (strtoupper($col['default']) === 'NULL') {
                     $part .= ' DEFAULT NULL';
                } else {
                     $part .= " DEFAULT '{$conn->real_escape_string($col['default'])}'";
                }
            }
            if($col['autoIncrement']) $part .= ' AUTO_INCREMENT';
            if($col['index'] === 'PRIMARY') $part .= ' PRIMARY KEY';
            if($col['index'] === 'UNIQUE') $part .= ' UNIQUE KEY';

            $sql_parts[] = $part;
        }

        $sql = '';
        if ($isCreating) {
            $sql = "CREATE TABLE `$tableName` (" . implode(', ', $sql_parts) . ") ENGINE=InnoDB;";
        } else {
            // Untuk ALTER TABLE, logikanya jauh lebih rumit.
            // Implementasi sederhana: rename dan drop/add columns.
            // Untuk aplikasi produksi, disarankan menggunakan library migrasi database.
            $sql = "ALTER TABLE `$originalTableName` RENAME TO `$tableName`;";
            // Kode untuk menambah/mengubah kolom akan lebih kompleks dan tidak disertakan di sini
            // untuk menjaga kejelasan.
             die(json_encode(['success' => false, 'message' => 'ALTER TABLE functionality is complex and not fully implemented in this example. CREATE and DELETE are functional.']));
        }

        if ($conn->query($sql)) {
            echo json_encode(['success' => true, 'message' => "Table '$tableName' saved successfully."]);
        } else {
            echo json_encode(['success' => false, 'message' => "SQL Error: " . $conn->error . " (Query: $sql)"]);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action.']);
        break;
}

$conn->close();
?>