<?php
/**
 * Konum: /magaza/admin/sayac/ziyaretci-detay.php
 */
require_once '../../includes/db.php';
require_once '../../includes/functions.php';

adminCheck(); // Sisteminizin yetki kontrol fonksiyonu

$ip = $_GET['ip'] ?? null;
if (!$ip) die("IP adresi belirtilmedi.");

// Ziyaretçi loglarını çek (En yeniden en eskiye)
$sql = "SELECT * FROM visitor_logs WHERE ip_address = ? ORDER BY id DESC LIMIT 500";
$stmt = $db->prepare($sql);
$stmt->execute([$ip]);
$logs = $stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($logs)) die("<div class='alert alert-warning m-4'>Kayıt bulunamadı.</div>");

$first_visit = end($logs); // En eski kayıt (dizinin sonu)
$last_visit = reset($logs); // En yeni kayıt (dizinin başı)
$total_views = count($logs);

// --- 1. EN GÜNCEL KULLANICI VE OTURUM BİLGİSİNİ BUL ---
$active_user_id = null;
$active_session = null;

foreach($logs as $l) {
    if (!$active_user_id && !empty($l['user_id'])) $active_user_id = $l['user_id'];
    if (!$active_session && !empty($l['session_token'])) $active_session = $l['session_token'];
    
    // İkisini de bulduysak daha fazla geriye gitmeye gerek yok
    if ($active_user_id && $active_session) break;
}

// Eğer loglarda user_id yoksa ama aktif bir session varsa, Carts (Sepet) tablosundan kullanıcıyı doğrula
if (!$active_user_id && $active_session) {
    $u_stmt = $db->prepare("SELECT user_id FROM carts WHERE session_token = ? AND user_id IS NOT NULL ORDER BY id DESC LIMIT 1");
    $u_stmt->execute([$active_session]);
    $active_user_id = $u_stmt->fetchColumn();
}

// Kullanıcı Durumunu Hazırla
$user_status = '<span class="fw-bold fs-5 text-secondary"><i class="bi bi-person"></i> Misafir</span>';
if ($active_user_id) {
    $u_stmt = $db->prepare("SELECT name, surname FROM users WHERE id = ?");
    $u_stmt->execute([$active_user_id]);
    $user = $u_stmt->fetch();
    if($user) {
        $user_status = '<span class="fw-bold fs-5 text-primary"><i class="bi bi-person-check-fill"></i> ' . htmlspecialchars($user['name'] . ' ' . $user['surname']) . '</span>';
    }
}

// --- 2. GÜNCEL SEPET DURUMUNU BUL ---
$sepet_bilgisi = '<span class="d-block small fw-bold text-muted text-uppercase mb-1">Sepet Durumu</span><span class="fw-bold fs-5 text-secondary">Boş</span>';

