<?php
// /patient_dashboard.php
// VERSIÓN LIMPIA Y REFACTORIZADA CON MEJORAS EN BANNERS

// --- 1. GESTIÓN DE SESIÓN Y DEPENDENCIAS ---
session_start();
if (!isset($_SESSION['user_id'])) {
    header('Location: index.php');
    exit;
}
if ($_SESSION['user_rol'] !== 'paciente') {
    header('Location: dashboard.php');
    exit;
}

require 'db.php';
$patient_id = $_SESSION['user_id'];
$patient_name = $_SESSION['user_nombre'] ?? 'Pacient';

// --- LÓGICA PARA LAS ALERTAS DE TRATAMIENTOS (SE EJECUTA EN LA CARGA INICIAL) ---

// Alerta 1: Tratamientos que finalizan en los próximos 3 días
// *** MODIFICADO: Seleccionar id y title, usar FETCH_KEY_PAIR ***
$stmt_ending = $db->prepare("
    SELECT id, title
    FROM tratamientos
    WHERE paciente_id = :pacient_id
      AND status = 'En curs'
      AND end_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 3 DAY)
");
$stmt_ending->execute([':pacient_id' => $patient_id]);
$treatments_ending_soon = $stmt_ending->fetchAll(PDO::FETCH_KEY_PAIR); // Obtiene [id => title]

