<?php
// --- AYARLAR VE GÜVENLİK ---
$baseDir = '../../../deppo/reports/'; 
$currentMonth = date('Y_m'); 

// 1. Ay Seçimi ve Dosya Yolu
$selectedMonth = (isset($_GET['m']) && preg_match('/^\d{4}_\d{2}$/', $_GET['m'])) ? $_GET['m'] : $currentMonth;
$targetFile = $baseDir . 'ads_report_' . $selectedMonth . '.json';

// --- DOSYA SİLME İŞLEMİ ---
if (isset($_GET['durum']) && $_GET['durum'] === 'delete_file') {
    if (file_exists($targetFile)) unlink($targetFile);
    $cleanUrl = "?ne=" . ($_GET['ne'] ?? '') . "&islem=" . ($_GET['islem'] ?? '') . "&id=" . ($_GET['id'] ?? '');
    echo "<script>window.location.href='$cleanUrl';</script>";
    exit;
}

// --- DOSYA LİSTESİ ---
$files = glob($baseDir . 'ads_report_*.json');
$availableMonths = [];
foreach ($files as $f) {
    if (preg_match('/ads_report_(\d{4}_\d{2})\.json$/', $f, $m)) $availableMonths[] = $m[1];
}
$availableMonths = array_unique($availableMonths);
rsort($availableMonths); 

// --- VERİ OKUMA VE ANALİZ ---
$hasData = false;
$stats = [
    'today_total' => 0,  // Bugün Toplam
    'week_total'  => 0,  // Bu Hafta Toplam
    'month_total' => 0,  // Bu Ay Toplam
    'month_unique'=> 0   // Bu Ay Uniq
];
$dailyStats = [];
$dayOfWeekJS = [];
$topIps = [];

if (file_exists($targetFile)) {
    $jsonRaw = file_get_contents($targetFile);
    $allData = json_decode($jsonRaw, true);
    $reqId = $_GET['id'] ?? null;
    
    if ($allData && $reqId && isset($allData[$reqId])) {
        $report = $allData[$reqId];
        $hasData = true; 
        
        $ipStats = [];
        $dayOfWeekStats = array_fill(0, 7, 0);
        $days = ['Pazar', 'Pazartesi', 'Salı', 'Çarşamba', 'Perşembe', 'Cuma', 'Cumartesi'];

        // Tarih Hesaplamaları için bugünün değerleri
        $todayStr = date('d.m.Y');
        $currentYearWeek = date('oW'); // Yıl ve Hafta numarası (Örn: 202512)

        foreach ($report as $date => $row) {
            $t = (int)$row['total'];
            $u = (int)$row['unique'];
            
            // 1. AYLIK TOPLAM (Zaten dosyadaki her şey bu aya ait)
            $stats['month_total'] += $t;
            $stats['month_unique'] += $u;

            // 2. BUGÜN TOPLAM
            if ($date === $todayStr) {
                $stats['today_total'] += $t;
            }

            // 3. BU HAFTA TOPLAM
            // Tarih formatı d.m.Y olduğu için tireye çevirip zaman damgası alıyoruz
            $loopTs = strtotime(str_replace('.', '-', $date));
            $loopYearWeek = date('oW', $loopTs);
            
            if ($loopYearWeek === $currentYearWeek) {
                $stats['week_total'] += $t;
            }

            // Grafik Verileri
            $dailyStats[] = [$date, $t, $u];
            $dIndex = date('w', $loopTs); 
            $dayOfWeekStats[$dIndex] += $t;
            
            // IP Analizi
            if (isset($row['ips']) && is_array($row['ips'])) {
                foreach ($row['ips'] as $ip) {
                    if (!isset($ipStats[$ip])) $ipStats[$ip] = 0;
                    $ipStats[$ip]++; 
                }
            }
        }
        
        // IP Sıralama (En çok görünen en üstte)
        arsort($ipStats);
        // Sadece ilk 50 IP'yi alalım ki tablo çok şişmesin
        $topIps = array_slice($ipStats, 0, 50); 
        
        // Haftalık Grafik Formatı
        foreach ($dayOfWeekStats as $k => $v) {
            $dayOfWeekJS[] = [$days[$k], $v];
        }
    }
}
?>

