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

// Verificar que el usuario tiene rol de Cashier (ID 2)
$user_id = $_SESSION['user_id'] ?? 0;
$has_cashier_role = false;

if ($user_id > 0) {
    $stmt = $pdo->prepare("SELECT COUNT(*) FROM user_roles WHERE user_id = ? AND role_id = 2");
    $stmt->execute([$user_id]);
    $has_cashier_role = (int)$stmt->fetchColumn() > 0;
}

// Si no tiene el rol, verificar si es admin
$is_admin = false;
if ($user_id > 0) {
    $stmt = $pdo->prepare("
        SELECT COUNT(*) 
        FROM user_roles ur 
        JOIN roles r ON r.id = ur.role_id 
        WHERE ur.user_id = ? AND r.is_admin = 1
    ");
    $stmt->execute([$user_id]);
    $is_admin = (int)$stmt->fetchColumn() > 0;
}

// Si no es cajero ni admin, redirigir
if (!$has_cashier_role && !$is_admin) {
    header('Location: ' . site('index.php'));
    exit;
}

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

// Obtener estadísticas del día
$today = date('Y-m-d');

// Ventas del día
$stmt = $pdo->prepare("SELECT COALESCE(SUM(total), 0) FROM sales WHERE DATE(created_at) = ?");
$stmt->execute([$today]);
$total_today = (float)$stmt->fetchColumn();

$stmt = $pdo->prepare("SELECT COUNT(*) FROM sales WHERE DATE(created_at) = ?");
$stmt->execute([$today]);
$count_today = (int)$stmt->fetchColumn();

// Ventas por método de pago
$stmt = $pdo->prepare("
    SELECT payment_method, COUNT(*) as count, COALESCE(SUM(total), 0) as total 
    FROM sales 
    WHERE DATE(created_at) = ? 
    GROUP BY payment_method
");
$stmt->execute([$today]);
$payment_methods = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Últimas ventas
$stmt = $pdo->prepare("
    SELECT s.*, u.username 
    FROM sales s 
    LEFT JOIN users u ON u.id = s.user_id 
    WHERE DATE(s.created_at) = ? 
    ORDER BY s.created_at DESC 
    LIMIT 5
");
$stmt->execute([$today]);
$recent_sales = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Información de la estación
$station = $pdo->query("SELECT * FROM estacion LIMIT 1")->fetch(PDO::FETCH_ASSOC);
if (!$station) {
    $station = ['nombre' => 'FuelPOS'];
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Dashboard Cajero - <?= htmlspecialchars($station['nombre'] ?? 'FuelPOS') ?></title>
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <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;
    }
    
    .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;
    }
    
    .user-name {
      display: flex;
      flex-direction: column;
    }
    
    .user-name strong {
      font-size: 14px;
      color: #333;
    }
    
    .user-name small {
      font-size: 12px;
      color: #666;
    }
    
    /* MAIN CONTAINER */
    .main-container {
      max-width: 1400px;
      margin: 30px auto;
      padding: 0 20px;
    }
    
    /* WELCOME BANNER */
    .welcome-banner {
      background: white;
      border-radius: 20px;
      padding: 30px;
      margin-bottom: 30px;
      box-shadow: 0 10px 40px rgba(0,0,0,0.1);
      position: relative;
      overflow: hidden;
    }
    
    .welcome-banner::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;
    }
    
    .welcome-banner h2 {
      font-size: 32px;
      font-weight: 800;
      color: #333;
      margin-bottom: 10px;
      position: relative;
      z-index: 1;
    }
    
    .welcome-banner p {
      font-size: 16px;
      color: #666;
      margin: 0;
      position: relative;
      z-index: 1;
    }
    
    /* STATS CARDS */
    .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;
      position: relative;
      overflow: hidden;
    }
    
    .stat-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 30px rgba(0,0,0,0.15);
    }
    
    .stat-card::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      height: 4px;
      background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
    }
    
    .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;
      line-height: 1;
    }
    
    /* ACTION CARDS */
    .actions-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
      gap: 25px;
      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;
    }
    
    /* RECENT ACTIVITY */
    .activity-card {
      background: white;
      border-radius: 20px;
      padding: 30px;
      box-shadow: 0 10px 40px rgba(0,0,0,0.1);
    }
    
    .activity-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;
      padding-bottom: 15px;
      border-bottom: 2px solid #f0f0f0;
    }
    
    .activity-header h3 {
      font-size: 20px;
      font-weight: 800;
      color: #333;
      margin: 0;
    }
    
    .activity-list {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }
    
    .activity-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 15px;
      background: #f8f9fa;
      border-radius: 12px;
      transition: all 0.3s ease;
    }
    
    .activity-item:hover {
      background: #e9ecef;
      transform: translateX(5px);
    }
    
    .activity-info {
      display: flex;
      align-items: center;
      gap: 15px;
    }
    
    .activity-icon {
      width: 45px;
      height: 45px;
      border-radius: 10px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 18px;
    }
    
    .activity-details h6 {
      font-size: 14px;
      font-weight: 700;
      color: #333;
      margin: 0 0 4px 0;
    }
    
    .activity-details small {
      font-size: 12px;
      color: #666;
    }
    
    .activity-amount {
      font-size: 18px;
      font-weight: 800;
      color: #667eea;
    }
    
    /* PAYMENT METHODS */
    .payment-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
      gap: 15px;
      margin-top: 20px;
    }
    
    .payment-method-card {
      background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
      border-radius: 12px;
      padding: 20px;
      text-align: center;
      transition: all 0.3s ease;
    }
    
    .payment-method-card:hover {
      transform: translateY(-3px);
      box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    
    .payment-method-card h6 {
      font-size: 12px;
      text-transform: uppercase;
      letter-spacing: 1px;
      color: #666;
      margin-bottom: 10px;
      font-weight: 600;
    }
    
    .payment-method-card .value {
      font-size: 24px;
      font-weight: 800;
      color: #333;
      margin-bottom: 5px;
    }
    
    .payment-method-card .count {
      font-size: 12px;
      color: #666;
    }
    
    /* RESPONSIVE */
    @media (max-width: 768px) {
      .stats-grid,
      .actions-grid {
        grid-template-columns: 1fr;
      }
      
      .welcome-banner h2 {
        font-size: 24px;
      }
      
      .user-name {
        display: none;
      }
    }
    
    /* ANIMATIONS */
    @keyframes fadeInUp {
      from {
        opacity: 0;
        transform: translateY(30px);
      }
      to {
        opacity: 1;
        transform: translateY(0);
      }
    }
    
    .stat-card,
    .action-card,
    .activity-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; }
    .action-card:nth-child(4) { animation-delay: 0.4s; }
  </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-fuel-pump-fill"></i>
        <?= htmlspecialchars($station['nombre'] ?? 'FuelPOS') ?>
      </div>
      
      <div class="user-info">
        <div class="user-name d-none d-md-block">
          <strong><?= htmlspecialchars($full_name) ?></strong>
          <small>Cajero(a)</small>
        </div>
        <div class="user-avatar">
          <?= strtoupper(substr($username, 0, 1)) ?>
        </div>
        <div class="dropdown">
          <button class="btn btn-link text-dark" type="button" data-bs-toggle="dropdown">
            <i class="bi bi-three-dots-vertical"></i>
          </button>
          <ul class="dropdown-menu dropdown-menu-end">
            <?php if ($is_admin): ?>
            <li>
              <a class="dropdown-item" href="<?= site('index.php') ?>">
                <i class="bi bi-speedometer2"></i> Dashboard Principal
              </a>
            </li>
            <li><hr class="dropdown-divider"></li>
            <?php endif; ?>
            <li>
              <a class="dropdown-item text-danger" href="<?= site('admin_logout.php') ?>">
                <i class="bi bi-box-arrow-right"></i> Cerrar Sesión
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</nav>