// Alerta 2: Tratamiento programado que se inicia en las próximas 48 horas (inminente)
$imminent_treatment = null;
$days_to_start = null;
$today = date('Y-m-d H:i:s');
$forty_eight_hours_from_now = date('Y-m-d H:i:s', strtotime('+48 hours'));
$stmt_imminent = $db->prepare("
    SELECT title, start_date
    FROM tratamientos
    WHERE paciente_id = :pacient_id
    AND status = 'Programat'
    AND start_date > :today
    AND start_date <= :forty_eight_hours_from_now
    ORDER BY start_date ASC
    LIMIT 1
");
$stmt_imminent->execute([
    ':pacient_id' => $patient_id,
    ':today' => $today,
    ':forty_eight_hours_from_now' => $forty_eight_hours_from_now
]);
$imminent_treatment = $stmt_imminent->fetch();
if ($imminent_treatment) {
    try {
        $start_dt = new DateTime($imminent_treatment['start_date']);
        $now_dt = new DateTime();
        $interval = $now_dt->diff($start_dt);
        $hours_remaining = $interval->h + ($interval->days * 24) + ($interval->i / 60);
        $days_to_start = ceil($hours_remaining / 24);
        $days_to_start = max(1, $days_to_start);
    } catch (Exception $e) { $days_to_start = 1; }
}
// --- FIN LÓGICA PARA LAS ALERTAS ---


// --- 3. RENDERIZADO HTML PRINCIPAL ---
$page_title = "El Meu Portal - AVANT ONLINE";
include 'partials/header_patient.php';
// *** AÑADIDO: data-patient-id en body ***
?>
<body data-patient-id="<?= htmlspecialchars($patient_id) // Para pasar el ID a JS ?>">

<main class="main-content container mt-4">

    <div id="dashboard-announcements" class="mb-4">
        <!-- Los anuncios se cargarán aquí vía JS -->
    </div>
    <div id="alerts-container">
        <?php
        // *** MODIFICADO: Banner amarillo con data-attributes ***
        if (!empty($treatments_ending_soon)):
            $ending_ids_string = htmlspecialchars(implode(',', array_keys($treatments_ending_soon)));
            $ending_titles_string = htmlspecialchars(implode(', ', array_values($treatments_ending_soon)));
        ?>
            <div class="alert alert-warning alert-dismissible fade show" role="alert"
                 data-alert-type="treatment-ending"
                 data-treatment-ids="<?= $ending_ids_string // <-- IDs aquí ?>">
                <i class="bi bi-calendar-x me-2"></i>
                <strong>Atenció:</strong> El teu tractament "<?= $ending_titles_string // <-- Títulos aquí ?>" finalitza aviat. Recorda completar els teus exercicis.
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (!empty($imminent_treatment)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert" id="imminent-treatment-alert">
                <i class="bi bi-clock me-2"></i>
                **A punt de començar!** El teu nou tractament "**<?= htmlspecialchars($imminent_treatment['title']) ?>**" s'activarà en <?= $days_to_start ?> di<?= $days_to_start == 1 ? 'a' : 'es' ?> pròxims.
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php // *** MODIFICADO: Banner azul con IDs y d-none, sin texto inicial *** ?>
        <div id="daily-exercises-banner" class="alert alert-info alert-dismissible fade show d-none" role="alert">
             <!-- El contenido se generará con JS -->
             <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    </div>

    <div id="widgets-container" class="row mb-4 g-3">
        <div class="col-12 text-center p-4">
             <div class="spinner-border spinner-border-sm text-secondary" role="status">
                 <span class="visually-hidden">Carregant resum...</span>
             </div>
        </div>
    </div>

    <div class="card card-body shadow-sm mb-4 d-none" id="main-content-card">

      <div class="d-flex justify-content-between align-items-start mb-2">
                 <div>
                     <h1 class="h3 mb-1" id="main-title">Carregant...</h1>
                     <div id="treatment-info" class="text-start mb-2"></div>
                     </div>
                 <div id="treatment-selector-container" style="display: none; min-width: 250px;">
                        <label for="treatmentSelector" class="form-label fw-bold small">Tractament Actiu:</label>
                        <select id="treatmentSelector" class="form-select form-select"></select>
                 </div>
           </div>

        <div id="calendar-container" class="d-none flex-column mt-3">
             <div id="calendar-controls" class="mb-3">
                     <div class="d-flex align-items-center">
                         <button class="btn btn-sm btn-link text-muted" id="prev-month-btn" title="Mes Anterior"><i class="bi bi-chevron-double-left"></i></button>
                         <h2 class="h5 mb-0 mx-2" id="month-display"></h2>
                         <button class="btn btn-sm btn-link text-muted" id="next-month-btn" title="Mes Següent"><i class="bi bi-chevron-double-right"></i></button>
                     </div>
                     <div class="btn-group">
                         <button class="btn btn-sm btn-secondary view-toggle-btn active">Setmanal</button>
                         <button class="btn btn-sm btn-secondary view-toggle-btn">Mensual</button>
                         <button class="btn btn-sm today-btn ms-3" id="today-btn">Anar a Hui</button>
                     </div>
            </div>
            <div id="week-carousel-container" class="d-flex flex-column">
                             <div id="day-carousel-wrapper" class="flex-grow-1">
                                 <div id="day-carousel" class="d-flex"></div>
                             </div>
                             <div class="d-flex justify-content-between mt-2">
                                 <button class="btn btn-sm btn-outline-secondary" id="prev-week-btn" title="Setmana Anterior"><i class="bi bi-chevron-left"></i></button>
                                 <button class="btn btn-sm btn-outline-secondary" id="next-week-btn" title="Setmana Següent"><i class="bi bi-chevron-right"></i></button>
                             </div>
                         </div>

             <div id="month-calendar-wrapper" class="d-none"></div>
        </div>

        <div class="mt-4"> <p class="text-end">
                <button class="btn btn-outline-primary btn-sm" type="button" data-bs-toggle="collapse" data-bs-target="#progressCollapse" aria-expanded="false" aria-controls="progressCollapse">
                    <i class="bi bi-graph-up me-2"></i> Mostrar el meu Progrés
                </button>
            </p>
            <div class="collapse" id="progressCollapse">
                <div id="progress-bars-container" class="mb-4" style="max-width: 500px;">
                    <!-- Barras de progreso se cargarán aquí -->
                </div>

                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5 class="mb-0">Evolució del Tractament</h5>
                    <div style="max-width: 300px;">
                        <select id="chart-exercise-filter" class="form-select form-select-sm">
                            <option value="0">Evolució General</option>
                            <!-- Opciones de filtro se cargarán aquí -->
                        </select>
                    </div>
                </div>
                <div class="mb-4">
                    <h6>Nivell de Dolor i Esforç Percebut (0-5)</h6>
                    <div style="height: 300px;"><canvas id="progressChart"></canvas></div>
                </div>
                 <div id="chart-comments" class="mt-4 small border-top pt-3" style="max-height: 150px; overflow-y: auto;">
                    <h6>Comentaris Registrats:</h6>
                    <ul class="list-unstyled"></ul>
                 </div>
            </div>
        </div>

    </div>

    <h4 class="h5 mb-3 d-none" id="exercises-title">Exercicis per a Hui</h4>

    <div id="daily-exercises-container" class="card card-body mb-4 d-none">
        <?php if (!empty($imminent_treatment)): ?>
            <p class="text-center text-muted p-5">
                <i class="bi bi-hourglass-split me-2"></i>
                El teu nou tractament s'iniciarà en els **<?= $days_to_start ?> di<?= $days_to_start == 1 ? 'a' : 'es' ?>** pròxims. Torna llavors per veure els teus exercicis!
            </p>
        <?php else: ?>
            <div class="text-center p-5"><div class="spinner-border text-primary"></div></div>
        <?php endif; ?>
    </div>

</main>

<?php
// --- ARCHIVOS INCLUIDOS ANTES DEL FOOTER ---

// 2. Incluye el footer estándar
include 'partials/footer.php';
?>

<?php // *** Script para pasar el ID del paciente a JS de forma segura *** ?>
<script>
    // Define una constante global JS antes de cargar el script principal
    const GLOBAL_PATIENT_ID = <?= json_encode($patient_id) ?>;
</script>

<script src="patient_dashboard.js?v=1.2"></script> <?php // Incrementa versión para evitar caché ?>

</body>
</html>
