<?php
require_once 'db/config.php';

$data = json_decode(file_get_contents('php://input'), true);

if ($data) {
    $fecha = $data['fecha'];
    $provincia = $data['provincia'];
    $columna = $data['columna'];
    $valor = $data['valor'];

    // Robustness: Ensure 'monto' is always numeric.
    if ($columna === 'monto') {
        // If $valor is not a valid number (e.g., an empty string), default it to 0.
        if (!is_numeric($valor)) {
            $valor = 0;
        }
    }

    // Column name validation
    if ($columna === 'monto' || $columna === 'estado') {
        try {
            $pdo = db();
            $sql = "INSERT INTO liquidaciones_provincia (fecha, provincia, $columna) VALUES (:fecha, :provincia, :valor)
                    ON DUPLICATE KEY UPDATE $columna = :valor";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['fecha' => $fecha, 'provincia' => $provincia, 'valor' => $valor]);

            echo json_encode(['success' => true]);
        } catch (PDOException $e) {
            http_response_code(500);
            echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        }
    } else {
        http_response_code(400);
        echo json_encode(['success' => false, 'message' => 'Invalid column name.']);
    }
} else {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'No data received.']);
}
?>