<?php
// crud.php - FIXED & CLEAN VERSION
error_reporting(E_ALL);
ini_set('display_errors', 0); // Matikan display error agar tidak merusak format JSON
header('Content-Type: application/json; charset=utf-8');

include 'config.php';

// Buat koneksi
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    echo json_encode(['error' => 'Connection failed: ' . $conn->connect_error]);
    exit;
}
$conn->set_charset("utf8mb4");

$action = isset($_POST['action']) ? $_POST['action'] : '';

// --- FUNGSI CREATE (TAMBAH) ---
if ($action === 'tambahjson') {
    $table = $_POST['table'];
    
    // Ambil semua data POST
    $data = $_POST;
    
    // Hapus field sistem yang bukan nama kolom database
    $ignoredKeys = ['action', 'table', 'xbrand', 'xcab', 'id'];
    foreach($ignoredKeys as $key) {
        unset($data[$key]);
    }

    // Persiapkan Query
    $fields = array_keys($data);
    $values = array_values($data);
    $params = array_fill(0, count($fields), '?');
    
    // Gunakan backticks (`) untuk nama kolom agar aman dari reserved words
    $sql = "INSERT INTO `$table` (`" . implode('`, `', $fields) . "`) VALUES (" . implode(', ', $params) . ")";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['error' => 'Prepare failed: ' . $conn->error]);
        exit;
    }

    // Bind Params
    $types = '';
    foreach ($values as $value) {
        // Tentukan tipe data
        if (is_int($value)) $types .= 'i';
        elseif (is_float($value)) $types .= 'd';
        else $types .= 's';
    }
    
    $stmt->bind_param($types, ...$values);
    
    if ($stmt->execute()) {
        echo $conn->insert_id; // Sukses, return ID baru
    } else {
        echo json_encode(['error' => $stmt->error]);
    }
    $stmt->close();
}

// --- FUNGSI UPDATE (RUBAH) ---
if ($action === 'rubahjson') {
    $table = $_POST['table'];
    $id = intval($_POST['id']);
    
    $data = $_POST;
    // Hapus field sistem
    $ignoredKeys = ['action', 'table', 'id', 'ff', 'xbrand', 'xcab'];
    foreach($ignoredKeys as $key) {
        unset($data[$key]);
    }
    
    if (empty($data)) {
        echo json_encode(['error' => 'No data to update']);
        exit;
    }

    $updateParts = [];
    $values = [];
    $types = '';

    foreach ($data as $key => $value) {
        $updateParts[] = "`$key` = ?"; // Gunakan backtick
        $values[] = $value;
        
        if (is_int($value)) $types .= 'i';
        elseif (is_float($value)) $types .= 'd';
        else $types .= 's';
    }

    // Tambahkan ID di akhir untuk WHERE
    $values[] = $id;
    $types .= 'i';

    $sql = "UPDATE `$table` SET " . implode(', ', $updateParts) . " WHERE id = ?";
    
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['error' => 'Prepare failed: ' . $conn->error]);
        exit;
    }

    $stmt->bind_param($types, ...$values);
    
    if ($stmt->execute()) {
        echo 1; // Sukses
    } else {
        echo json_encode(['error' => $stmt->error]);
    }
    $stmt->close();
}

// --- FUNGSI DELETE (HAPUS) ---
if ($action === 'hapus') {
    $table = $_POST['table'];
    $idField = $_POST['idField'];
    $idValue = $_POST['idValue'];

    $sql = "DELETE FROM `$table` WHERE `$idField` = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $idValue); // Asumsikan ID string/int aman pakai 's'

    if ($stmt->execute()) {
        echo 1;
    } else {
        echo json_encode(['error' => $stmt->error]);
    }
    $stmt->close();
}

// --- FUNGSI READ (SELECT) ---
if ($action === 'ambil_select' || $action === 'yambil_select') {
    $sql = $_POST['sql'];
    
    // Basic security check
    $dangerous = ['DROP', 'TRUNCATE', 'ALTER'];
    foreach($dangerous as $word) {
        if (stripos($sql, $word) !== false) {
            echo json_encode(['error' => 'Query blocked security reason']);
            exit;
        }
    }

    $result = $conn->query($sql);
    $data = [];
    if ($result) {
        while ($row = $result->fetch_assoc()) {
            $data[] = $row;
        }
    }
    echo json_encode($data);
}

// --- FUNGSI READ SPESIFIK (AMBIL) ---
if ($action === 'ambil') {
    $table = $_POST['table'];
    $field = $_POST['field'];
    $val = $_POST['value'];
    
    $val1 = $val[0];
    $val2 = isset($val[1]) ? $val[1] : $val1;

    $sql = "SELECT * FROM `$table` WHERE `$field` BETWEEN ? AND ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ss", $val1, $val2);
    $stmt->execute();
    $res = $stmt->get_result();
    
    $data = [];
    while ($row = $res->fetch_assoc()) {
        $data[] = $row;
    }
    echo json_encode($data);
    $stmt->close();
}

$conn->close();
?>