<!-- MAIN CONTENT -->
<div class="main-container">
  
  <!-- WELCOME BANNER -->
  <div class="welcome-banner">
    <h2>¡Hola, <?= htmlspecialchars(explode(' ', $full_name)[0]) ?>! 👋</h2>
    <p>Bienvenido(a) al sistema de caja. Aquí puedes gestionar tus operaciones diarias.</p>
  </div>
  
  <!-- STATS CARDS -->
  <div class="stats-grid">
    <div class="stat-card">
      <div class="stat-icon blue">
        <i class="bi bi-cash-stack"></i>
      </div>
      <div class="stat-label">Total Ventas Hoy</div>
      <div class="stat-value">$<?= number_format($total_today, 2) ?></div>
    </div>
    
    <div class="stat-card">
      <div class="stat-icon green">
        <i class="bi bi-receipt"></i>
      </div>
      <div class="stat-label">Transacciones</div>
      <div class="stat-value"><?= number_format($count_today) ?></div>
    </div>
    
    <div class="stat-card">
      <div class="stat-icon orange">
        <i class="bi bi-clock-history"></i>
      </div>
      <div class="stat-label">Hora Actual</div>
      <div class="stat-value" style="font-size: 24px;"><?= date('H:i:s') ?></div>
    </div>
  </div>
  
  <!-- ACTION CARDS -->
  <div class="actions-grid">
    <a href="<?= site('cuadrebomberos.php') ?>" class="action-card">
      <div class="action-icon">
        <i class="bi bi-calculator-fill"></i>
      </div>
      <div class="action-title">Cuadre de Bomberos</div>
      <div class="action-desc">
        Realiza el cuadre diario de los bomberos y verifica las transacciones de cada isla.
      </div>
    </a>
    
    <a href="<?= site('asignar_metodo_pago.php') ?>" class="action-card">
      <div class="action-icon">
        <i class="bi bi-credit-card-fill"></i>
      </div>
      <div class="action-title">Asignar Método de Pago</div>
      <div class="action-desc">
        Gestiona y asigna métodos de pago a las transacciones realizadas por bomba.
      </div>
    </a>
    
    <a href="<?= site('creditos_empleados.php') ?>" class="action-card">
      <div class="action-icon">
        <i class="bi bi-person-badge-fill"></i>
      </div>
      <div class="action-title">Créditos Empleados</div>
      <div class="action-desc">
        Asigna ventas a crédito de empleados usando sus tarjetas corporativas.
      </div>
    </a>
    
    <a href="<?= site('ncf/facturas.php') ?>" class="action-card">
      <div class="action-icon">
        <i class="bi bi-file-earmark-text-fill"></i>
      </div>
      <div class="action-title">Comprobantes Fiscales</div>
      <div class="action-desc">
        Consulta y gestiona los comprobantes fiscales (NCF) del sistema.
      </div>
    </a>
  </div>
  
  <div class="row g-4">
    <!-- RECENT ACTIVITY -->
    <div class="col-lg-7">
      <div class="activity-card">
        <div class="activity-header">
          <h3><i class="bi bi-clock-history"></i> Últimas Ventas</h3>
          <span class="badge bg-primary"><?= count($recent_sales) ?> registros</span>
        </div>
        
        <div class="activity-list">
          <?php if (empty($recent_sales)): ?>
            <div class="text-center text-muted py-4">
              <i class="bi bi-inbox" style="font-size: 48px; opacity: 0.3;"></i>
              <p class="mt-2">No hay ventas registradas hoy</p>
            </div>
          <?php else: ?>
            <?php foreach ($recent_sales as $sale): ?>
              <div class="activity-item">
                <div class="activity-info">
                  <div class="activity-icon">
                    <i class="bi bi-receipt-cutoff"></i>
                  </div>
                  <div class="activity-details">
                    <h6><?= htmlspecialchars($sale['sale_code']) ?></h6>
                    <small>
                      <i class="bi bi-person"></i> <?= htmlspecialchars($sale['username'] ?? 'Sistema') ?>
                      <i class="bi bi-dot"></i>
                      <i class="bi bi-clock"></i> <?= date('H:i', strtotime($sale['created_at'])) ?>
                    </small>
                  </div>
                </div>
                <div class="activity-amount">
                  $<?= number_format($sale['total'], 2) ?>
                </div>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>
    </div>
    
    <!-- PAYMENT METHODS -->
    <div class="col-lg-5">
      <div class="activity-card">
        <div class="activity-header">
          <h3><i class="bi bi-pie-chart-fill"></i> Métodos de Pago</h3>
          <span class="badge bg-success">Hoy</span>
        </div>
        
        <?php if (empty($payment_methods)): ?>
          <div class="text-center text-muted py-4">
            <i class="bi bi-inbox" style="font-size: 48px; opacity: 0.3;"></i>
            <p class="mt-2">No hay datos disponibles</p>
          </div>
        <?php else: ?>
          <div class="payment-grid">
            <?php foreach ($payment_methods as $pm): ?>
              <div class="payment-method-card">
                <h6><?= htmlspecialchars(ucfirst($pm['payment_method'])) ?></h6>
                <div class="value">$<?= number_format($pm['total'], 2) ?></div>
                <div class="count"><?= $pm['count'] ?> transacciones</div>
              </div>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </div>
    </div>
  </div>
  
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Auto-refresh cada 30 segundos
setInterval(() => {
  location.reload();
}, 30000);

// Actualizar reloj
setInterval(() => {
  const clockElements = document.querySelectorAll('.stat-value');
  clockElements.forEach(el => {
    if (el.textContent.includes(':')) {
      el.textContent = new Date().toLocaleTimeString('es-ES', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
      });
    }
  });
}, 1000);
</script>

</body>
</html>