<?php
// Evitar cualquier output antes de los headers
ob_start();

require_once '../auth.php';
require_once '../config.php';
checkLogin();

// Verificar que sea admin
if (($_SESSION['role'] ?? '') !== 'admin') {
    ob_end_clean();
    die("Acceso denegado.");
}

$buque_id = $_GET['buque_id'] ?? '';
$year = $_GET['year'] ?? date('Y');
$month = $_GET['month'] ?? date('m');

if (!$buque_id) {
    ob_end_clean();
    die("Falta ID de buque");
}

$pdo = getDBConnection();

if (!$pdo) {
    ob_end_clean();
    die("Error de conexión a la base de datos");
}

// Obtener información del buque
$stmtShip = $pdo->prepare("SELECT name, max_temp, min_temp FROM ships WHERE ship_id = :id");
$stmtShip->execute([':id' => $buque_id]);
$shipData = $stmtShip->fetch(PDO::FETCH_ASSOC);

if (!$shipData) {
    die("Buque no encontrado");
}

$shipName = $shipData['name'];
$maxTemp = (float) $shipData['max_temp'];
$minTemp = (float) ($shipData['min_temp'] ?? 0.0);

// Obtener labels de sensores
$sensorLabels = [];
for ($i = 1; $i <= 14; $i++)
    $sensorLabels[$i] = "Sensor $i";

try {
    $stmtL = $pdo->prepare("SELECT sensor_id, label FROM sensor_positions WHERE buque_id = :buque ORDER BY sensor_id ASC");
    $stmtL->execute([':buque' => $buque_id]);
    while ($row = $stmtL->fetch(PDO::FETCH_ASSOC)) {
        if (!empty($row['label'])) {
            $sensorLabels[(int) $row['sensor_id']] = $row['label'];
        }
    }
} catch (PDOException $e) { /* Ignore */ }

// Calcular rango de fechas del mes
$startDate = "$year-$month-01 00:00:00";
$endDate = date("$year-$month-t 23:59:59", strtotime($startDate));

// Obtener datos del mes
$stmt = $pdo->prepare("SELECT * FROM mediciones WHERE buque_id = :buque AND fecha BETWEEN :start AND :end ORDER BY fecha ASC");
$stmt->execute([
    ':buque' => $buque_id,
    ':start' => $startDate,
    ':end' => $endDate
]);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Generar nombre del archivo
$monthNames = [
    1 => 'Enero', 2 => 'Febrero', 3 => 'Marzo', 4 => 'Abril',
    5 => 'Mayo', 6 => 'Junio', 7 => 'Julio', 8 => 'Agosto',
    9 => 'Septiembre', 10 => 'Octubre', 11 => 'Noviembre', 12 => 'Diciembre'
];
$monthName = $monthNames[(int)$month] ?? date('F', strtotime($startDate));
$safeShipName = preg_replace('/[^a-zA-Z0-9_-]/', '_', $shipName);
$filename = "Reporte_Mensual_" . $safeShipName . "_" . $monthName . "_" . $year . ".xls";

// Limpiar cualquier salida previa
ob_end_clean();

// Enviar headers para forzar descarga
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Pragma: no-cache');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

echo "\xEF\xBB\xBF"; // UTF-8 BOM
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: Arial, sans-serif; font-size: 12px; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #cccccc; padding: 8px; text-align: center; vertical-align: middle; }
        .header-main { background-color: #2c3e50; color: #ffffff; font-size: 16px; font-weight: bold; text-align: left; }
        .header-sub { background-color: #ecf0f1; color: #333333; font-weight: bold; text-align: left; }
        .col-header { background-color: #34495e; color: #ffffff; font-weight: bold; }
        .date-col { mso-number-format: "dd\/mm\/yyyy hh\:mm"; text-align: center; }
        .ip-col { text-align: left; color: #7f8c8d; font-size: 11px; }
        .temp-cell { mso-number-format: "0.00"; }
        .alert-high { background-color: #ffcccc; color: #c0392b; font-weight: bold; }
    </style>
</head>
<body>
    <table>
        <tr>
            <td colspan="16" class="header-main">REPORTE MENSUAL - TECNOTRACK MARINE</td>
        </tr>
        <tr>
            <td colspan="16" class="header-sub">
                <strong>Buque:</strong> <?php echo htmlspecialchars($shipName); ?> |
                <strong>Período:</strong> <?php echo date('F Y', strtotime($startDate)); ?> |
                <strong>Umbral Alerta:</strong> <?php echo number_format($maxTemp, 1); ?>°C
            </td>
        </tr>
        <tr>
            <td colspan="16" class="header-sub">
                <strong>Rango:</strong> <?php echo date('d/m/Y', strtotime($startDate)); ?> - <?php echo date('d/m/Y', strtotime($endDate)); ?> |
                <strong>Total Registros:</strong> <?php echo count($rows); ?> |
                <strong>Generado:</strong> <?php echo date('d/m/Y H:i'); ?>
            </td>
        </tr>
        <tr><td colspan="16" style="height: 10px; border: none;"></td></tr>
        <tr>
            <th class="col-header">ID</th>
            <th class="col-header">FECHA REGISTRO</th>
            <th class="col-header">IP ORIGEN</th>
            <?php foreach ($sensorLabels as $id => $label): ?>
                <th class="col-header" style="min-width: 80px; vertical-align: top;">
                    Sensor <?php echo $id; ?><br>
                    <span style="font-size: 0.9em; font-weight: normal;"><?php echo htmlspecialchars($label); ?></span>
                </th>
            <?php endforeach; ?>
        </tr>
        <?php foreach ($rows as $row): ?>
            <tr>
                <td><?php echo $row['id']; ?></td>
                <td class="date-col"><?php echo date('d/m/Y H:i', strtotime($row['fecha'])); ?></td>
                <td class="ip-col"><?php echo htmlspecialchars($row['ip'] ?? ''); ?></td>
                <?php for ($i = 1; $i <= 14; $i++):
                    $val = $row["temp$i"];
                    $numVal = is_numeric($val) ? (float) $val : null;
                    $class = "temp-cell";
                    if ($numVal !== null && ($numVal >= $maxTemp || $numVal < $minTemp)) {
                        $class .= " alert-high";
                    }
                    ?>
                    <td class="<?php echo $class; ?>">
                        <?php echo ($numVal !== null) ? number_format($numVal, 2, ',', '.') : ''; ?>
                    </td>
                <?php endfor; ?>
            </tr>
        <?php endforeach; ?>
    </table>
</body>
</html>

