<?php
// card.php - Zamjena za card.html

require_once 'config.php';

// Dohvati slug iz URL-a na ispravan način
$slug = $_GET['slug'] ?? ''; // Dohvaća 'slug' parametar koji šalje .htaccess

// Ako nema sluga, prikaži error
if (empty($slug)) {
    http_response_code(404);
    echo '<h1>404 - Stranica nije pronađena</h1>';
    exit;
}

try {
    $db = getDB();
    
    // Dohvati korisnika po slug-u
    $stmt = $db->prepare('SELECT * FROM users WHERE slug = ?');
    $stmt->execute([$slug]);
    $user = $stmt->fetch();
    
    if (!$user) {
        http_response_code(404);
        echo '<h1>404 - Korisnik nije pronađen</h1>';
        exit;
    }
    
    // Dohvati linkove
    $stmt = $db->prepare('SELECT * FROM links WHERE user_id = ? ORDER BY sort_order');
    $stmt->execute([$user['id']]);
    $links = $stmt->fetchAll();
    
    // Dohvati module
    $stmt = $db->prepare('SELECT * FROM modules WHERE user_id = ?');
    $stmt->execute([$user['id']]);
    $modules = $stmt->fetchAll();
    
    // Pripremi module u array po nazivu (samo aktivni)
    $activeModules = [];
    foreach ($modules as $module) {
        if ($module['aktivan'] == 1) {
            $activeModules[$module['modul_name']] = $module;
        }
    }
    
    // Provjeri je li account aktivan
if (!$user['active']) {
    http_response_code(403);
    ?>
    <!DOCTYPE html>
    <html lang="hr">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Račun neaktivan</title>
        <style>
            body { font-family: -apple-system, sans-serif; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background: #f5f7fa; }
            .box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); text-align: center; max-width: 400px; }
            h1 { color: #ef4444; margin-bottom: 15px; }
            p { color: #64748b; line-height: 1.6; }
        </style>
    </head>
    <body>
        <div class="box">
            <h1>⚠️ Račun neaktivan</h1>
            <p>Ovaj korisnički račun trenutno nije aktivan. Molimo kontaktirajte vlasnika za više informacija.</p>
        </div>
    </body>
    </html>
    <?php
    exit;
}

// Provjeri datum
if ($user['active_until']) {
    $today = new DateTime();
    $expiryDate = new DateTime($user['active_until']);
    
    if ($today > $expiryDate) {
        http_response_code(403);
        ?>
        <!DOCTYPE html>
        <html lang="hr">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Račun istekao</title>
            <style>
                body { font-family: -apple-system, sans-serif; display: flex; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background: #f5f7fa; }
                .box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); text-align: center; max-width: 400px; }
                h1 { color: #f59e0b; margin-bottom: 15px; }
                p { color: #64748b; line-height: 1.6; }
            </style>
        </head>
        <body>
            <div class="box">
                <h1>⏰ Račun istekao</h1>
                <p>Ovaj korisnički račun je istekao <?php echo $expiryDate->format('d.m.Y'); ?>. Molimo kontaktirajte vlasnika za obnovu.</p>
            </div>
        </body>
        </html>
        <?php
        exit;
    }
}
    
    // Logiraj posjet
    $ip = getUserIP();
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $qrScan = isset($_GET['qr']) && $_GET['qr'] == '1' ? 1 : 0;
    
    $stmt = $db->prepare('INSERT INTO visits (user_id, ip, user_agent, qr_scan) VALUES (?, ?, ?, ?)');
    $stmt->execute([$user['id'], $ip, $userAgent, $qrScan]);
    
    // Generiraj header background
    function getHeaderBackground($user) {
        if (!empty($user['background_image'])) {
            return [
                'type' => 'image',
                'style' => "background-image: url('" . htmlspecialchars($user['background_image']) . "'); background-size: cover; background-position: center;"
            ];
        }
        
        if (!empty($user['background_color'])) {
            $color = $user['background_color'];
            $darker = adjustBrightness($color, -20);
            return [
                'type' => 'gradient',
                'style' => "background: linear-gradient(135deg, {$color} 0%, {$darker} 100%);"
            ];
        }
        
        // Fallback: koristi accent boju
        $accentColor = $user['accent_color'] ?? '#3b82f6';
        $darker = adjustBrightness($accentColor, -25);
        return [
            'type' => 'accent',
            'style' => "background: linear-gradient(135deg, {$accentColor} 0%, {$darker} 100%);"
        ];
    }
    
    function adjustBrightness($hex, $percent) {
        $hex = str_replace('#', '', $hex);
        $r = hexdec(substr($hex, 0, 2));
        $g = hexdec(substr($hex, 2, 2));
        $b = hexdec(substr($hex, 4, 2));
        
        $r = max(0, min(255, $r + ($r * $percent / 100)));
        $g = max(0, min(255, $g + ($g * $percent / 100)));
        $b = max(0, min(255, $b + ($b * $percent / 100)));
        
        return sprintf("#%02x%02x%02x", $r, $g, $b);
    }
    
    $headerBg = getHeaderBackground($user);
    
    // Učitaj template
    $template = $user['display_template'] ?? 'modern';
    $templateFile = "template-{$template}.php";
    
    if (!file_exists($templateFile)) {
        $templateFile = 'template-modern.php';
    }
    
    include $templateFile;
    
} catch (Exception $e) {
    http_response_code(500);
    echo '<h1>500 - Greška na serveru</h1>';
    error_log('Card error: ' . $e->getMessage());
}
?>