File "guardar_ausentismo.php"

Full Path: C:/wamp64/www/casos_medicos/guardar_ausentismo.php
File size: 4.95 KB
MIME-type: text/x-php
Charset: utf-8

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

    // Función para leer archivo
    function leerArchivo($campo){
        return (isset($_FILES[$campo]) && $_FILES[$campo]['error']==0) 
            ? file_get_contents($_FILES[$campo]['tmp_name']) 
            : null;
    }

    // Función para obtener nombre
    function nombreArchivo($campo){
        return isset($_FILES[$campo]['name']) ? $_FILES[$campo]['name'] : null;
    }

// Campos obligatorios
$campos = ['cedula','nombre','ccosto','cargo','telefono','correo','tipo_incapacidad','eps','fecha_inicio','fecha_fin','dias'];
foreach($campos as $c){
    if(empty($_POST[$c])){
        echo json_encode(["ok"=>false,"msg"=>"Falta el campo: $c"]);
        exit;
    }
}

// Leer archivos
$certificado = leerArchivo('certificado'); 
$certificado_nombre = nombreArchivo('certificado');

$epicrisis = leerArchivo('epicrisis'); 
$epicrisis_nombre = nombreArchivo('epicrisis');

$furips = null; $furips_nombre = null;
$registro_civil = null; $registro_civil_nombre = null;

$tipo = $_POST['tipo_incapacidad'];

if($tipo=="Accidente de Tránsito"){
    $furips = leerArchivo('furips');
    $furips_nombre = nombreArchivo('furips');
}

if(in_array($tipo, ['Licencia de Maternidad','Licencia de Paternidad'])){
    $registro_civil = leerArchivo('registro_civil');
    $registro_civil_nombre = nombreArchivo('registro_civil');
}

try {
    
    $sql = "INSERT INTO ausentismo (
        cedula, nombre, ccosto, cargo, telefono, correo, tipo_incapacidad, eps, fecha_inicio, fecha_fin, dias,
        certificado, certificado_nombre, epicrisis, epicrisis_nombre, furips, furips_nombre, registro_civil, 
        registro_civil_nombre, fecha_registro)
         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,NOW())";

    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        throw new Exception("Error en prepare: " . $conn->error);
    }

    // PREPARAMOS LOS VALORES EN EL ORDEN EXACTO DE LOS ? EN LA CONSULTA
    $values = [
        $_POST['cedula'] ?? null,            // 1
        $_POST['nombre'] ?? null,            // 2
        $_POST['ccosto'] ?? null,            // 3
        $_POST['cargo'] ?? null,             // 4
        $_POST['telefono'] ?? null,          // 5
        $_POST['correo'] ?? null,            // 6
        $_POST['tipo_incapacidad'] ?? null,  // 7
        $_POST['eps'] ?? null,               // 8
        $_POST['fecha_inicio'] ?? null,      // 9
        $_POST['fecha_fin'] ?? null,         // 10
        isset($_POST['dias']) ? intval($_POST['dias']) : null, // 11 (i)
        $certificado,                        // 12 (BLOB o null)
        $certificado_nombre,                 // 13
        $epicrisis,                          // 14 (BLOB)
        $epicrisis_nombre,                   // 15
        $furips,                             // 16 (BLOB or null)
        $furips_nombre,                      // 17
        $registro_civil,                     // 18 (BLOB or null)
        $registro_civil_nombre               // 19
    ];

    // Verificación rápida: la consulta tiene N placeholders, los values deben ser N
    $placeholders = substr_count($sql, '?'); // debe ser 19
    if ($placeholders !== count($values)) {
        throw new Exception("Mismatch: placeholders=$placeholders pero valores=" . count($values));
    }

    // Construir la cadena de tipos automáticamente: 'i' para enteros, 's' para todo lo demás
    $types = '';
    foreach ($values as $v) {
        if (is_int($v)) {
            $types .= 'i';
        } else {
            // si es NULL o string o binary: 's' (tratar BLOBs como 's' suele funcionar)
            $types .= 's';
        }
    }

    // bind_param necesita argumentos por referencia en un array
    $bind_names[] = $types;
    for ($i = 0; $i < count($values); $i++) {
        // convertir a variable (necesario para referenciarlas)
        $bind_name = 'bind' . $i;
        $$bind_name = $values[$i];
        $bind_names[] = &$$bind_name; // referencia
    }

    // Ejecutar bind_param dinámicamente
    if (!call_user_func_array([$stmt, 'bind_param'], $bind_names)) {
        throw new Exception("bind_param falló: " . $stmt->error);
    }

    // Si los archivos son muy grandes podrías usar send_long_data, pero aquí
    // tratamos los BLOBs como strings directos en los valores; si quieres usar
    // send_long_data, habría que pasar NULL en bind y luego enviar con índices
    // correctos. Este enfoque evita errores de conteo.
    if ($stmt->execute()) {
        echo json_encode(["ok" => true, "msg" => "Registro guardado correctamente"]);
    } else {
        echo json_encode(["ok" => false, "msg" => "Error al guardar: " . $stmt->error]);
    }

    $stmt->close();
    $conn->close();

} catch (Exception $e) {
    echo json_encode(["ok" => false, "msg" => "Error interno: " . $e->getMessage()]);
}

?>