<?php
session_start();
require_once 'config/config.php';
require_once 'includes/functions.php';
require_once 'includes/orthanc-api.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

// Set default date range (today)
$endDate = date('Y-m-d');
$startDate = date('Y-m-d');

// Handle date filter form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $startDate = sanitizeInput($_POST['start_date']);
    $endDate = sanitizeInput($_POST['end_date']);
}

// Get studies from Orthanc
$estudios = [];
$mensajeError = "";

// Convert dates to Orthanc format (YYYYMMDD)
$startDateOrthanc = str_replace('-', '', $startDate);
$endDateOrthanc = str_replace('-', '', $endDate);

// Build the query data
$data = [
    'Level' => 'Study',
    'Expand' => true,
    'Query' => [
        'StudyDate' => $startDateOrthanc . '-' . $endDateOrthanc
    ]
];

// Initialize cURL
$ch = curl_init(ORTHANC_HOST . 'tools/find');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_USERPWD, ORTHANC_USERNAME . ":" . ORTHANC_PASSWORD);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode !== 200) {
    $mensajeError = "Error al obtener los estudios: " . $httpCode;
} else {
    $studies = json_decode($response, true);
    
    if (json_last_error() !== JSON_ERROR_NONE) {
        $mensajeError = "Error al decodificar la respuesta JSON";
    } else {
        // Get detailed information for each study
        foreach ($studies as $study) {
            // Obtener detalles del estudio
            $studyDetails = getStudyDetails($study);
            
            // Si no hay error y el estudio tiene los datos necesarios, lo agregamos
            if (!isset($studyDetails['error']) && 
                isset($studyDetails['MainDicomTags']) && 
                isset($studyDetails['PatientMainDicomTags'])) {
                $estudios[] = $studyDetails;
            }
        }
    }
}

curl_close($ch);

// Almacenar autenticación en la sesión para que los scripts la usen
$_SESSION['is_authenticated'] = true;
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Estudios - Portal de Imágenes</title>
    <link rel="stylesheet" href="css/styles.css">
