<?php
/**
 * Konum: /magaza/admin/sayac/stats.php
 * İşlev: Genel Trafik ve Özet Analiz Dashboard'u
 */
date_default_timezone_set('Europe/Istanbul');
require_once '../../includes/db.php';
require_once '../../includes/functions.php';

adminCheck(); // Sisteminizin yetki kontrol fonksiyonu

// İstatistikleri Sıfırla
if (isset($_GET['clear_stats']) && $_GET['clear_stats'] == 'true') {
    $db->query("TRUNCATE TABLE visitor_logs");
    $db->query("TRUNCATE TABLE product_shares"); 
    header("Location: stats.php"); exit;
}

// Tarih Filtresi
$filterDate = $_GET['date'] ?? date('Y-m-d');

// --- 1. ÖZET VERİLER ---
$stats = [
    'total' => $db->query("SELECT COUNT(*) FROM visitor_logs")->fetchColumn(),
    'today' => $db->query("SELECT COUNT(*) FROM visitor_logs WHERE visit_date = '$filterDate'")->fetchColumn(),
    'unique_today' => $db->query("SELECT COUNT(DISTINCT ip_address) FROM visitor_logs WHERE visit_date = '$filterDate'")->fetchColumn()
];

// --- 2. KAYNAK ANALİZİ ---
$sourcesSql = "SELECT referer_url, COUNT(*) as count FROM visitor_logs WHERE visit_date = '$filterDate' GROUP BY referer_url ORDER BY count DESC LIMIT 10";
$sources = $db->query($sourcesSql)->fetchAll(PDO::FETCH_ASSOC);

// --- 3. POPÜLER SAYFALAR ---
$pagesSql = "SELECT request_url, COUNT(*) as count FROM visitor_logs WHERE visit_date = '$filterDate' GROUP BY request_url ORDER BY count DESC LIMIT 10";
$pages = $db->query($pagesSql)->fetchAll(PDO::FETCH_ASSOC);

// --- 4. CANLI ZİYARETÇİLER ---
$visitorsSql = "
    SELECT 
        ip_address, 
        MAX(visit_date) as last_seen, 
        COUNT(*) as page_views,
        (SELECT request_url FROM visitor_logs v2 WHERE v2.ip_address = visitor_logs.ip_address ORDER BY v2.id DESC LIMIT 1) as last_page,
        (SELECT referer_url FROM visitor_logs v3 WHERE v3.ip_address = visitor_logs.ip_address ORDER BY v3.id ASC LIMIT 1) as first_source
    FROM visitor_logs 
    WHERE visit_date = '$filterDate'
    GROUP BY ip_address 
    ORDER BY last_seen DESC 
    LIMIT 50
";
$visitors = $db->query($visitorsSql)->fetchAll(PDO::FETCH_ASSOC);


// --- ÖZET: PAYLAŞIM VE ETKİLEŞİM ANALİZİ (PEM İÇİN) ---
$platformStatsSql = "SELECT platform, COUNT(*) as count FROM product_shares WHERE DATE(created_at) = '$filterDate' GROUP BY platform";
$platformData = $db->query($platformStatsSql)->fetchAll(PDO::FETCH_ASSOC);
$platformStats = ['whatsapp' => 0, 'facebook' => 0, 'twitter' => 0, 'copy' => 0];
$toplam_paylasim = 0;
foreach($platformData as $pd) {
    $platformStats[$pd['platform']] = $pd['count'];
    $toplam_paylasim += $pd['count'];
}

$viralProductsSql = "
    SELECT ps.product_id, p.name as product_name, p.slug, COUNT(*) as share_count 
    FROM product_shares ps 
    JOIN products p ON ps.product_id = p.id 
    WHERE DATE(ps.created_at) = '$filterDate' 
    GROUP BY ps.product_id 
    ORDER BY share_count DESC 
    LIMIT 5
