<?php
/**
 * Konum: /magaza/admin/sayac/pem.php
 * İşlev: Sosyal Medya Paylaşım ve Viral Etkileşim Merkezi
 */
date_default_timezone_set('Europe/Istanbul');
require_once '../../includes/db.php';
require_once '../../includes/functions.php';

adminCheck(); // Yetki kontrolü

// --- FİLTRE VERİLERİNİ AL ---
$date_start = $_GET['date_start'] ?? date('Y-m-d', strtotime('-30 days'));
$date_end = $_GET['date_end'] ?? date('Y-m-d');
$category_id = isset($_GET['category_id']) && $_GET['category_id'] !== '' ? (int)$_GET['category_id'] : '';
$platform_filter = $_GET['platform'] ?? '';

// --- KATEGORİLERİ ÇEK (Filtre Dropdown'u İçin) ---
$categories = $db->query("SELECT id, name FROM categories WHERE status = 1 ORDER BY name ASC")->fetchAll(PDO::FETCH_ASSOC);

// --- SQL ŞARTLARINI OLUŞTUR ---
$startDateStr = $date_start . " 00:00:00";
$endDateStr = $date_end . " 23:59:59";
$whereSql = "WHERE ps.created_at BETWEEN '$startDateStr' AND '$endDateStr'";

if ($category_id) {
    $whereSql .= " AND p.category_id = {$category_id}";
}
if ($platform_filter) {
    $whereSql .= " AND ps.platform = " . $db->quote($platform_filter);
}

// 1. TOPLAM PAYLAŞIM SAYISI
$totalShares = $db->query("SELECT COUNT(*) FROM product_shares ps JOIN products p ON ps.product_id = p.id $whereSql")->fetchColumn();

// 2. PLATFORMLARA GÖRE DAĞILIM
$platformStatsSql = "
    SELECT ps.platform, COUNT(*) as count 
    FROM product_shares ps 
    JOIN products p ON ps.product_id = p.id 
    $whereSql 
    GROUP BY ps.platform 
    ORDER BY count DESC
";
$platformData = $db->query($platformStatsSql)->fetchAll(PDO::FETCH_ASSOC);

$platformStats = ['whatsapp' => 0, 'facebook' => 0, 'twitter' => 0, 'copy' => 0];
foreach($platformData as $pd) {
    $platformStats[$pd['platform']] = $pd['count'];
}

// Platform Tanımları (Renkler ve İkonlar)
$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']
];

// 3. VİRAL ÜRÜNLER (Hangi platformda kaç kere paylaşıldı detayı ile)
$viralProductsSql = "
    SELECT p.name as product_name, p.slug, p.price, p.discount_price, c.name as cat_name, COUNT(ps.id) as total_shares,
    SUM(CASE WHEN ps.platform = 'whatsapp' THEN 1 ELSE 0 END) as wp_shares,
    SUM(CASE WHEN ps.platform = 'facebook' THEN 1 ELSE 0 END) as fb_shares,
    SUM(CASE WHEN ps.platform = 'twitter' THEN 1 ELSE 0 END) as tw_shares,
    SUM(CASE WHEN ps.platform = 'copy' THEN 1 ELSE 0 END) as cp_shares
    FROM product_shares ps 
    JOIN products p ON ps.product_id = p.id 
    LEFT JOIN categories c ON p.category_id = c.id
    $whereSql 
    GROUP BY ps.product_id 
    ORDER BY total_shares DESC 
    LIMIT 20
";
$viralProducts = $db->query($viralProductsSql)->fetchAll(PDO::FETCH_ASSOC);

// 4. SON PAYLAŞIM AKIŞI (Canlı Ziyaretçi Hareketi)
$recentSharesSql = "
    SELECT ps.platform, ps.ip_address, ps.created_at, p.name as product_name, p.slug 
    FROM product_shares ps 
    JOIN products p ON ps.product_id = p.id 
    $whereSql 
    ORDER BY ps.created_at DESC 
    LIMIT 15
";
$recentShares = $db->query($recentSharesSql)->fetchAll(PDO::FETCH_ASSOC);

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

<div class="row mb-4 align-items-center text-dark">
    <div class="col-md-8">
        <h2 class="fw-bold mb-0"><i class="bi bi-share-fill text-success me-2"></i>Viral Paylaşım Merkezi</h2>
        <p class="text-muted small mb-0 mt-1">Ürünlerinizin sosyal medyadaki paylaşım istatistikleri ve viral etki analizleri.</p>
    </div>
    <div class="col-md-4 text-md-end mt-3 mt-md-0">
        <a href="stats.php" class="btn btn-light border shadow-sm fw-bold me-2"><i class="bi bi-pie-chart-fill me-1"></i> Trafik</a>
        <a href="mus.php" class="btn btn-light border shadow-sm fw-bold"><i class="bi bi-magnet-fill me-1"></i> Etkileşim</a>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4 text-dark">
    <div class="card-body bg-light rounded-3 p-3">
        <form action="pem.php" method="GET" class="row g-2 align-items-center">
            <div class="col-md-2">
                <span class="fw-bold text-muted ms-2"><i class="bi bi-calendar-range me-1"></i> Filtrele:</span>
            </div>
            <div class="col-md-2">
                <input type="date" name="date_start" class="form-control border-0 shadow-sm fw-bold text-muted" value="<?= htmlspecialchars($date_start) ?>">
            </div>
            <div class="col-md-2">
                <input type="date" name="date_end" class="form-control border-0 shadow-sm fw-bold text-muted" value="<?= htmlspecialchars($date_end) ?>">
            </div>
            <div class="col-md-2">
                <select name="category_id" class="form-select border-0 shadow-sm fw-bold text-muted">
                    <option value="">Tüm Kategoriler</option>
                    <?php foreach($categories as $cat): ?>
                        <option value="<?= $cat['id'] ?>" <?= $category_id == $cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <select name="platform" class="form-select border-0 shadow-sm fw-bold text-muted">
                    <option value="">Tüm Platformlar</option>
                    <option value="whatsapp" <?= $platform_filter == 'whatsapp' ? 'selected' : '' ?>>WhatsApp</option>
                    <option value="facebook" <?= $platform_filter == 'facebook' ? 'selected' : '' ?>>Facebook</option>
                    <option value="twitter" <?= $platform_filter == 'twitter' ? 'selected' : '' ?>>Twitter</option>
                    <option value="copy" <?= $platform_filter == 'copy' ? 'selected' : '' ?>>Kopyalananlar</option>
                </select>
            </div>
            <div class="col-md-2 text-end">
                <button type="submit" class="btn btn-success fw-bold shadow-sm w-100"><i class="bi bi-filter me-1"></i> Uygula</button>
            </div>
        </form>
    </div>
