<?php
require_once 'config.php';

$requestUri = $_SERVER['REQUEST_URI'];
preg_match('#/([a-zA-Z0-9_-]+)/analytics/([a-zA-Z0-9]{32})#', $requestUri, $matches);

if (!$matches) {
    http_response_code(404);
    die('Nevažeći link');
}

$slug = $matches[1];
$key = $matches[2];

$db = getDB();
$stmt = $db->prepare('SELECT id, ime, prezime, active, active_until FROM users WHERE slug = ? AND analytics_key = ?');
$stmt->execute([$slug, $key]);
$user = $stmt->fetch();

if (!$user) {
    http_response_code(403);
    die('Neovlašteni pristup');
}

// Provjera statusa
$isActive = (bool)$user['active'];
$activeUntil = $user['active_until'] ? new DateTime($user['active_until']) : null;
$isLifetime = !$activeUntil;
$isExpired = false;
$daysLeft = null;

if ($activeUntil) {
    $today = new DateTime();
    if ($today > $activeUntil) {
        $isExpired = true;
        $daysLeft = 0;
    } else {
        $diff = $today->diff($activeUntil);
        $daysLeft = (int)$diff->format('%a');
    }
}

// Konačan status
if (!$isActive) {
    $statusColor = '#ef4444';
    $statusIcon = '⛔';
    $statusText = 'Račun neaktivan';
} elseif ($isExpired) {
    $statusColor = '#f59e0b';
    $statusIcon = '⏰';
    $statusText = 'Račun istekao';
} elseif ($isLifetime) {
    $statusColor = '#10b981';
    $statusIcon = '♾️';
    $statusText = 'Lifetime pristup';
} else {
    $statusColor = $daysLeft > 7 ? '#667eea' : '#f59e0b';
    $statusIcon = '✓';
    $statusText = "Još {$daysLeft} dana";
}
?>
<!DOCTYPE html>
<html lang="hr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Analytics - <?php echo htmlspecialchars($user['ime'] . ' ' . $user['prezime']); ?></title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #f5f7fa; padding: 20px; }
    .container { max-width: 1200px; margin: 0 auto; }
    h1 { color: #1e293b; margin-bottom: 30px; text-align: center; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; }
    .card { background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
    .card h2 { font-size: 14px; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; margin-bottom: 15px; }
    .stat { display: flex; justify-content: space-between; padding: 12px 0; border-bottom: 1px solid #f1f5f9; }
    .stat:last-child { border-bottom: none; }
    .stat-label { color: #475569; font-size: 15px; }
    .stat-value { font-size: 20px; font-weight: 700; color: #667eea; }
    .qr-value { color: #10b981; }
    .status-box { background: white; border-radius: 12px; padding: 25px; margin-bottom: 30px; text-align: center; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
    .status-icon { font-size: 48px; margin-bottom: 10px; }
    .status-text { font-size: 20px; font-weight: 600; margin-bottom: 10px; }
    .status-detail { font-size: 14px; color: #64748b; }
  </style>
</head>
<body>
  <div class="container">
    <h1>📊 Analytics - <?php echo htmlspecialchars($user['ime'] . ' ' . $user['prezime']); ?></h1>
    
    <div class="status-box">
      <div class="status-icon"><?php echo $statusIcon; ?></div>
      <div class="status-text" style="color: <?php echo $statusColor; ?>;">
        <?php echo $statusText; ?>
      </div>
      <?php if ($activeUntil): ?>
        <div class="status-detail">
          Vrijedi do: <?php echo $activeUntil->format('d.m.Y'); ?>
        </div>
      <?php endif; ?>
    </div>
    
    <?php if ($isActive && !$isExpired): ?>
      <div id="stats" class="grid">Učitavanje...</div>
    <?php else: ?>
      <div class="card" style="text-align: center; padding: 40px;">
        <p style="color: #64748b; font-size: 16px;">Statistika nije dostupna za neaktivne račune.</p>
      </div>
    <?php endif; ?>
  </div>
  
  <?php if ($isActive && !$isExpired): ?>
  <script>
    async function loadStats() {
      try {
        const response = await fetch('/api/analytics/<?php echo $slug; ?>/<?php echo $key; ?>');
        const data = await response.json();
        
        document.getElementById('stats').innerHTML = `
          <div class="card">
            <h2>Danas</h2>
            <div class="stat"><span class="stat-label">Posjeta</span><span class="stat-value">${data.today.visits}</span></div>
            <div class="stat"><span class="stat-label">QR skeniranja</span><span class="stat-value qr-value">${data.today.qr_scans}</span></div>
          </div>
          <div class="card">
            <h2>Ovaj tjedan</h2>
            <div class="stat"><span class="stat-label">Posjeta</span><span class="stat-value">${data.this_week.visits}</span></div>
            <div class="stat"><span class="stat-label">QR skeniranja</span><span class="stat-value qr-value">${data.this_week.qr_scans}</span></div>
          </div>
          <div class="card">
            <h2>Ovaj mjesec</h2>
            <div class="stat"><span class="stat-label">Posjeta</span><span class="stat-value">${data.this_month.visits}</span></div>
            <div class="stat"><span class="stat-label">QR skeniranja</span><span class="stat-value qr-value">${data.this_month.qr_scans}</span></div>
          </div>
          <div class="card">
            <h2>Prošli mjesec</h2>
            <div class="stat"><span class="stat-label">Posjeta</span><span class="stat-value">${data.last_month.visits}</span></div>
            <div class="stat"><span class="stat-label">QR skeniranja</span><span class="stat-value qr-value">${data.last_month.qr_scans}</span></div>
          </div>
          <div class="card">
            <h2>Ova godina</h2>
            <div class="stat"><span class="stat-label">Posjeta</span><span class="stat-value">${data.this_year.visits}</span></div>
            <div class="stat"><span class="stat-label">QR skeniranja</span><span class="stat-value qr-value">${data.this_year.qr_scans}</span></div>
          </div>
          <div class="card">
            <h2>Ukupno</h2>
            <div class="stat"><span class="stat-label">Posjeta</span><span class="stat-value">${data.total.visits}</span></div>
            <div class="stat"><span class="stat-label">QR skeniranja</span><span class="stat-value qr-value">${data.total.qr_scans}</span></div>
          </div>
        `;
      } catch (e) {
        document.getElementById('stats').innerHTML = '<div class="card"><p style="text-align:center;color:red;">Greška pri učitavanju</p></div>';
      }
    }
    loadStats();
    setInterval(loadStats, 60000);
  </script>
  <?php endif; ?>
</body>
</html>