";
$viralProducts = $db->query($viralProductsSql)->fetchAll(PDO::FETCH_ASSOC);
// ------------------------------------------

// --- ÖZET: MÜŞTERİ ETKİLEŞİM (MUS İÇİN) ---
$inCartCount = $db->query("SELECT SUM(quantity) FROM cart_items ci JOIN carts c ON ci.cart_id = c.id")->fetchColumn() ?: 0;
$favCount = $db->query("SELECT COUNT(*) FROM favorites")->fetchColumn() ?: 0;
$alertCount = $db->query("SELECT COUNT(*) FROM price_alerts WHERE status = 0")->fetchColumn() ?: 0;
// ------------------------------------------

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

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

<div class="row mb-4 align-items-center text-dark">
    <div class="col-xl-4 col-md-12 mb-3 mb-xl-0">
        <h2 class="fw-bold mb-0"><i class="bi bi-pie-chart-fill text-primary me-2"></i>Trafik Analizi</h2>
        <p class="text-muted small mb-0 mt-1">Site ziyaretçi kaynakları ve davranışları.</p>
    </div>
    <div class="col-xl-8 col-md-12 text-xl-end d-flex flex-wrap gap-2 justify-content-xl-end">
        <a href="mus.php" class="btn btn-outline-danger fw-bold shadow-sm"><i class="bi bi-magnet-fill me-1"></i> Müşteri (MUS)</a>
        <a href="pem.php" class="btn btn-outline-success fw-bold shadow-sm"><i class="bi bi-share-fill me-1"></i> Paylaşım (PEM)</a>
        <a href="../index.php" class="btn btn-light border shadow-sm fw-bold"><i class="bi bi-house-door-fill me-1"></i> Panele Dön</a>
        <a href="?clear_stats=true" onclick="return confirm('TÜM GEÇMİŞ VERİLER SİLİNECEK! Emin misiniz?')" class="btn btn-danger shadow-sm fw-bold"><i class="bi bi-trash-fill me-1"></i> Temizle</a>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4">
    <div class="card-body bg-light rounded-3 p-3">
        <form action="stats.php" method="GET" class="d-flex align-items-center gap-2">
            <span class="fw-bold text-muted ms-2 d-none d-md-inline">Tarih:</span>
            <input type="date" name="date" class="form-control border-0 shadow-sm fw-bold text-muted" style="max-width: 200px;" value="<?= htmlspecialchars($filterDate) ?>">
            <button type="submit" class="btn btn-primary fw-bold shadow-sm px-4"><i class="bi bi-filter me-1"></i> Filtrele</button>
        </form>
    </div>
</div>

