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

$db = getDB();

// Estadísticas generales
$stats = [];

// Total de órdenes hoy
$stmt = $db->query("SELECT COUNT(*) FROM ordenes WHERE DATE(fecha_orden) = CURDATE()");
$stats['ordenes_hoy'] = $stmt->fetchColumn();

// Total de pacientes
$stmt = $db->query("SELECT COUNT(*) FROM pacientes");
$stats['total_pacientes'] = $stmt->fetchColumn();

// Órdenes pendientes
$stmt = $db->query("SELECT COUNT(*) FROM ordenes WHERE estado IN ('pendiente', 'en_proceso')");
$stats['ordenes_pendientes'] = $stmt->fetchColumn();

// Ingresos del día
$stmt = $db->query("SELECT COALESCE(SUM(monto), 0) FROM pagos WHERE DATE(fecha_pago) = CURDATE()");
$stats['ingresos_hoy'] = $stmt->fetchColumn();

// Últimas órdenes
$stmt = $db->query("
    SELECT o.*, p.nombre, p.apellidos 
    FROM ordenes o 
    JOIN pacientes p ON o.paciente_id = p.id 
    ORDER BY o.id DESC 
    LIMIT 10
");
$ultimasOrdenes = $stmt->fetchAll();

// Insumos con stock bajo
$stmt = $db->query("SELECT * FROM insumos WHERE stock_actual <= stock_minimo AND activo = 1 LIMIT 5");
$insumosbajos = $stmt->fetchAll();

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

<div class="page-header">
    <h2><i class="bi bi-speedometer2"></i> Dashboard</h2>
    <span class="date-badge"><i class="bi bi-calendar3"></i> <?= date('d/m/Y H:i') ?></span>
</div>

<!-- Estadísticas -->
<div class="row g-4 mb-4">
    <div class="col-md-6 col-lg-3">
        <div class="stat-card orders">
            <div class="d-flex justify-content-between align-items-start">
                <div style="position:relative;z-index:1;">
                    <h6 class="mb-1">Órdenes Hoy</h6>
                    <h2 class="mb-0"><?= $stats['ordenes_hoy'] ?></h2>
                    <small style="opacity:0.7;font-size:0.75rem;">del día actual</small>
                </div>
                <div style="width:50px;height:50px;background:rgba(255,255,255,0.15);border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative;z-index:1;">
                    <i class="bi bi-clipboard2-pulse" style="font-size: 1.5rem;"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-lg-3">
        <div class="stat-card patients">
            <div class="d-flex justify-content-between align-items-start">
                <div style="position:relative;z-index:1;">
                    <h6 class="mb-1">Total Pacientes</h6>
                    <h2 class="mb-0"><?= $stats['total_pacientes'] ?></h2>
                    <small style="opacity:0.7;font-size:0.75rem;">registrados</small>
                </div>
                <div style="width:50px;height:50px;background:rgba(255,255,255,0.15);border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative;z-index:1;">
                    <i class="bi bi-people" style="font-size: 1.5rem;"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-lg-3">
        <div class="stat-card pending">
            <div class="d-flex justify-content-between align-items-start">
                <div style="position:relative;z-index:1;">
                    <h6 class="mb-1">Pendientes</h6>
                    <h2 class="mb-0"><?= $stats['ordenes_pendientes'] ?></h2>
                    <small style="opacity:0.7;font-size:0.75rem;">por procesar</small>
                </div>
                <div style="width:50px;height:50px;background:rgba(255,255,255,0.15);border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative;z-index:1;">
                    <i class="bi bi-hourglass-split" style="font-size: 1.5rem;"></i>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-6 col-lg-3">
        <div class="stat-card revenue">
            <div class="d-flex justify-content-between align-items-start">
                <div style="position:relative;z-index:1;">
                    <h6 class="mb-1">Ingresos Hoy</h6>
                    <h2 class="mb-0"><?= formatMoney($stats['ingresos_hoy']) ?></h2>
                    <small style="opacity:0.7;font-size:0.75rem;">cobrado hoy</small>
                </div>
                <div style="width:50px;height:50px;background:rgba(255,255,255,0.15);border-radius:12px;display:flex;align-items:center;justify-content:center;position:relative;z-index:1;">
                    <i class="bi bi-currency-dollar" style="font-size: 1.5rem;"></i>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Últimas órdenes -->
    <div class="col-md-8">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-clock-history"></i> Últimas Órdenes</h5>
                <a href="<?= SITE_URL ?>/modules/ordenes/create.php" class="btn btn-primary btn-sm">
                    <i class="bi bi-plus"></i> Nueva Orden
                </a>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Código</th>
                                <th>Paciente</th>
                                <th>Fecha</th>
                                <th>Total</th>
                                <th>Estado</th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($ultimasOrdenes)): ?>
                            <tr>
                                <td colspan="6" class="text-center text-muted">No hay órdenes registradas</td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($ultimasOrdenes as $orden): ?>
                            <tr>
                                <td><strong><?= $orden['codigo'] ?></strong></td>
                                <td><?= $orden['nombre'] . ' ' . $orden['apellidos'] ?></td>
                                <td><?= formatDateTime($orden['fecha_orden']) ?></td>
                                <td><?= formatMoney($orden['total']) ?></td>
                                <td>
                                    <?php
                                    $estadoClass = [
                                        'pendiente' => 'bg-warning',
                                        'en_proceso' => 'bg-info',
                                        'completada' => 'bg-success',
                                        'entregada' => 'bg-primary',
                                        'cancelada' => 'bg-danger'
                                    ];
                                    ?>
                                    <span class="badge <?= $estadoClass[$orden['estado']] ?>">
                                        <?= ucfirst(str_replace('_', ' ', $orden['estado'])) ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="<?= SITE_URL ?>/modules/ordenes/view.php?id=<?= $orden['id'] ?>" 
                                       class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Panel lateral -->
    <div class="col-md-4">
        <!-- Acciones rápidas -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0" style="font-weight:700;font-size:1rem;"><i class="bi bi-lightning-charge-fill" style="color:#f59e0b;"></i> Acciones Rápidas</h5>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <a href="<?= SITE_URL ?>/modules/ordenes/create.php" class="btn btn-primary" style="border-radius:10px;padding:12px;font-size:0.9rem;">
                        <i class="bi bi-plus-circle"></i> Nueva Orden
                    </a>
                    <a href="<?= SITE_URL ?>/modules/pacientes/create.php" class="btn btn-outline-primary" style="border-radius:10px;padding:12px;font-size:0.9rem;border-width:2px;">
                        <i class="bi bi-person-plus"></i> Nuevo Paciente
                    </a>
                    <a href="<?= SITE_URL ?>/modules/resultados/list.php" class="btn btn-outline-success" style="border-radius:10px;padding:12px;font-size:0.9rem;border-width:2px;">
                        <i class="bi bi-file-earmark-medical"></i> Ingresar Resultados
                    </a>
                </div>
            </div>
        </div>

        <!-- Alertas de inventario -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0" style="font-weight:700;font-size:1rem;"><i class="bi bi-exclamation-triangle-fill" style="color:#f59e0b;"></i> Stock Bajo</h5>
            </div>
            <div class="card-body">
                <?php if (empty($insumosbajos)): ?>
                <p class="text-muted text-center mb-0">
                    <i class="bi bi-check-circle text-success"></i> Inventario OK
                </p>
                <?php else: ?>
                <ul class="list-group list-group-flush">
                    <?php foreach ($insumosbajos as $insumo): ?>
                    <li class="list-group-item d-flex justify-content-between align-items-center">
                        <span><?= $insumo['nombre'] ?></span>
                        <span class="badge bg-danger"><?= $insumo['stock_actual'] ?> <?= $insumo['unidad_medida'] ?></span>
                    </li>
                    <?php endforeach; ?>
                </ul>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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