<?php
require '../../backend/bd/Conexion.php';

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

// Campos disponibles para validación
$available_fields = [
    'sex', 'modalidad', 'tsudadera', 'tchaqueta', 'tzapatos', 
    'ecivil', 'zona', 'sisben', 'pensionado', 'vivecon',
    'poblaciond', 'educacion', 'leerut', 'tecnologia', 'grup'
];

// Obtener campos seleccionados
$modalidad = isset($_GET['modalidad']) ? $_GET['modalidad'] : 'all';
$field2 = isset($_GET['field2']) ? $_GET['field2'] : null;

// Validar campo secundario
if ($field2 && $field2 !== 'none' && !in_array($field2, $available_fields)) {
    echo json_encode(['error' => 'Campo inválido']);
    exit;
}

try {
    // Construir condición WHERE para modalidad
    $whereModalidad = '';
    if ($modalidad !== 'all') {
        $whereModalidad = " AND modalidad = :modalidad";
    }
    
    // Si hay campo secundario, hacer análisis cruzado
    if ($field2 && $field2 !== 'none') {
        // Consulta para análisis cruzado
        $query = "SELECT 
                    modalidad as campo1, 
                    `$field2` as campo2, 
                    COUNT(*) as cantidad 
                 FROM patients 
                 WHERE modalidad IS NOT NULL AND modalidad <> ''
                   AND `$field2` IS NOT NULL AND `$field2` <> ''
                   $whereModalidad
                 GROUP BY modalidad, `$field2` 
                 ORDER BY modalidad, `$field2`";
        
        $stmt = $connect->prepare($query);
        if ($modalidad !== 'all') {
            $stmt->bindParam(':modalidad', $modalidad, PDO::PARAM_STR);
        }
        $stmt->execute();
        
        $crossData = [];
        $field1Values = [];
        $field2Values = [];
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $val1 = empty($row['campo1']) ? 'No especificado' : $row['campo1'];
            $val2 = empty($row['campo2']) ? 'No especificado' : $row['campo2'];
            
            if (!in_array($val1, $field1Values)) {
                $field1Values[] = $val1;
            }
            if (!in_array($val2, $field2Values)) {
                $field2Values[] = $val2;
            }
            
            if (!isset($crossData[$val1])) {
                $crossData[$val1] = [];
            }
            $crossData[$val1][$val2] = $row['cantidad'];
        }
        
        // Construir matriz completa con ceros donde no hay datos
        $matrix = [];
        foreach ($field1Values as $val1) {
            $row = ['label' => $val1];
            foreach ($field2Values as $val2) {
                $row[$val2] = isset($crossData[$val1][$val2]) ? $crossData[$val1][$val2] : 0;
            }
            $matrix[] = $row;
        }
        
        echo json_encode([
            'type' => 'cross',
            'field1Values' => $field1Values,
            'field2Values' => $field2Values,
            'matrix' => $matrix,
            'crossData' => $crossData
        ]);
        
    } else {
        // Consulta simple para modalidad
        $query = "SELECT 
                    modalidad as campo, 
                    COUNT(*) as cantidad 
                 FROM patients 
                 WHERE modalidad IS NOT NULL AND modalidad <> ''
                   $whereModalidad
                 GROUP BY modalidad 
                 ORDER BY cantidad DESC";
        
        $stmt = $connect->prepare($query);
        if ($modalidad !== 'all') {
            $stmt->bindParam(':modalidad', $modalidad, PDO::PARAM_STR);
        }
        $stmt->execute();
        
        $labels = [];
        $values = [];
        $data = [];
        
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $campo = empty($row['campo']) ? 'No especificado' : $row['campo'];
            $labels[] = $campo;
            $values[] = (int)$row['cantidad'];
            $data[] = [
                'campo' => $campo,
                'cantidad' => (int)$row['cantidad']
            ];
        }
        
        echo json_encode([
            'type' => 'simple',
            'labels' => $labels,
            'values' => $values,
            'data' => $data,
            'modalidad' => $modalidad
        ]);
    }
    
} catch (PDOException $e) {
    echo json_encode(['error' => 'Error en la base de datos: ' . $e->getMessage()]);
}
?>