<div class="row mb-4 text-dark">
    <div class="col-md-4 mb-3 mb-md-0">
        <div class="card border-0 shadow-sm position-relative overflow-hidden h-100">
            <div class="card-body p-4">
                <i class="bi bi-people-fill position-absolute text-primary opacity-25" style="font-size: 5rem; top: -10px; right: -10px;"></i>
                <h6 class="text-muted fw-bold text-uppercase" style="font-size: 0.8rem; letter-spacing: 1px;">Bugün (Tekil Ziyaretçi)</h6>
                <h2 class="fw-black mb-0 display-5 fw-bold"><?= number_format($stats['unique_today']) ?></h2>
                <span class="badge bg-primary-subtle text-primary border border-primary-subtle mt-2">Farklı IP Adresi</span>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-3 mb-md-0">
        <div class="card border-0 shadow-sm position-relative overflow-hidden h-100">
            <div class="card-body p-4">
                <i class="bi bi-eye-fill position-absolute text-info opacity-25" style="font-size: 5rem; top: -10px; right: -10px;"></i>
                <h6 class="text-muted fw-bold text-uppercase" style="font-size: 0.8rem; letter-spacing: 1px;">Bugün (Sayfa Gösterimi)</h6>
                <h2 class="fw-black mb-0 display-5 fw-bold"><?= number_format($stats['today']) ?></h2>
                <span class="badge bg-info-subtle text-info border border-info-subtle mt-2">Toplam Tıklama</span>
            </div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="card border-0 shadow-sm position-relative overflow-hidden h-100">
            <div class="card-body p-4">
                <i class="bi bi-globe position-absolute text-success opacity-25" style="font-size: 5rem; top: -10px; right: -10px;"></i>
                <h6 class="text-muted fw-bold text-uppercase" style="font-size: 0.8rem; letter-spacing: 1px;">Tüm Zamanlar</h6>
                <h2 class="fw-black mb-0 display-5 fw-bold"><?= number_format($stats['total']) ?></h2>
                <span class="badge bg-success-subtle text-success border border-success-subtle mt-2">Toplam Veri</span>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4 text-dark">
    <div class="col-12">
        <div class="card shadow-sm border-0">
            <div class="card-body bg-white rounded-3 p-4 d-flex justify-content-between align-items-center flex-wrap gap-3">
                <div class="d-flex align-items-center">
                    <div class="bg-danger bg-opacity-10 text-danger rounded p-3 me-3"><i class="bi bi-magnet-fill fs-3"></i></div>
                    <div>
                        <h5 class="fw-bold mb-0">Müşteri Etkileşim Özeti</h5>
                        <p class="text-muted small mb-0">Ziyaretçilerin favori, sepet ve indirim beklentileri.</p>
                    </div>
                </div>
                <div class="d-flex gap-4 text-center">
                    <div>
                        <h4 class="fw-bold text-primary mb-0"><?= $inCartCount ?></h4>
                        <span class="small text-muted fw-bold">Sepette Bekleyen</span>
                    </div>
                    <div>
                        <h4 class="fw-bold text-danger mb-0"><?= $favCount ?></h4>
                        <span class="small text-muted fw-bold">Favorilenen Ürün</span>
                    </div>
                    <div>
                        <h4 class="fw-bold text-warning mb-0"><?= $alertCount ?></h4>
                        <span class="small text-muted fw-bold">Fiyat Alarmı</span>
                    </div>
                </div>
                <a href="mus.php" class="btn btn-outline-danger fw-bold px-4 rounded-pill">Tüm Detayları Gör (MUS) <i class="bi bi-arrow-right ms-1"></i></a>
            </div>
        </div>
    </div>
</div>


