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

require_once __DIR__ . '/../config/user_functions.php';
if (session_status() === PHP_SESSION_NONE) { session_start(); }
require_once __DIR__ . '/../config/users_local.php';

if (function_exists('user_has_permission') && !user_has_permission('settings')) {
    http_response_code(403);
    echo json_encode(['ok' => false, 'error' => 'Access denied']);
    exit;
}

require_once __DIR__ . '/../config/db_remote.php';

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

if ($action === 'ping') {
    echo json_encode(['ok' => true, 'message' => 'IBC AJAX online']);
    exit;
}

// Example: inline cell update
if ($action === 'update_cell') {
    $table = $_POST['table'] ?? '';
    $pkField = $_POST['pk_field'] ?? 'id';
    $pkValue = $_POST['pk_value'] ?? '';
    $field = $_POST['field'] ?? '';
    $value = $_POST['value'] ?? '';

    if (!preg_match('/^[A-Za-z0-9_]+$/', $table)
        || !preg_match('/^[A-Za-z0-9_]+$/', $pkField)
        || !preg_match('/^[A-Za-z0-9_]+$/', $field)) {
        echo json_encode(['ok' => false, 'error' => 'Invalid identifiers']);
        exit;
    }

    $pkValue = (int)$pkValue;
    $valEsc  = $mysqli->real_escape_string($value);
    $sql = "UPDATE `{$table}` SET `{$field}` = '{$valEsc}' WHERE `{$pkField}` = {$pkValue} LIMIT 1";
    $ok = $mysqli->query($sql);
    echo json_encode(['ok' => (bool)$ok]);
    exit;
}

echo json_encode(['ok' => false, 'error' => 'Unknown action']);
