<?php
require __DIR__ . '/../init.php';
require_login();

$pdo = pdo();

// Detectar rol del usuario
$user_id = $_SESSION['user_id'] ?? 0;
$is_admin = $_SESSION['is_admin'] ?? 0;
$is_cashier = $_SESSION['is_cashier'] ?? 0;

// Si no está en sesión, verificar en BD
if (!$is_cashier && $user_id > 0) {
    try {
        $stmt = $pdo->prepare("
            SELECT COUNT(*) 
            FROM user_roles ur 
            JOIN roles r ON r.id = ur.role_id 
            WHERE ur.user_id = ? AND (r.id = 2 OR LOWER(r.name) IN ('cashier', 'cajero', 'caja'))
        ");
        $stmt->execute([$user_id]);
        $is_cashier = (int)$stmt->fetchColumn() > 0 ? 1 : 0;
        $_SESSION['is_cashier'] = $is_cashier;
    } catch (Exception $e) {
        error_log("Error detectando cashier: " . $e->getMessage());
    }
}

// Determinar URL de retorno
if ($is_cashier && !$is_admin) {
    $back_url = site('cashier_dashboard.php');
    $back_label = 'Dashboard Cajero';
} else {
    $back_url = site('index.php');
    $back_label = 'Dashboard Principal';
}

$username = $_SESSION['username'] ?? 'Usuario';
$full_name = $_SESSION['full_name'] ?? $username;

// ✅ OBTENER ESTADÍSTICAS DE COMPROBANTES FISCALES
$comprobantes_today = 0;
$total_comprobantes = 0;
$tipos_disponibles = [];

try {
    // Total de tipos de comprobantes configurados
    $stmt = $pdo->query("SELECT COUNT(*) FROM comprobantes_fiscales");
    $total_comprobantes = (int)$stmt->fetchColumn();
    
    // Obtener tipos disponibles con sus secuencias
    $stmt = $pdo->query("
        SELECT 
            codigo_comprobante,
            tipo_comprobante,
            secuencia_actual,
            secuencia_final,
            ROUND((secuencia_actual / secuencia_final) * 100, 1) as porcentaje_uso
        FROM comprobantes_fiscales 
        ORDER BY codigo_comprobante ASC
    ");
    $tipos_disponibles = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Error obteniendo estadísticas de comprobantes: " . $e->getMessage());
}

// Obtener info de la estación
$station = null;
try {
    $station = $pdo->query("SELECT * FROM stations LIMIT 1")->fetch(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    // Ignorar error
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Comprobantes Fiscales / Tickets - <?= htmlspecialchars($station['nombre'] ?? 'FuelPOS') ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.0/font/bootstrap-icons.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap');
        
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 0;
            margin: 0;
        }
        
        /* NAVBAR */
        .top-navbar {
            background: white;
            box-shadow: 0 4px 20px rgba(0,0,0,0.1);
            padding: 15px 0;
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        
        .nav-brand {
            font-size: 24px;
            font-weight: 800;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        
        .user-avatar {
            width: 45px;
            height: 45px;
            border-radius: 50%;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 800;
            font-size: 18px;
        }
        
        /* MAIN CONTAINER */
        .main-container {
            max-width: 1200px;
            margin: 50px auto;
            padding: 0 20px;
        }
        
        /* PAGE HEADER */
        .page-header {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .page-header::before {
            content: '';
            position: absolute;
            top: -50%;
            right: -10%;
            width: 400px;
            height: 400px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            border-radius: 50%;
            opacity: 0.1;
        }
        
        .page-header h1 {
            font-size: 36px;
            font-weight: 800;
            color: #333;
            margin-bottom: 10px;
            position: relative;
            z-index: 1;
        }
        
        .page-header p {
            font-size: 16px;
            color: #666;
            margin: 0;
            position: relative;
            z-index: 1;
        }
        
        .header-icon {
            font-size: 48px;
            color: #667eea;
            margin-bottom: 15px;
        }
        
        /* STATS GRID */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .stat-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            transition: all 0.3s ease;
        }
        
        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        }
        
        .stat-icon {
            width: 60px;
            height: 60px;
            border-radius: 15px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 28px;
            margin-bottom: 15px;
        }
        
        .stat-icon.blue {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .stat-icon.green {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }
        
        .stat-icon.orange {
            background: linear-gradient(135deg, #ff6a00 0%, #ee0979 100%);
            color: white;
        }
        
        .stat-label {
            font-size: 13px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 1px;
            font-weight: 600;
            margin-bottom: 8px;
        }
        
        .stat-value {
            font-size: 32px;
            font-weight: 800;
            color: #333;
        }
        
        /* NCF TYPES CARDS */
        .ncf-types-section {
            background: white;
            border-radius: 20px;
            padding: 30px;
            margin-bottom: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
        }
        
        .ncf-types-section h3 {
            font-size: 22px;
            font-weight: 800;
            color: #333;
            margin-bottom: 20px;
        }
        
        .ncf-type-card {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            transition: all 0.3s ease;
        }
        
        .ncf-type-card:hover {
            transform: translateX(5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .ncf-type-info h6 {
            font-size: 14px;
            font-weight: 700;
            color: #333;
            margin: 0 0 5px 0;
        }
        
        .ncf-type-info p {
            font-size: 12px;
            color: #666;
            margin: 0;
        }
        
        .ncf-type-progress {
            flex: 1;
            margin: 0 20px;
        }
        
        .progress {
            height: 8px;
            border-radius: 10px;
            background: #e9ecef;
        }
        
        .progress-bar {
            border-radius: 10px;
        }
        
        .ncf-type-stats {
            text-align: right;
        }
        
        .ncf-type-stats strong {
            font-size: 18px;
            color: #333;
            display: block;
        }
        
        .ncf-type-stats small {
            font-size: 11px;
            color: #666;
        }
        
        /* ACTION CARDS */
        .actions-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .action-card {
            background: white;
            border-radius: 20px;
            padding: 35px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            cursor: pointer;
            text-decoration: none;
            color: inherit;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            position: relative;
            overflow: hidden;
        }
        
        .action-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            opacity: 0;
            transition: all 0.3s ease;
        }
        
        .action-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 15px 50px rgba(0,0,0,0.2);
        }
        
        .action-card:hover::before {
            opacity: 1;
        }
        
        .action-card:hover .action-icon,
        .action-card:hover .action-title,
        .action-card:hover .action-desc {
            color: white;
            position: relative;
            z-index: 1;
        }
        
        .action-icon {
            width: 80px;
            height: 80px;
            border-radius: 20px;
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 36px;
            margin-bottom: 20px;
            color: #667eea;
            transition: all 0.3s ease;
        }
        
        .action-title {
            font-size: 20px;
            font-weight: 800;
            color: #333;
            margin-bottom: 10px;
            transition: all 0.3s ease;
        }
        
        .action-desc {
            font-size: 14px;
            color: #666;
            line-height: 1.6;
            transition: all 0.3s ease;
        }
        
        /* BACK BUTTON */
        .back-button {
            display: inline-flex;
            align-items: center;
            gap: 10px;
            background: white;
            color: #667eea;
            text-decoration: none;
            padding: 12px 24px;
            border-radius: 12px;
            font-weight: 600;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .back-button:hover {
            background: #667eea;
            color: white;
            transform: translateX(-5px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.3);
        }
        
        /* RESPONSIVE */
        @media (max-width: 768px) {
            .main-container {
                margin: 30px auto;
            }
            
            .page-header h1 {
                font-size: 28px;
            }
            
            .stats-grid,
            .actions-grid {
                grid-template-columns: 1fr;
            }
            
            .ncf-type-card {
                flex-direction: column;
                text-align: center;
                gap: 15px;
            }
            
            .ncf-type-progress {
                width: 100%;
                margin: 10px 0;
            }
        }
        
        /* ANIMATIONS */
        @keyframes fadeInUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        
        .stat-card,
        .action-card {
            animation: fadeInUp 0.6s ease;
        }
        
        .action-card:nth-child(1) { animation-delay: 0.1s; }
        .action-card:nth-child(2) { animation-delay: 0.2s; }
        .action-card:nth-child(3) { animation-delay: 0.3s; }
    </style>
</head>
<body>

<!-- NAVBAR -->
<nav class="top-navbar">
    <div class="container-fluid">
        <div class="d-flex justify-content-between align-items-center">
            <div class="nav-brand">
                <i class="bi bi-receipt-cutoff"></i>
                Comprobantes Fiscales / Tickets
            </div>
            
            <div class="user-info">
                <div class="d-none d-md-block">
                    <div style="text-align: right;">
                        <strong style="display: block; font-size: 14px; color: #333;">
                            <?= htmlspecialchars($full_name) ?>
                        </strong>
                        <small style="font-size: 12px; color: #666;">
                            <?= $is_admin ? 'Administrador' : ($is_cashier ? 'Cajero(a)' : 'Usuario') ?>
                        </small>
                    </div>
                </div>
                <div class="user-avatar">
                    <?= strtoupper(substr($username, 0, 1)) ?>
                </div>
            </div>
        </div>
    </div>
</nav>

<!-- MAIN CONTENT -->
<div class="main-container">
    
    <!-- BACK BUTTON -->
    <div class="mb-4">
        <a href="<?= $back_url ?>" class="back-button">
            <i class="bi bi-arrow-left-circle-fill"></i>
            Volver a <?= $back_label ?>
        </a>
    </div>
    
    <!-- PAGE HEADER -->
    <div class="page-header">
        <div class="header-icon">
            <i class="bi bi-file-earmark-text-fill"></i>
        </div>
        <h1>Comprobantes Fiscales / Tickets</h1>
        <p>Genera y gestiona comprobantes fiscales y tickets de ventas</p>
    </div>
    
    <!-- STATS GRID -->
    <div class="stats-grid">
        <div class="stat-card">
            <div class="stat-icon blue">
                <i class="bi bi-receipt"></i>
            </div>
            <div class="stat-label">Tipos Configurados</div>
            <div class="stat-value"><?= number_format($total_comprobantes) ?></div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon green">
                <i class="bi bi-check-circle"></i>
            </div>
            <div class="stat-label">Estado</div>
            <div class="stat-value" style="font-size: 20px;">Activo</div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon orange">
                <i class="bi bi-clock"></i>
            </div>
            <div class="stat-label">Hora Actual</div>
            <div class="stat-value" style="font-size: 24px;" id="currentTime"><?= date('H:i:s') ?></div>
        </div>
    </div>
    
    <!-- NCF TYPES SECTION -->
    <?php if (!empty($tipos_disponibles)): ?>
    <div class="ncf-types-section">
        <h3><i class="bi bi-list-check"></i> Tipos de Comprobantes Disponibles</h3>
        
        <?php foreach ($tipos_disponibles as $tipo): ?>
            <div class="ncf-type-card">
                <div class="ncf-type-info">
                    <h6>
                        <i class="bi bi-file-earmark-code"></i>
                        <?= htmlspecialchars($tipo['codigo_comprobante']) ?>
                    </h6>
                    <p><?= htmlspecialchars($tipo['tipo_comprobante']) ?></p>
                </div>
                
                <div class="ncf-type-progress">
                    <div class="progress">
                        <div 
                            class="progress-bar <?= $tipo['porcentaje_uso'] >= 80 ? 'bg-danger' : ($tipo['porcentaje_uso'] >= 50 ? 'bg-warning' : 'bg-success') ?>" 
                            style="width: <?= $tipo['porcentaje_uso'] ?>%"
                        ></div>
                    </div>
                    <small class="text-muted">
                        <?= $tipo['porcentaje_uso'] ?>% utilizado
                    </small>
                </div>
                
                <div class="ncf-type-stats">
                    <strong><?= number_format($tipo['secuencia_actual']) ?></strong>
                    <small>de <?= number_format($tipo['secuencia_final']) ?></small>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>
    
    <!-- ACTION CARDS -->
    <div class="actions-grid">
        <!-- TODOS LOS USUARIOS: Generar Comprobantes y Tickets -->
        <a href="<?= site('ncf/comprobantes.php') ?>" class="action-card">
            <div class="action-icon">
                <i class="bi bi-printer-fill"></i>
            </div>
            <div class="action-title">Generar Comprobantes y Tickets</div>
            <div class="action-desc">
                Genera comprobantes fiscales (NCF) y tickets de venta para tus transacciones. 
                Imprime y registra automáticamente cada documento.
            </div>
        </a>
        
        <a href="<?= site('ncf/reporte.php') ?>" class="action-card">
            <div class="action-icon">
                <i class="bi bi-graph-up-arrow"></i>
            </div>
            <div class="action-title">Reportes</div>
            <div class="action-desc">
                Consulta reportes consolidados de comprobantes fiscales y tickets generados por periodo.
            </div>
        </a>
        
        <!-- SOLO ADMIN Y MANAGER -->
        <?php if ($is_admin): ?>
        <a href="<?= site('ncf/generar.php') ?>" class="action-card">
            <div class="action-icon">
                <i class="bi bi-plus-circle-fill"></i>
            </div>
            <div class="action-title">Crear Comprobante Manual</div>
            <div class="action-desc">
                Crea un nuevo comprobante fiscal (NCF) manualmente con numeración secuencial. Solo para administradores.
            </div>
        </a>
        
        <a href="<?= site('ncf/index.php') ?>" class="action-card">
            <div class="action-icon">
                <i class="bi bi-gear-fill"></i>
            </div>
            <div class="action-title">Configuración</div>
            <div class="action-desc">
                Administra secuencias, tipos de NCF y configuraciones del sistema. Solo para administradores.
            </div>
        </a>
        <?php endif; ?>
    </div>
    
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Actualizar reloj cada segundo
function updateClock() {
    const now = new Date();
    const timeString = now.toLocaleTimeString('es-ES', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
    const clockEl = document.getElementById('currentTime');
    if (clockEl) clockEl.textContent = timeString;
}

setInterval(updateClock, 1000);
updateClock();
</script>

</body>
</html>