<div class="row mb-4 text-dark">
    <div class="col-md-5 mb-4 mb-md-0">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-bottom-0 pt-4 pb-0 d-flex justify-content-between align-items-center">
                <h6 class="fw-bold text-uppercase mb-0"><i class="bi bi-share-fill text-success me-2"></i> Paylaşım Dağılımı</h6>
            </div>
            <div class="card-body pb-2">
                <?php if($toplam_paylasim == 0): ?>
                    <p class="text-center text-muted small fst-italic py-4">Bugün henüz ürün paylaşılmadı.</p>
                <?php else: ?>
                    <div class="d-flex justify-content-center align-items-center mb-4">
                        <h1 class="display-3 fw-bold text-dark mb-0 me-2"><?= $toplam_paylasim ?></h1>
                        <span class="text-muted small">Toplam<br>Paylaşım</span>
                    </div>
                    
                    <?php 
                    $platforms = [
                        'whatsapp' => ['icon' => 'bi-whatsapp', 'color' => '#25D366', 'name' => 'WhatsApp'],
                        'facebook' => ['icon' => 'bi-facebook', 'color' => '#1877F2', 'name' => 'Facebook'],
                        'twitter'  => ['icon' => 'bi-twitter-x', 'color' => '#000000', 'name' => 'X (Twitter)'],
                        'copy'     => ['icon' => 'bi-link-45deg', 'color' => '#6c757d', 'name' => 'Kopyalananlar']
                    ];
                    
                    foreach($platforms as $key => $p): 
                        $count = $platformStats[$key];
                        $percent = $toplam_paylasim > 0 ? round(($count / $toplam_paylasim) * 100) : 0;
                    ?>
                        <div class="mb-3">
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <span class="fw-bold small text-secondary">
                                    <i class="<?= $p['icon'] ?> me-1" style="color: <?= $p['color'] ?>"></i> <?= $p['name'] ?>
                                </span>
                                <span class="fw-bold small"><?= $count ?> <span class="text-muted fw-normal">(%<?= $percent ?>)</span></span>
                            </div>
                            <div class="progress" style="height: 6px;">
                                <div class="progress-bar" role="progressbar" style="width: <?= $percent ?>%; background-color: <?= $p['color'] ?>"></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <div class="card-footer bg-white border-top-0 pb-3 text-center">
                <a href="pem.php" class="btn btn-sm btn-outline-success fw-bold w-100 rounded-pill">Platform Analizi (PEM) <i class="bi bi-arrow-right ms-1"></i></a>
            </div>
        </div>
    </div>
    
    <div class="col-md-7">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-bottom-0 pt-4 pb-0 d-flex justify-content-between align-items-center">
                <h6 class="fw-bold text-uppercase mb-0"><i class="bi bi-fire text-danger me-2"></i> Viral Olanlar (Top 5)</h6>
            </div>
            <div class="card-body p-0 mt-3">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <tbody>
                            <?php if(empty($viralProducts)): ?>
                                <tr><td class="text-center text-muted small fst-italic py-5">Bugün henüz viral ürününüz yok.</td></tr>
                            <?php endif; ?>
                            <?php foreach($viralProducts as $index => $vp): ?>
                            <tr>
                                <td class="ps-4">
                                    <span class="badge <?= $index == 0 ? 'bg-danger' : ($index == 1 ? 'bg-warning text-dark' : 'bg-light text-dark border') ?> me-2">
                                        <?= $index == 0 ? '<i class="bi bi-trophy-fill"></i>' : $index + 1 ?>
                                    </span>
                                    <a href="../../urun-detay.php?slug=<?= htmlspecialchars($vp['slug']) ?>" target="_blank" class="small fw-bold text-dark text-decoration-none border-bottom border-secondary border-opacity-25">
                                        <?= htmlspecialchars(substr($vp['product_name'], 0, 50)) . (strlen($vp['product_name']) > 50 ? '...' : '') ?>
                                    </a>
                                </td>
                                <td class="text-end pe-4">
                                    <span class="badge bg-success rounded-pill px-3 shadow-sm"><i class="bi bi-share-fill me-1"></i> <?= $vp['share_count'] ?></span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <div class="card-footer bg-white border-top-0 pb-3 text-center mt-auto">
                <a href="pem.php" class="btn btn-sm btn-outline-success fw-bold w-100 rounded-pill">Viral Analizi (PEM) <i class="bi bi-arrow-right ms-1"></i></a>
            </div>
        </div>
    </div>
</div>

