<?php
    require_once('../../backend/bd/Conexion.php');

    // Debug para verificar datos recibidos
    error_log("POST data: " . print_r($_POST, true));

    // Función para limpiar valores (eliminar [object...] si existe)
    function cleanValue($value) {
        $value = trim($value ?? '');
        // Si contiene "[object", retornar vacío
        if (strpos($value, '[object') !== false) {
            error_log("Valor corrupto detectado: " . $value);
            return '';
        }
        return $value;
    }

    $consl1 = cleanValue($_POST['consl']);
    $csidpa1 = cleanValue($_POST['csidpa']);
    $csnopa1 = cleanValue($_POST['csnopa']);
    $CSV = cleanValue($_POST['CSV']);
    $CFC = cleanValue($_POST['CFC']);
    $CFR = cleanValue($_POST['CFR']);
    $CTMP = cleanValue($_POST['CTMP']);
    $CT = cleanValue($_POST['CT']);
    $CP = cleanValue($_POST['CP']);
    $CIMC = cleanValue($_POST['CIMC']);
    $CPA = cleanValue($_POST['CPA']);
    $CPC = cleanValue($_POST['CPC']);
    $CGL = cleanValue($_POST['CGL']);
    $CTV = cleanValue($_POST['CTV']);
    $CTA = cleanValue($_POST['CTA']);
    $CCB_CL = cleanValue($_POST['CCB_CL']);
    $CNEU = cleanValue($_POST['CNEU']);
    $CTRX = cleanValue($_POST['CTRX']);
    $CDOR = cleanValue($_POST['CDOR']);
    $CABD = cleanValue($_POST['CABD']);
    $CPIE = cleanValue($_POST['CPIE']);
    $CGUN = cleanValue($_POST['CGUN']);
    $CEXT = cleanValue($_POST['CEXT']);
    $CLIM = cleanValue($_POST['CLIM']);
    
////////////// Insertar a la tabla la informacion generada /////////

$sql = "INSERT INTO consult(
    mtcl, idpa, nompa, fere, SV, FC, FR, TMP, T, P, IMC, PA, PC, GL, TV, TA, 
    CB_CL, NEU, TRX, DOR, ABD, PIE, GUN, EXT, LIM, state
) VALUES (?, ?, ?, NOW(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

try {
    $stmt = $connect->prepare($sql);
    $result = $stmt->execute([
        $consl1, $csidpa1, $csnopa1, $CSV, $CFC, $CFR, $CTMP, $CT, $CP, $CIMC, $CPA, $CPC,
        $CGL, $CTV, $CTA, $CCB_CL, $CNEU, $CTRX, $CDOR, $CABD, $CPIE, $CGUN, $CEXT, $CLIM, 1
    ]);
    
    if($result) {
        error_log("Consulta guardada exitosamente para ID: " . $csidpa1);
        echo 'Agregado correctamente';
    } else {
        error_log("Error al guardar consulta: " . print_r($stmt->errorInfo(), true));
        echo 'Error al guardar';
    }
} catch(PDOException $e) {
    error_log("Excepción PDO: " . $e->getMessage());
    echo 'Error: ' . $e->getMessage();
}
?>