</head>
<body>
    <div class="container">
        <div class="header">
            <img src="images/imac_logo.png" alt="IMAC Tucumán" class="header-logo">
            <div class="user-info">
                Bienvenido, <?php echo sanitizeInput($_SESSION['full_name']); ?>
                <a href="logout.php" class="logout-btn">Cerrar Sesión</a>
            </div>
        </div>

        <div class="filter-container">
            <form method="post" class="date-filter-form">
                <div class="form-group">
                    <label for="start_date">Fecha Inicio:</label>
                    <input type="date" id="start_date" name="start_date" value="<?php echo $startDate; ?>" required>
                </div>
                <div class="form-group">
                    <label for="end_date">Fecha Fin:</label>
                    <input type="date" id="end_date" name="end_date" value="<?php echo $endDate; ?>" required>
                </div>
                <button type="submit" class="filter-btn">Filtrar</button>
            </form>
        </div>

        <?php if (!empty($mensajeError)): ?>
        <div class="error-message">
            <?php echo $mensajeError; ?>
        </div>
        <?php endif; ?>

        <div class="estudios-container">
            <?php if (empty($estudios)): ?>
                <p>No se encontraron estudios en el período seleccionado.</p>
            <?php else: ?>
                <!-- Vista móvil -->
                <div class="mobile-cards-container">
                    <?php foreach ($estudios as $estudio): 
                        $mainTags = $estudio['MainDicomTags'] ?? [];
                        $studyDate = $mainTags['StudyDate'] ?? '';
                        $studyDesc = $mainTags['StudyDescription'] ?? '';
                        $studyId = $estudio['ID'] ?? '';
                        $patientName = $estudio['PatientMainDicomTags']['PatientName'] ?? '';
                        $patientId = $estudio['PatientMainDicomTags']['PatientID'] ?? '';
                        
                        // Obtener la modalidad de la primera serie
                        $modality = getStudyMainModality($studyId);
                        
                        // Determinar si es un informe
                        $isReport = false;
                        if (stripos($studyDesc, 'INFORME') !== false || $modality === 'OT') {
                            $isReport = true;
                        }
                    ?>
                    <div class="estudio-card">
                        <div class="estudio-card-header">
                            <div class="estudio-card-title"><?php echo getTipoEstudio($modality); ?></div>
                            <div class="estudio-card-date"><?php echo formatStudyDate($studyDate); ?></div>
                        </div>
                        
                        <div class="estudio-card-details">
                            <div class="estudio-card-row">
                                <span class="estudio-card-label">Paciente:</span>
                                <span class="estudio-card-value"><?php echo sanitizeInput($patientName); ?></span>
                            </div>
                            <div class="estudio-card-row">
                                <span class="estudio-card-label">ID:</span>
                                <span class="estudio-card-value"><?php echo sanitizeInput($patientId); ?></span>
                            </div>
                            <?php if (!empty($studyDesc)): ?>
                            <div class="estudio-card-row">
                                <span class="estudio-card-label">Detalle:</span>
                                <span class="estudio-card-value estudio-desc-short">
                                    <?php 
                                    $shortDesc = (strlen($studyDesc) > 40) ? substr($studyDesc, 0, 37) . '...' : $studyDesc;
                                    echo sanitizeInput($shortDesc); 
                                    ?>
                                </span>
                            </div>
                            <?php if (strlen($studyDesc) > 40): ?>
                            <span class="description-toggle" data-target="desc-<?php echo $studyId; ?>">Ver más</span>
                            <div id="desc-<?php echo $studyId; ?>" class="estudio-card-description">
                                <?php echo sanitizeInput($studyDesc); ?>
                            </div>
                            <?php endif; ?>
                            <?php endif; ?>
                        </div>
                        
                        <div class="estudio-card-actions">
                            <?php if ($isReport): ?>
                            <button class="action-btn view-btn" 
                                    data-study-id="<?php echo $studyId; ?>"
                                    data-is-report="true">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                                <span class="btn-text">VISUALIZAR</span>
                            </button>
                            <button class="action-btn download-btn" 
                                    data-study-id="<?php echo $studyId; ?>"
                                    data-patient-name="<?php echo sanitizeInput($patientName); ?>"
                                    data-study-date="<?php echo $studyDate; ?>"
                                    data-is-report="true"
                                    data-user-type="medico">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                                    <polyline points="7 10 12 15 17 10"></polyline>
                                    <line x1="12" y1="15" x2="12" y2="3"></line>
                                </svg>
                                <span class="btn-text">DESCARGAR</span>
                            </button>
                            <?php else: ?>
                            <button class="action-btn view-btn" 
                                    data-study-id="<?php echo $studyId; ?>"
                                    data-is-report="false">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                                    <circle cx="12" cy="12" r="3"></circle>
                                </svg>
                                <span class="btn-text">VISUALIZAR</span>
                            </button>
                            <a href="<?php echo ORTHANC_PUBLIC_HOST; ?>/studies/<?php echo $studyId; ?>/archive?filename=estudio-<?php echo date('d-m-Y', strtotime($studyDate)); ?>_<?php echo str_replace(' ', '', sanitizeInput($patientName)); ?>.zip" 
                               class="action-btn download-btn" 
                               target="_blank">
                                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                                    <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path>
                                    <polyline points="7 10 12 15 17 10"></polyline>
                                    <line x1="12" y1="15" x2="12" y2="3"></line>
                                </svg>
                                <span class="btn-text">DESCARGAR</span>
                            </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>

                <!-- Vista desktop -->
                <div class="table-responsive desktop-view">
                    <table class="estudios-table">
                        <thead>
                            <tr>
                                <th>Fecha</th>
                                <th>Paciente</th>
                                <th>ID</th>
                                <th>Tipo de Estudio</th>
                                <th>Descripción</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($estudios as $estudio): 
                                $mainTags = $estudio['MainDicomTags'] ?? [];
                                $studyDate = $mainTags['StudyDate'] ?? '';
                                $studyDesc = $mainTags['StudyDescription'] ?? '';
                                $studyId = $estudio['ID'] ?? '';
                                $patientName = $estudio['PatientMainDicomTags']['PatientName'] ?? '';
                                $patientId = $estudio['PatientMainDicomTags']['PatientID'] ?? '';
                                
                                // Obtener la modalidad de la primera serie
                                $modality = getStudyMainModality($studyId);
                                
                                // Determinar si es un informe
                                $isReport = false;
                                if (stripos($studyDesc, 'INFORME') !== false || $modality === 'OT') {
                                    $isReport = true;
                                }
                            ?>
                            <tr>
                                <td><?php echo formatStudyDate($studyDate); ?></td>
                                <td><?php echo sanitizeInput($patientName); ?></td>
                                <td><?php echo sanitizeInput($patientId); ?></td>
                                <td><?php echo getTipoEstudio($modality); ?></td>
                                <td><?php echo sanitizeInput($studyDesc); ?></td>
                                <td>
                                    <?php if ($isReport): ?>
                                    <button class="action-btn view-btn" 
                                            data-study-id="<?php echo $studyId; ?>"
                                            data-is-report="true">
                                        <span class="btn-icon">👁️</span>
                                        <span class="btn-text">VISUALIZAR</span>
                                    </button>
                                    <button class="action-btn download-btn" 
                                            data-study-id="<?php echo $studyId; ?>"
                                            data-patient-name="<?php echo sanitizeInput($patientName); ?>"
                                            data-study-date="<?php echo $studyDate; ?>"
                                            data-is-report="true"
                                            data-user-type="medico">
                                        <span class="btn-icon">⬇️</span>
                                        <span class="btn-text">DESCARGAR</span>
                                    </button>
                                    <?php else: ?>
                                    <button class="action-btn view-btn" 
                                            data-study-id="<?php echo $studyId; ?>"
                                            data-is-report="false">
                                        <span class="btn-icon">👁️</span>
                                        <span class="btn-text">VISUALIZAR</span>
                                    </button>
                                    <a href="<?php echo ORTHANC_PUBLIC_HOST; ?>/studies/<?php echo $studyId; ?>/archive?filename=estudio-<?php echo date('d-m-Y', strtotime($studyDate)); ?>_<?php echo str_replace(' ', '', sanitizeInput($patientName)); ?>.zip" 
                                       class="action-btn download-btn" 
                                       target="_blank">
                                        <span class="btn-icon">⬇️</span>
                                        <span class="btn-text">DESCARGAR</span>
                                    </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
    
    <script>
        // Definir variables globales para JavaScript
        const ORTHANC_PUBLIC_HOST = '<?php echo ORTHANC_PUBLIC_HOST; ?>';
        const IS_AUTHENTICATED = true;
        const USER_TYPE = 'medico';
    </script>
    <script src="js/main.js"></script>
    
    <script>
    // Script adicional para asegurar que la descarga funcione correctamente
    document.addEventListener('DOMContentLoaded', function() {
        const downloadButtons = document.querySelectorAll('.download-btn');
        
        downloadButtons.forEach(button => {
            button.addEventListener('click', function(e) {
                e.preventDefault();
                
                const studyId = this.getAttribute('data-study-id');
                const patientName = this.getAttribute('data-patient-name');
                const studyDate = this.getAttribute('data-study-date');
                const isReport = this.getAttribute('data-is-report') === 'true';
                
                // Si es un informe, usamos download-report.php
                if (isReport) {
                    window.location.href = `download-report.php?study_id=${studyId}&auth=true`;
                } else {
                    // Si es un estudio normal, usamos download.php
                    window.location.href = `download.php?study_id=${studyId}&patient_name=${encodeURIComponent(patientName)}&study_date=${studyDate}&auth=true`;
                }
            });
        });
    });
    </script>
</body>
</html>