<div class="row mb-4 text-dark">
    <div class="col-md-6 mb-4 mb-md-0">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-bottom-0 pt-4 pb-0">
                <h6 class="fw-bold text-uppercase mb-0"><i class="bi bi-signpost-split-fill text-warning me-2"></i> Trafik Kaynakları</h6>
            </div>
            <div class="card-body">
                <?php if(empty($sources)): ?>
                    <p class="text-center text-muted small fst-italic">Bugün henüz veri yok.</p>
                <?php endif; ?>
                <?php foreach($sources as $src): 
                    $info = parseSource($src['referer_url']);
                    $percent = $stats['today'] > 0 ? round(($src['count'] / $stats['today']) * 100) : 0;
                ?>
                <div class="mb-3">
                    <div class="d-flex justify-content-between align-items-center mb-1">
                        <span class="fw-bold small text-secondary"><i class="bi <?= $info['icon'] ?> text-<?= $info['color'] ?> me-1"></i> <?= htmlspecialchars($info['text']) ?></span>
                        <span class="fw-bold small"><?= $src['count'] ?> <span class="text-muted fw-normal">(%<?= $percent ?>)</span></span>
                    </div>
                    <div class="progress" style="height: 6px;">
                        <div class="progress-bar bg-<?= $info['color'] ?>" role="progressbar" style="width: <?= $percent ?>%"></div>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
    
    <div class="col-md-6">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-header bg-white border-bottom-0 pt-4 pb-0">
                <h6 class="fw-bold text-uppercase mb-0"><i class="bi bi-file-earmark-text-fill text-primary me-2"></i> Popüler Sayfalar</h6>
            </div>
            <div class="card-body p-0 mt-3">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <tbody>
                            <?php if(empty($pages)): ?>
                                <tr><td class="text-center text-muted small fst-italic py-4">Bugün henüz veri yok.</td></tr>
                            <?php endif; ?>
                            <?php foreach($pages as $index => $page): ?>
                            <tr>
                                <td class="ps-4">
                                    <span class="badge bg-light text-dark border me-2"><?= $index + 1 ?></span>
                                    <span class="small fw-bold text-secondary"><?= htmlspecialchars(substr($page['request_url'], 0, 50)) . (strlen($page['request_url']) > 50 ? '...' : '') ?></span>
                                </td>
                                <td class="text-end pe-4">
                                    <span class="badge bg-primary rounded-pill"><?= $page['count'] ?></span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-5 text-dark">
    <div class="card-header bg-white pt-4 pb-3 d-flex justify-content-between align-items-center">
        <h6 class="fw-bold text-uppercase mb-0"><i class="bi bi-activity text-danger me-2"></i> Canlı Ziyaretçiler (IP Bazlı)</h6>
        <span class="badge bg-light border text-dark"><?= count($visitors) ?> Kişi</span>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-light">
                    <tr>
                        <th class="ps-4">Ziyaretçi IP</th>
                        <th>Kaynak</th>
                        <th>Son Gezilen Sayfa</th>
                        <th class="text-center">Gezilen</th>
                        <th>Son Görülme</th>
                        <th class="text-end pe-4">İşlem</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($visitors)): ?>
                        <tr><td colspan="6" class="p-4 text-center text-muted fw-bold">Bugün henüz ziyaretçi yok.</td></tr>
                    <?php endif; ?>
                    <?php foreach($visitors as $v): 
                        $srcInfo = parseSource($v['first_source']);
                    ?>
                    <tr>
                        <td class="ps-4 fw-bold font-monospace">
                            <?= htmlspecialchars($v['ip_address']) ?>
                            <?php if($v['page_views'] > 15): ?><span class="badge bg-danger ms-1" style="font-size:0.6rem;">Aktif</span><?php endif; ?>
                        </td>
                        <td><span class="badge bg-light text-dark border"><i class="bi <?= $srcInfo['icon'] ?> text-<?= $srcInfo['color'] ?> me-1"></i> <?= $srcInfo['text'] ?></span></td>
                        <td class="small text-muted" title="<?= $v['last_page'] ?>"><?= htmlspecialchars(substr($v['last_page'], 0, 30)) ?>...</td>
                        <td class="text-center"><span class="badge bg-secondary rounded-circle"><?= $v['page_views'] ?></span></td>
                        <td class="small fw-bold text-muted"><i class="bi bi-clock me-1"></i> <?= $v['last_seen'] ? date('H:i', strtotime($v['last_seen'])) : '-' ?></td>
                        <td class="text-end pe-4">
                            <a href="ziyaretci-detay.php?ip=<?= $v['ip_address'] ?>" class="btn btn-sm btn-outline-primary fw-bold">İncele <i class="bi bi-search ms-1"></i></a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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