<?php
// crud2.php
header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Pastikan file config.php ada di direktori yang benar
// require 'config.php';

// Fungsi helper untuk keamanan nama kolom
function escapeColumnName($column) {
    $reservedWords = ['group', 'left', 'right', 'top', 'bottom', 'order', 'table', 'select', 'delete', 'insert', 'update', 'default', 'user'];
    if (in_array(strtolower($column), $reservedWords)) {
        return "`" . $column . "`";
    }
    // Sanitasi dasar untuk mencegah karakter yang tidak diinginkan
    return preg_replace('/[^a-zA-Z0-9_]/', '', $column);
}
include_once '../data.php';
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    error_log("Connection failed: " . $conn->connect_error);
    echo json_encode(['success' => false, 'error' => 'Connection failed: ' . $conn->connect_error]);
    exit();
}

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

if ($action === 'ambil') {
    $table = $_POST['table'] ?? '';
    $field = $_POST['field'] ?? 'id';
    $valuePost = $_POST['value'] ?? [];
    $value1 = $valuePost[0] ?? '';
    $value2 = $valuePost[1] ?? $value1;
    $xbrand = $_POST['xbrand'] ?? '';
    $xcab = $_POST['xcab'] ?? '';
    $noFilter = $_POST['noFilter'] ?? 'false';

    if (empty($table)) {
        echo json_encode(['success' => false, 'error' => 'Parameter tabel untuk ambil tidak lengkap.']);
        $conn->close();
        exit();
    }

    $escapedField = escapeColumnName($field);
    $sql = "SELECT * FROM `" . $conn->real_escape_string($table) . "`";
    $conditions = [];
    $types = '';
    $params_to_bind = [];

    // Filter berdasarkan brand dan cab jika bukan tabel sistem
    if ($noFilter !== 'true' && $xcab !== 'yyy' && $table !== 'menus' && $table !== 'menugroups' && $table !== 'config') {
        if (!empty($xbrand) && $xbrand !== 'zzz') {
            $conditions[] = "brand = ?";
            $types .= 's';
            $params_to_bind[] = $xbrand;
        }
        if (!empty($xcab)) {
            $conditions[] = "cab = ?";
            $types .= 's';
            $params_to_bind[] = $xcab;
        }
    }

    // Filter utama berdasarkan field dan value
    if ($value1 !== '') {
        if ($value1 === $value2 || $value2 === '') {
            $conditions[] = $escapedField . " = ?";
            $types .= 's';
            $params_to_bind[] = $value1;
        } else {
            $conditions[] = $escapedField . " >= ?";
            $conditions[] = $escapedField . " <= ?";
            $types .= 'ss';
            $params_to_bind[] = $value1;
            $params_to_bind[] = $value2;
        }
    }

    if (!empty($conditions)) {
        $sql .= " WHERE " . implode(' AND ', $conditions);
    }

    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        error_log("Query error in ambil (prepare): " . $conn->error . " SQL: " . $sql);
        echo json_encode(['success' => false, 'error' => 'Prepare statement error: ' . $conn->error, 'sql' => $sql]);
    } else {
        if (!empty($params_to_bind)) {
            $stmt->bind_param($types, ...$params_to_bind);
        }
        $stmt->execute();
        $result = $stmt->get_result();
        if ($result === false) {
            error_log("Query error in ambil (execute): " . $stmt->error . " SQL: " . $sql);
            echo json_encode(['success' => false, 'error' => 'Execute statement error: ' . $stmt->error, 'sql' => $sql]);
        } else {
            $rows = [];
            while ($row = $result->fetch_assoc()) {
                $rows[] = $row;
            }
            echo json_encode($rows);
        }
        $stmt->close();
    }
} else {
    echo json_encode(['success' => false, 'error' => 'Invalid or no action specified for crud2.php']);
}

$conn->close();
?>