<style>
    /* KPI Kartları - Renk ve Düzen */
    .kpi-card { 
        background: #fff; 
        padding: 15px; 
        border-radius: 8px; 
        border: 1px solid #e0e0e0; 
        text-align: center; 
        box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        transition: transform 0.2s;
    }
    .kpi-card:hover { transform: translateY(-3px); box-shadow: 0 4px 8px rgba(0,0,0,0.1); }
    .kpi-val { font-size: 24px; font-weight: bold; color: #333; display: block; margin-bottom: 5px;}
    .kpi-label { font-size: 13px; color: #666; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
    
    .chart-box { background: #fff; border: 1px solid #ddd; border-radius: 6px; padding: 10px; margin-bottom: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.05); }
    .no-data-alert { background: #fff3cd; color: #856404; padding: 20px; border: 1px solid #ffeeba; border-radius: 5px; text-align: center; }
    
    /* Scrollable Table CSS */
    .scrollable-table {
        width: 100%;
        height: 260px; /* Sabit yükseklik */
        overflow-y: auto; /* Dikey scroll */
        overflow-x: hidden;
    }
    
    /* Google Table CSS özelleştirme (Ufak makyaj) */
    .google-visualization-table-table { width: 100% !important; }
    .google-visualization-table-tr-head { background-color: #f8f9fa !important; }
</style>

<fieldset style="position: relative; padding-top: 15px;">

    <legend>{<b>ID: <?php echo $_GET['id'] ?? '-';?></b>} Trafik Analiz Raporu</legend>
    
    <div style="position: absolute; right: 15px; top: -35px; display: flex; align-items: center; gap: 10px;">
        <select name="m" onchange="self.location.href=this.options[this.selectedIndex].value;" style="padding: 6px; border:1px solid #ccc; border-radius: 4px; background: #fff;">
            <?php 
            $trAylar = [ 1 => 'Ocak', 2 => 'Şubat', 3 => 'Mart', 4 => 'Nisan', 5 => 'Mayıs', 6 => 'Haziran', 7 => 'Temmuz', 8 => 'Ağustos', 9 => 'Eylül', 10 => 'Ekim', 11 => 'Kasım', 12 => 'Aralık' ];
            if (!in_array($selectedMonth, $availableMonths) && $selectedMonth == $currentMonth) array_unshift($availableMonths, $currentMonth);

            foreach ($availableMonths as $m): 
                $ts = strtotime(str_replace('_', '-', $m) . '-01');
                $ayLabel = $trAylar[(int)date('n', $ts)] . ' ' . date('Y', $ts);
                $url = "?ne=".($_GET['ne']??'')."&islem=".($_GET['islem']??'')."&id=".($_GET['id']??'')."&m=".$m;
            ?>
                <option value="<?php echo $url; ?>" <?php echo ($m == $selectedMonth ? 'selected' : ''); ?>><?php echo $ayLabel; ?></option>
            <?php endforeach; ?>
        </select>

        <?php if (file_exists($targetFile)): ?>
        <div onclick="if(confirm('BU AYIN raporunu silmek istediğine emin misin?')) location.href='?ne=<?php echo $_GET["ne"]??'';?>&islem=<?php echo $_GET["islem"]??'';?>&id=<?php echo $_GET["id"]??'';?>&m=<?php echo $selectedMonth; ?>&durum=delete_file'" 
             title="Bu Ayın Raporunu Sil" class="v3-btn" 
             style="cursor:pointer; padding: 5px; background: #ffebee; border-radius: 4px; border: 1px solid #ffcdd2;">
            <img src="https://cdn-icons-png.flaticon.com/64/9790/9790368.png" style="height:20px; vertical-align: middle;">
        </div>
        <?php endif; ?>
    </div>

    <?php if ($hasData): ?>
        
        <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 15px; margin-bottom: 20px;">
            <div class="kpi-card">
                <span class="kpi-val" style="color: #E91E63;"><?php echo number_format($stats['today_total']); ?></span>
                <span class="kpi-label">Bugün Toplam</span>
            </div>
            <div class="kpi-card">
                <span class="kpi-val" style="color: #FF9800;"><?php echo number_format($stats['week_total']); ?></span>
                <span class="kpi-label">Bu Hafta Toplam</span>
            </div>
            <div class="kpi-card">
                <span class="kpi-val" style="color: #2196F3;"><?php echo number_format($stats['month_total']); ?></span>
                <span class="kpi-label">Bu Ay Toplam</span>
            </div>
            <div class="kpi-card">
                <span class="kpi-val" style="color: #4CAF50;"><?php echo number_format($stats['month_unique']); ?></span>
                <span class="kpi-label">Bu Ay Unique</span>
            </div>
        </div>

        <div style="width:100%; min-height:100px;">
            <div class="chart-box">
                <div id="timeline_chart" style="width: 100%; height: 350px;"></div>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                <div class="chart-box">
                    <div id="day_chart" style="width: 100%; height: 300px;"></div>
                </div>
                <div class="chart-box">
                    <div style="font-weight:bold; padding:10px; border-bottom:1px solid #eee; background:#fafafa;">
                        🏆 En Sadık Ziyaretçiler <span style="font-size:11px; color:#888; font-weight:normal;">(Gün Bazlı Ziyaret)</span>
                    </div>
                    <div class="scrollable-table">
                        <div id="ip_table"></div>
                    </div>
                </div>
            </div>
        </div>

    <?php else: ?>
        <div class="no-data-alert">
            <img src="https://cdn-icons-png.flaticon.com/512/7486/7486754.png" style="height: 64px; opacity: 0.6; margin-bottom: 10px;"><br>
            <strong>Henüz veri bulunamadı.</strong><br>
            <small>Reklam tıklandığında rapor oluşacaktır.</small>
        </div>
    <?php endif; ?>

</fieldset>

<?php if ($hasData): ?>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load('current', { packages: ['corechart', 'bar', 'table'] });
    google.charts.setOnLoadCallback(drawDashboard);

    function drawDashboard() {
        // 1. ZAMAN ÇİZELGESİ
        var timelineData = new google.visualization.DataTable();
        timelineData.addColumn('string', 'Tarih');
        timelineData.addColumn('number', 'Toplam');
        timelineData.addColumn('number', 'Tekil');
        timelineData.addRows(<?php echo json_encode($dailyStats); ?>);

        var timelineOptions = {
            title: 'Günlük Trafik Seyri',
            hAxis: {title: 'Tarih',  titleTextStyle: {color: '#333'}},
            vAxis: {minValue: 0},
            areaOpacity: 0.1, colors: ['#2196F3', '#4CAF50'],
            legend: { position: 'top' },
            width: '100%', height: 350
        };
        new google.visualization.AreaChart(document.getElementById('timeline_chart')).draw(timelineData, timelineOptions);

        // 2. HAFTALIK GRAFİK
        var dayData = new google.visualization.DataTable();
        dayData.addColumn('string', 'Gün');
        dayData.addColumn('number', 'Tıklama');
        dayData.addRows(<?php echo json_encode($dayOfWeekJS); ?>);

        var dayOptions = {
            title: 'Haftanın En Yoğun Günleri',
            legend: { position: 'none' }, colors: ['#FF9800'],
            width: '100%', height: 300
        };
        new google.visualization.ColumnChart(document.getElementById('day_chart')).draw(dayData, dayOptions);

        // 3. IP TABLOSU
        var ipData = new google.visualization.DataTable();
        ipData.addColumn('string', 'IP Adresi');
        ipData.addColumn('number', 'Tekrar (Gün)'); // Başlığı değiştirdim
        var rawIps = [
            <?php foreach($topIps as $ip => $count) echo "['$ip', $count],"; ?>
        ];
        ipData.addRows(rawIps);

        var tableOptions = { 
            showRowNumber: true, 
            width: '100%', 
            // height özelliği burdan kaldırıldı, CSS ile scroll verilecek
            cssClassNames: { headerRow: 'header-row-custom' }
        };
        new google.visualization.Table(document.getElementById('ip_table')).draw(ipData, tableOptions);
    }

    // Resize Olayları
    window.addEventListener('resize', drawDashboard);
    if (typeof ResizeObserver !== 'undefined') {
        var ro = new ResizeObserver(function() {
            window.requestAnimationFrame(function() {
                if (document.getElementById('timeline_chart').offsetWidth > 0) drawDashboard();
            });
        });
        ['timeline_chart', 'day_chart', 'ip_table'].forEach(id => {
            var el = document.getElementById(id);
            if(el) ro.observe(el);
        });
    }
</script>
<?php endif; ?>