</div>

<div class="row mb-4 text-dark">
    <div class="col-md-4 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-bar-chart-fill text-primary me-2"></i> Platform Dağılımı</h6>
            </div>
            <div class="card-body">
                <?php if($totalShares == 0): ?>
                    <p class="text-center text-muted small fst-italic py-4">Belirtilen kriterlerde paylaşım yok.</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"><?= $totalShares ?></h1>
                        <span class="text-muted small">Toplam<br>Paylaşım</span>
                    </div>
                    
                    <?php foreach($platforms as $key => $p): 
                        $count = $platformStats[$key];
                        $percent = $totalShares > 0 ? round(($count / $totalShares) * 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>
    </div>

    <div class="col-md-8">
        <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 Ürünler Tablosu</h6>
            </div>
            <div class="card-body p-0 mt-3">
                <div class="table-responsive">
                    <table class="table table-hover align-middle mb-0">
                        <thead class="table-light small">
                            <tr>
                                <th class="ps-4">Sıra</th>
                                <th>Ürün Adı</th>
                                <th class="text-center" title="WhatsApp"><i class="bi bi-whatsapp" style="color:#25D366"></i></th>
                                <th class="text-center" title="Facebook"><i class="bi bi-facebook" style="color:#1877F2"></i></th>
                                <th class="text-center" title="Twitter"><i class="bi bi-twitter-x" style="color:#000"></i></th>
                                <th class="text-center" title="Link Kopyalama"><i class="bi bi-link-45deg" style="color:#6c757d"></i></th>
                                <th class="text-end pe-4">Toplam</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($viralProducts)): ?>
                                <tr><td colspan="7" class="text-center text-muted small fst-italic py-5">Veri bulunamadı.</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') ?>">
                                        <?= $index == 0 ? '<i class="bi bi-trophy-fill"></i>' : $index + 1 ?>
                                    </span>
                                </td>
                                <td>
                                    <a href="../../urun-detay.php?slug=<?= htmlspecialchars($vp['slug']) ?>" target="_blank" class="small fw-bold text-dark text-decoration-none d-block text-truncate" style="max-width: 200px;" title="<?= htmlspecialchars($vp['product_name']) ?>">
                                        <?= htmlspecialchars($vp['product_name']) ?>
                                    </a>
                                    <span class="badge bg-light text-secondary border mt-1" style="font-size: 0.65rem;"><?= htmlspecialchars($vp['cat_name'] ?? 'Kategorisiz') ?></span>
                                </td>
                                <td class="text-center small fw-bold text-muted"><?= $vp['wp_shares'] ?: '-' ?></td>
                                <td class="text-center small fw-bold text-muted"><?= $vp['fb_shares'] ?: '-' ?></td>
                                <td class="text-center small fw-bold text-muted"><?= $vp['tw_shares'] ?: '-' ?></td>
                                <td class="text-center small fw-bold text-muted"><?= $vp['cp_shares'] ?: '-' ?></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['total_shares'] ?></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-info me-2"></i> Son Paylaşılanlar Akışı</h6>
    </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">Tarih / Saat</th>
                        <th>Platform</th>
                        <th>Paylaşılan Ürün</th>
                        <th class="text-end pe-4">Ziyaretçi IP</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(empty($recentShares)): ?>
                        <tr><td colspan="4" class="p-4 text-center text-muted fw-bold">Yakın zamanda paylaşım yapılmamış.</td></tr>
                    <?php endif; ?>
                    <?php foreach($recentShares as $rs): 
                        $p_info = $platforms[$rs['platform']] ?? ['icon' => 'bi-share', 'color' => '#6c757d', 'name' => 'Bilinmiyor'];
                    ?>
                    <tr>
                        <td class="ps-4 small text-muted fw-bold">
                            <i class="bi bi-clock me-1"></i> <?= date('d.m.Y H:i', strtotime($rs['created_at'])) ?>
                        </td>
                        <td>
                            <span class="badge bg-light border text-dark">
                                <i class="<?= $p_info['icon'] ?> me-1" style="color: <?= $p_info['color'] ?>"></i> <?= $p_info['name'] ?>
                            </span>
                        </td>
                        <td>
                            <a href="../../urun-detay.php?slug=<?= htmlspecialchars($rs['slug']) ?>" target="_blank" class="small fw-bold text-dark text-decoration-none">
                                <?= htmlspecialchars(substr($rs['product_name'], 0, 40)) . (strlen($rs['product_name']) > 40 ? '...' : '') ?>
                            </a>
                        </td>
                        <td class="text-end pe-4 font-monospace small text-muted">
                            <?= htmlspecialchars($rs['ip_address']) ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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