<?php
$pageTitle = 'Reporte Semanal';
require_once __DIR__ . '/../../config/config.php';
requireLogin();

if ($_SESSION['rol'] != 'admin') {
    showAlert('No tiene permisos para acceder a esta sección', 'danger');
    header('Location: ' . SITE_URL);
    exit;
}

$db = getDB();

// Obtener semana seleccionada o actual
$semana = $_GET['semana'] ?? date('Y-\WW');
$year = substr($semana, 0, 4);
$weekNum = substr($semana, 6, 2);

// Calcular fechas de inicio y fin de la semana
$dto = new DateTime();
$dto->setISODate($year, $weekNum);
$fechaInicio = $dto->format('Y-m-d');
$dto->modify('+6 days');
$fechaFin = $dto->format('Y-m-d');

// Estadísticas de la semana
$stmt = $db->prepare("SELECT COUNT(*) FROM ordenes WHERE DATE(fecha_orden) BETWEEN ? AND ?");
$stmt->execute([$fechaInicio, $fechaFin]);
$totalOrdenes = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COALESCE(SUM(total), 0) FROM ordenes WHERE DATE(fecha_orden) BETWEEN ? AND ?");
$stmt->execute([$fechaInicio, $fechaFin]);
$totalVentas = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COALESCE(SUM(monto), 0) FROM pagos WHERE DATE(fecha_pago) BETWEEN ? AND ?");
$stmt->execute([$fechaInicio, $fechaFin]);
$totalCobrado = $stmt->fetchColumn();

$stmt = $db->prepare("SELECT COUNT(*) FROM pacientes WHERE DATE(created_at) BETWEEN ? AND ?");
$stmt->execute([$fechaInicio, $fechaFin]);
$pacientesNuevos = $stmt->fetchColumn();

