<?php
require_once 'config.php';

// Dohvati slug iz URL-a
$slug = $_GET['slug'] ?? '';

if (empty($slug)) {
    http_response_code(400);
    die('Missing slug');
}

try {
    $db = getDB();
    
    // Dohvati korisnika
    $stmt = $db->prepare('SELECT * FROM users WHERE slug = ?');
    $stmt->execute([$slug]);
    $user = $stmt->fetch();
    
    if (!$user) {
        http_response_code(404);
        die('User not found');
    }
    
    // Dohvati linkove
    $stmt = $db->prepare('SELECT * FROM links WHERE user_id = ? ORDER BY sort_order');
    $stmt->execute([$user['id']]);
    $links = $stmt->fetchAll();
    
    // Generiraj vCard 3.0 (najbolji compatibility za iOS i Android)
    $vcard = "BEGIN:VCARD\r\n";
    $vcard .= "VERSION:3.0\r\n";
    $vcard .= "FN:" . $user['ime'] . ' ' . $user['prezime'] . "\r\n";
    $vcard .= "N:" . $user['prezime'] . ';' . $user['ime'] . ";;;\r\n";
    
    // Telefoni
    if ($user['telefon']) {
        $vcard .= "TEL;TYPE=CELL:" . $user['telefon'] . "\r\n";
    }
    if ($user['whatsapp']) {
        $vcard .= "TEL;TYPE=CELL,VOICE:" . $user['whatsapp'] . "\r\n";
    }
    if ($user['viber']) {
        $vcard .= "TEL;TYPE=HOME:" . $user['viber'] . "\r\n";
    }
    
    // Email
    if ($user['email']) {
        $vcard .= "EMAIL:" . $user['email'] . "\r\n";
    }
    
    // Adresa
    if ($user['adresa'] || $user['grad'] || $user['drzava']) {
        $vcard .= "ADR;TYPE=WORK:;;" 
            . ($user['adresa'] ?? '') . ';' 
            . ($user['grad'] ?? '') . ';;' 
            . ($user['grad'] ? '88320' : '') . ';' 
            . ($user['drzava'] ?? '') . "\r\n";
    }
    
    // URL - glavna kartica
    $vcard .= "URL:https://card.taptap.ba/" . $user['slug'] . "\r\n";
    
    // Društvene mreže kao dodatni URL-ovi
    foreach ($links as $link) {
        $vcard .= "URL;TYPE=" . strtoupper($link['tip']) . ":" . $link['url'] . "\r\n";
    }
    
    // Opis
    if ($user['opis']) {
        $cleanDesc = str_replace(["\r\n", "\n", "\r"], ' ', $user['opis']);
        $vcard .= "NOTE:" . $cleanDesc . "\r\n";
    }
    
    // Slika - SAMO AKO POSTOJI I AKO JE LOKALNA
    if ($user['slika'] && strpos($user['slika'], '/uploads/') === 0) {
        $imagePath = __DIR__ . $user['slika'];
        if (file_exists($imagePath)) {
            $imageData = file_get_contents($imagePath);
            if ($imageData !== false) {
                $base64 = base64_encode($imageData);
                
                // Detektiraj tip slike
                $imageType = 'JPEG';
                $ext = strtolower(pathinfo($imagePath, PATHINFO_EXTENSION));
                if ($ext === 'png') $imageType = 'PNG';
                elseif ($ext === 'gif') $imageType = 'GIF';
                
                // iOS preferira ovaj format za vCard 3.0
                $vcard .= "PHOTO;ENCODING=b;TYPE=" . $imageType . ":" . $base64 . "\r\n";
            }
        }
    }
    
    // Org - ako je upisano u opis ili možeš dodati posebno polje
    if (strpos(strtolower($user['opis'] ?? ''), 'convoco') !== false) {
        $vcard .= "ORG:Convoco\r\n";
    }
    
    $vcard .= "REV:" . date('Y-m-d\TH:i:s\Z') . "\r\n";
    $vcard .= "END:VCARD\r\n";
    
    // KRITIČNO: Ovi headeri uzrokuju da se otvori direktno u contact app-u
    header('Content-Type: text/vcard; charset=utf-8');
    header('Content-Disposition: inline; filename="' . $user['ime'] . '_' . $user['prezime'] . '.vcf"');
    header('Content-Length: ' . strlen($vcard));
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: no-cache');
    
    echo $vcard;
    exit;
    
} catch (Exception $e) {
    http_response_code(500);
    error_log('vCard error: ' . $e->getMessage());
    die('Error generating vCard');
}
?>