if ($active_session) {
    $cart_stmt = $db->prepare("
        SELECT SUM(ci.quantity) as toplam_urun, SUM(ci.quantity * p.price) as sepet_tutari 
        FROM cart_items ci 
        JOIN carts c ON ci.cart_id = c.id 
        JOIN products p ON ci.product_id = p.id 
        WHERE c.session_token = ?
    ");
    $cart_stmt->execute([$active_session]);
    $sepet = $cart_stmt->fetch();
    
    if($sepet && $sepet['toplam_urun'] > 0) {
        $sepet_bilgisi = '<span class="d-block small fw-bold text-danger text-uppercase mb-1"><i class="bi bi-cart-fill"></i> Sepeti Dolu</span>
                          <span class="fw-bold fs-5 text-dark">' . $sepet['toplam_urun'] . ' Ürün <span class="text-success fs-6">(' . formatPrice($sepet['sepet_tutari']) . ')</span></span>';
    }
}

// --- URL KAYNAK ANALİZİ FONKSİYONU ---
function getSourceInfo($url) {
    if ($url == 'direct' || empty($url)) return ['text' => 'Doğrudan Giriş', 'icon' => 'bi-box-arrow-in-right'];
    if ($url == 'site_ici') return ['text' => 'Site İçi Dolaşım', 'icon' => 'bi-arrow-repeat'];
    
    $host = parse_url($url, PHP_URL_HOST);
    if (strpos($host, 'google') !== false) return ['text' => 'Google Arama', 'icon' => 'bi-google text-success'];
    if (strpos($host, 'instagram') !== false) return ['text' => 'Instagram', 'icon' => 'bi-instagram text-danger'];
    if (strpos($host, 'facebook') !== false) return ['text' => 'Facebook', 'icon' => 'bi-facebook text-primary'];
    if (strpos($host, 'twitter') !== false || strpos($host, 'x.com') !== false) return ['text' => 'X (Twitter)', 'icon' => 'bi-twitter-x text-dark'];
    
    return ['text' => htmlspecialchars(substr($url, 0, 35)).'...', 'icon' => 'bi-link-45deg text-secondary'];
}

require_once '../header.php';
?>

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-12 d-flex align-items-center">
        <a href="stats.php" class="btn btn-light border shadow-sm me-3"><i class="bi bi-arrow-left"></i></a>
        <div>
            <h2 class="fw-bold mb-0">Ziyaretçi: <span class="badge bg-light text-primary border font-monospace"><?= htmlspecialchars($ip) ?></span></h2>
            <p class="text-muted small mb-0 mt-1">Bu IP adresinin sitedeki ayak izleri.</p>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4 bg-light">
    <div class="card-body p-4">
        <div class="row text-center text-md-start align-items-center">
            <div class="col-md-3 mb-3 mb-md-0 border-md-end border-light-subtle">
                <span class="d-block small fw-bold text-muted text-uppercase mb-1">İlk Görülme</span>
                <span class="fw-bold fs-5 text-dark"><?= isset($first_visit['created_at']) ? date('d.m.Y H:i', strtotime($first_visit['created_at'])) : '-' ?></span>
            </div>
            <div class="col-md-3 mb-3 mb-md-0 border-md-end border-light-subtle">
                <span class="d-block small fw-bold text-muted text-uppercase mb-1">Sayfa Gezdi</span>
                <span class="fw-bold fs-4 text-primary"><?= $total_views ?></span>
            </div>
            <div class="col-md-3 mb-3 mb-md-0 border-md-end border-light-subtle">
                <span class="d-block small fw-bold text-muted text-uppercase mb-1">Müşteri Kimliği</span>
                <?= $user_status ?>
            </div>
            <div class="col-md-3">
                <?= $sepet_bilgisi ?>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-5 text-dark">
    <div class="card-body p-4">
        <h5 class="fw-bold mb-4 border-bottom pb-3"><i class="bi bi-geo-alt-fill text-danger me-2"></i> Ziyaretçi Yolculuğu</h5>
        
        <div class="border-start border-2 border-primary ms-3 ps-4 position-relative">
            <?php foreach($logs as $log): 
                $is_conversion = (strpos($log['request_url'], 'kayit.php') !== false || strpos($log['request_url'], 'sepet') !== false || strpos($log['request_url'], 'odeme') !== false);
                $color = $is_conversion ? 'success' : 'secondary';
                $icon = $is_conversion ? 'bi-check-lg' : 'bi-cursor-fill';
                $visitTime = isset($log['created_at']) ? strtotime($log['created_at']) : time();
                
                $sourceData = getSourceInfo($log['referer_url']);
            ?>
            <div class="mb-4 position-relative">
                <span class="position-absolute top-0 start-0 translate-middle p-2 bg-<?= $color ?> rounded-circle border border-white" style="left: -1.5rem !important; border-width: 4px !important;">
                    <i class="bi <?= $icon ?> text-white" style="font-size: 0.7rem; line-height: 0;"></i>
                </span>
                
                <div class="card border border-light bg-light shadow-sm">
                    <div class="card-body p-3 d-flex flex-column flex-md-row justify-content-between align-items-md-start">
                        <div>
                            <div class="fw-bold text-dark mb-1" style="word-break: break-all;">
                                <?= htmlspecialchars($log['request_url']) ?>
                            </div>
                            <div class="small text-muted d-flex align-items-center fw-medium">
                                <i class="<?= $sourceData['icon'] ?> me-2 fs-6"></i>
                                <?= $sourceData['text'] ?>
                            </div>
                        </div>
                        <div class="text-md-end mt-2 mt-md-0 min-vw-10">
                            <div class="fw-bold text-secondary"><?= date('H:i:s', $visitTime) ?></div>
                            <div class="small text-muted" style="font-size: 0.7rem;"><?= date('d.m.Y', $visitTime) ?></div>
                        </div>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<?php require_once '../footer.php'; ?>