// Órdenes por día de la semana
$stmt = $db->prepare("
    SELECT DAYNAME(fecha_orden) as dia, DATE(fecha_orden) as fecha, COUNT(*) as total, SUM(total) as monto
    FROM ordenes 
    WHERE DATE(fecha_orden) BETWEEN ? AND ?
    GROUP BY DATE(fecha_orden)
    ORDER BY fecha_orden
");
$stmt->execute([$fechaInicio, $fechaFin]);
$ordenesPorDia = $stmt->fetchAll();

// Exámenes más solicitados de la semana
$stmt = $db->prepare("
    SELECT e.nombre, COUNT(od.id) as total
    FROM orden_detalle od
    JOIN examenes e ON od.examen_id = e.id
    JOIN ordenes o ON od.orden_id = o.id
    WHERE DATE(o.fecha_orden) BETWEEN ? AND ?
    GROUP BY e.id
    ORDER BY total DESC
    LIMIT 10
");
$stmt->execute([$fechaInicio, $fechaFin]);
$examenesTop = $stmt->fetchAll();

// Estado de las órdenes
$stmt = $db->prepare("
    SELECT estado, COUNT(*) as total
    FROM ordenes
    WHERE DATE(fecha_orden) BETWEEN ? AND ?
    GROUP BY estado
");
$stmt->execute([$fechaInicio, $fechaFin]);
$ordenesPorEstado = $stmt->fetchAll();

require_once __DIR__ . '/../../includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mt-4 mb-4">
    <h2><i class="bi bi-calendar-week"></i> Reporte Semanal</h2>
    <div class="d-flex gap-2 align-items-center">
        <form method="GET" class="d-flex gap-2">
            <input type="week" name="semana" class="form-control" value="<?= $semana ?>">
            <button type="submit" class="btn btn-primary">
                <i class="bi bi-search"></i>
            </button>
        </form>
        <button onclick="window.print()" class="btn btn-outline-secondary">
            <i class="bi bi-printer"></i>
        </button>
        <a href="index.php" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left"></i> Volver
        </a>
    </div>
</div>

<div class="alert alert-info">
    <i class="bi bi-calendar3"></i> Semana del <strong><?= formatDate($fechaInicio) ?></strong> al <strong><?= formatDate($fechaFin) ?></strong>
</div>

<!-- Tarjetas de resumen -->
<div class="row mb-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body text-center">
                <h6>Total Órdenes</h6>
                <h2><?= $totalOrdenes ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body text-center">
                <h6>Total Ventas</h6>
                <h2><?= formatMoney($totalVentas) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-info text-white">
            <div class="card-body text-center">
                <h6>Total Cobrado</h6>
                <h2><?= formatMoney($totalCobrado) ?></h2>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-dark">
            <div class="card-body text-center">
                <h6>Pacientes Nuevos</h6>
                <h2><?= $pacientesNuevos ?></h2>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Órdenes por día -->
    <div class="col-md-8">
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-bar-chart"></i> Actividad por Día</h5>
            </div>
            <div class="card-body">
                <canvas id="chartSemanal" height="120"></canvas>
            </div>
        </div>
        
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-table"></i> Detalle Diario</h5>
            </div>
            <div class="card-body">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Día</th>
                            <th>Fecha</th>
                            <th class="text-center">Órdenes</th>
                            <th class="text-end">Monto</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $diasSemana = ['Monday' => 'Lunes', 'Tuesday' => 'Martes', 'Wednesday' => 'Miércoles', 
                                       'Thursday' => 'Jueves', 'Friday' => 'Viernes', 'Saturday' => 'Sábado', 'Sunday' => 'Domingo'];
                        foreach ($ordenesPorDia as $dia): 
                        ?>
                        <tr>
                            <td><?= $diasSemana[$dia['dia']] ?? $dia['dia'] ?></td>
                            <td><?= formatDate($dia['fecha']) ?></td>
                            <td class="text-center"><span class="badge bg-primary"><?= $dia['total'] ?></span></td>
                            <td class="text-end"><?= formatMoney($dia['monto']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($ordenesPorDia)): ?>
                        <tr><td colspan="4" class="text-center text-muted">Sin datos para esta semana</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    
    <!-- Panel lateral -->
    <div class="col-md-4">
        <!-- Estado de órdenes -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-pie-chart"></i> Estados de Órdenes</h5>
            </div>
            <div class="card-body">
                <?php 
                $coloresEstado = [
                    'pendiente' => 'warning',
                    'en_proceso' => 'info',
                    'completada' => 'success',
                    'entregada' => 'primary',
                    'cancelada' => 'danger'
                ];
                foreach ($ordenesPorEstado as $estado): 
                ?>
                <div class="d-flex justify-content-between align-items-center mb-2">
                    <span class="badge bg-<?= $coloresEstado[$estado['estado']] ?? 'secondary' ?>"><?= ucfirst($estado['estado']) ?></span>
                    <strong><?= $estado['total'] ?></strong>
                </div>
                <?php endforeach; ?>
                <?php if (empty($ordenesPorEstado)): ?>
                <p class="text-muted text-center">Sin datos</p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Exámenes top -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="bi bi-trophy"></i> Exámenes más Solicitados</h5>
            </div>
            <div class="card-body">
                <ul class="list-group list-group-flush">
                    <?php foreach ($examenesTop as $i => $ex): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center py-2">
                        <small><?= ($i + 1) ?>. <?= htmlspecialchars($ex['nombre']) ?></small>
                        <span class="badge bg-primary"><?= $ex['total'] ?></span>
                    </li>
                    <?php endforeach; ?>
                    <?php if (empty($examenesTop)): ?>
                    <li class="list-group-item text-center text-muted">Sin datos</li>
                    <?php endif; ?>
                </ul>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
const ctx = document.getElementById('chartSemanal').getContext('2d');
new Chart(ctx, {
    type: 'bar',
    data: {
        labels: [<?php echo implode(',', array_map(function($d) { 
            $dias = ['Monday' => 'Lun', 'Tuesday' => 'Mar', 'Wednesday' => 'Mié', 
                     'Thursday' => 'Jue', 'Friday' => 'Vie', 'Saturday' => 'Sáb', 'Sunday' => 'Dom'];
            return "'" . ($dias[$d['dia']] ?? $d['dia']) . "'"; 
        }, $ordenesPorDia)); ?>],
        datasets: [{
            label: 'Órdenes',
            data: [<?php echo implode(',', array_column($ordenesPorDia, 'total')); ?>],
            backgroundColor: 'rgba(102, 126, 234, 0.8)',
            borderColor: 'rgba(102, 126, 234, 1)',
            borderWidth: 1
        }]
    },
    options: {
        responsive: true,
        scales: { y: { beginAtZero: true } },
        plugins: { legend: { display: false } }
    }
});
</script>

<?php require_once __DIR__ . '/../../includes/footer.php'; ?>
