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

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

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

    // Column name validation to prevent SQL injection
    $allowed_columns = [
        'bcp_yape', 'b_nacion', 'interbank', 'bbva', 'otros_ingresos',
        'tu1', 'tu2', 'tu3', 'fl1', 'fl2', 'fl3',
        'rc_envio', 'rc_contraent', 'total_inversion_publicitaria'
    ];

    if (in_array($columna, $allowed_columns)) {
        try {
            $pdo = db();
            // Use INSERT ... ON DUPLICATE KEY UPDATE to handle both new and existing rows
            $sql = "INSERT INTO flujo_caja (fecha, $columna) VALUES (:fecha, :valor)
                    ON DUPLICATE KEY UPDATE $columna = :valor";
            $stmt = $pdo->prepare($sql);
            $stmt->execute(['fecha' => $fecha, '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.']);
}
?>