<?php
// reports.php - ENTERPRISE EDITION V3
require 'config.php';

// Preluam tipul de raport cerut
$type = isset($_GET['type']) ? $_GET['type'] : 'all';

// --- LOGICA DE "CITIRE" (MARK AS READ) ---
if ($type !== 'all') {
    $stmtMark = $pdo->prepare("INSERT INTO report_views (report_key, last_viewed_at) VALUES (?, NOW()) ON DUPLICATE KEY UPDATE last_viewed_at = NOW()");
    $stmtMark->execute([$type]);
}

// --- DEFINIRE QUERY-URI STANDARD ---
$sql_zombie = "SELECT * FROM seo_audit WHERE is_indexed = 0 AND coverage_state LIKE '%CRAWLED%' AND is_ignored = 0 ORDER BY last_crawl DESC";
$sql_discovered = "SELECT * FROM seo_audit WHERE is_indexed = 0 AND coverage_state LIKE '%DISCOVERED%' AND is_ignored = 0";
$sql_dusty = "SELECT * FROM seo_audit WHERE last_crawl < DATE_SUB(NOW(), INTERVAL 6 MONTH) AND is_ignored = 0 AND last_crawl IS NOT NULL ORDER BY last_crawl ASC";
$sql_unstable = "SELECT t1.url, t1.last_crawl, t1.verdict FROM seo_audit t1 JOIN seo_history t2 ON t1.id = t2.url_id WHERE t1.is_ignored = 0 GROUP BY t1.id HAVING COUNT(DISTINCT t2.is_indexed) > 1";
$sql_errors = "SELECT coverage_state, COUNT(*) as nr FROM seo_audit WHERE is_indexed = 0 AND is_ignored = 0 AND coverage_state NOT LIKE '%CRAWLED%' AND coverage_state NOT LIKE '%DISCOVERED%' GROUP BY coverage_state ORDER BY nr DESC";

// --- QUERY SPECIAL PENTRU HOT (ENTERPRISE) ---
$sql_hot_list = "SELECT * FROM seo_audit WHERE last_crawl IS NOT NULL AND is_ignored = 0 ORDER BY last_crawl DESC";

// Date pentru Grafic (Agregare pe zile - ultimele 30 zile)
$sql_hot_chart = "
    SELECT DATE(last_crawl) as crawl_date, COUNT(*) as count 
    FROM seo_audit 
    WHERE last_crawl IS NOT NULL 
    AND last_crawl >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY DATE(last_crawl) 
    ORDER BY crawl_date ASC";

// --- SELECTARE DATE ---
$data = [];
$chartData = []; 
$stats = [];     
$title = "Toate Rapoartele";
$desc = "";
$template = "list"; 
$showChart = false;

switch ($type) {
    case 'zombie':
        $data = $pdo->query($sql_zombie)->fetchAll();
        $title = "🧟 Zombie Pages";
        $desc = "Pagini vizitate de Google dar neindexate.";
        break;
    case 'discovered':
        $data = $pdo->query($sql_discovered)->fetchAll();
        $title = "⏳ Coada de Așteptare";
        $desc = "Pagini descoperite dar nevizitate încă.";
        break;
    case 'dusty':
        $data = $pdo->query($sql_dusty)->fetchAll();
        $title = "🕸️ Pagini Prăfuite";
        $desc = "Google nu a mai trecut pe aici de peste 6 luni.";
        break;
    case 'hot':
        // --- LOGICA ENTERPRISE EXTINSA ---
        $data = $pdo->query($sql_hot_list)->fetchAll();
        $rawChart = $pdo->query($sql_hot_chart)->fetchAll();
        
        // Statistici suplimentare
        $countYesterday = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE last_crawl >= DATE_SUB(NOW(), INTERVAL 24 HOUR)")->fetchColumn();
        $countLast7 = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE last_crawl >= DATE_SUB(NOW(), INTERVAL 7 DAY)")->fetchColumn();

        // Procesare date grafic
        $labels = [];
        $values = [];
        $maxCrawl = 0;
        $peakDay = '-';

        foreach($rawChart as $r) {
            $formattedDate = date('d.m', strtotime($r['crawl_date']));
            $labels[] = $formattedDate;
            $values[] = $r['count'];
            if($r['count'] > $maxCrawl) {
                $maxCrawl = $r['count'];
                $peakDay = $formattedDate;
            }
        }

        $chartData = ['labels' => $labels, 'values' => $values];
        $stats = [
            'total_items' => count($data),
            'yesterday' => $countYesterday,
            'last_7_days' => $countLast7,
            'peak_day' => $peakDay . " ($maxCrawl)"
        ];

        $title = "🔥 Activitate Googlebot (Live)";
        $desc = "Monitorizare detaliată a vizitelor Googlebot.";
        $showChart = true;
        break;
    case 'unstable':
        $data = $pdo->query($sql_unstable)->fetchAll();
        $title = "📉 Pagini Instabile";
        $desc = "Pagini care intră și ies din index frecvent.";
        break;
   case 'tech':
        // LOGICA NOUĂ: DRILL-DOWN
        if (isset($_GET['detail'])) {
            // Daca userul a dat click pe o cifra, afisam lista de URL-uri
            $errorType = $_GET['detail'];
            $stmt = $pdo->prepare("SELECT * FROM seo_audit WHERE coverage_state = ? AND is_indexed = 0 AND is_ignored = 0");
            $stmt->execute([$errorType]);
            $data = $stmt->fetchAll();
            
            $title = "🛠️ Detalii: " . htmlspecialchars($errorType);
            $desc = "Lista paginilor care au această eroare specifică.";
            $template = "list"; // Refolosim tabelul standard cu lista de URL-uri!
        } else {
            // Altfel, afisam tabelul sumar (ca in screenshot)
            $data = $pdo->query($sql_errors)->fetchAll();
            $title = "🛠️ Erori Tehnice";
            $desc = "Sumar al problemelor tehnice (click pe cifre pentru detalii).";
            $template = "tech_table";
        }
        break;
}
?>

<!DOCTYPE html>
<html lang="ro">
<head>
    <meta charset="UTF-8">
    <title><?php echo $title; ?> - Raport Enterprise</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body { background-color: #f4f6f9; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
        .card { border: none; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.05); transition: transform 0.2s; }
        .card:hover { transform: translateY(-2px); }
        .stat-card { border-left: 4px solid #0d6efd; background: white; padding: 20px; height: 100%; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .stat-label { font-size: 0.75rem; color: #6c757d; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; }
        .stat-value { font-size: 1.8rem; font-weight: 800; color: #212529; margin-top: 5px; }
        .chart-container { position: relative; height: 300px; width: 100%; }
    </style>
</head>
<body>

<div class="container my-5">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold text-dark mb-1"><?php echo $title; ?></h2>
            <p class="text-muted mb-0"><?php echo $desc; ?></p>
        </div>
<?php if(isset($_GET['detail'])): ?>
            <a href="reports.php?type=tech" class="btn btn-outline-secondary btn-sm fw-bold px-4 rounded-pill">← Înapoi la Erori</a>
        <?php else: ?>
            <a href="index.php" class="btn btn-outline-dark btn-sm fw-bold px-4 rounded-pill">← Dashboard</a>
        <?php endif; ?>    </div>

    <?php if($showChart): ?>
    <div class="row mb-4 g-3">
        <div class="col-md-3">
            <div class="row g-3 h-100">
                <div class="col-12">
                    <div class="stat-card border-primary">
                        <div class="stat-label">Total Vizite (All Time)</div>
                        <div class="stat-value"><?php echo number_format($stats['total_items']); ?></div>
                    </div>
                </div>
                <div class="col-12">
                    <div class="stat-card border-success">
                        <div class="stat-label">Ieri (Ultimele 24h)</div>
                        <div class="stat-value text-success"><?php echo number_format($stats['yesterday']); ?></div>
                    </div>
                </div>
                <div class="col-12">
                    <div class="stat-card border-warning">
                        <div class="stat-label">Ultimele 7 Zile</div>
                        <div class="stat-value text-warning"><?php echo number_format($stats['last_7_days']); ?></div>
                    </div>
                </div>
                <div class="col-12">
                    <div class="stat-card border-info">
                        <div class="stat-label">Ziua de Vârf</div>
                        <div class="stat-value text-info" style="font-size: 1.4rem;"><?php echo $stats['peak_day']; ?></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-md-9">
            <div class="card p-4 h-100">
                <h6 class="fw-bold text-secondary mb-3">📊 Trend Vizite Googlebot (30 Zile)</h6>
                <div class="chart-container">
                    <canvas id="hotChart"></canvas>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <div class="card">
        <div class="card-body p-0">
            <?php if(count($data) > 0): ?>
                <?php if($template == 'list'): ?>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light py-3">
                                <tr>
                                    <th class="ps-4">URL</th>
                                    <?php if($type == 'hot' || $type == 'dusty' || $type == 'zombie'): ?>
                                        <th>Ultimul Crawl</th>
                                    <?php endif; ?>
                                    <?php if($type != 'hot' && $type != 'dusty'): ?>
                                        <th>Status Google</th>
                                    <?php endif; ?>
                                   
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($data as $row): ?>
                                <tr>
                                    <td class="ps-4">
                                        <a href="<?php echo htmlspecialchars($row['url']); ?>" target="_blank" class="text-decoration-none fw-bold text-dark text-truncate d-inline-block" style="max-width: 500px;">
                                            <?php echo htmlspecialchars($row['url']); ?>
                                        </a>
                                    </td>
                                    
                                    <?php if($type == 'hot' || $type == 'dusty' || $type == 'zombie'): ?>
                                        <td>
                                            <?php 
                                            $date = strtotime($row['last_crawl']);
                                            $isRecent = (time() - $date < 86400); // Sub 24 ore
                                            $color = $isRecent ? 'text-success fw-bold' : 'text-muted';
                                            $badge = $isRecent ? ' <span class="badge bg-success" style="font-size:0.6rem">NOU</span>' : '';
                                            echo "<span class='$color'>" . date("d.m.Y H:i", $date) . "</span>" . $badge; 
                                            ?>
                                        </td>
                                    <?php endif; ?>
                                    
                                    <?php if($type != 'hot' && $type != 'dusty'): ?>
                                        <td>
                                            <span class="badge bg-light text-dark border">
                                                <?php echo isset($row['coverage_state']) ? $row['coverage_state'] : ($row['verdict'] ?? '-'); ?>
                                            </span>
                                        </td>
                                    <?php endif; ?>

                                  
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
            <?php elseif($template == 'tech_table'): ?>
                    <div class="p-4">
                        <div class="alert alert-info">
                            <i class="me-2">ℹ️</i> Dă click pe numărul din dreapta pentru a vedea lista URL-urilor.
                        </div>
                        <table class="table table-bordered table-hover shadow-sm">
                            <thead class="table-dark">
                                <tr>
                                    <th>Tip Eroare (Coverage State)</th>
                                    <th class="text-center" style="width: 150px;">Nr. Pagini</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($data as $row): ?>
                                <tr>
                                    <td class="align-middle fw-medium"><?php echo $row['coverage_state']; ?></td>
                                    <td class="text-center">
                                        <a href="reports.php?type=tech&detail=<?php echo urlencode($row['coverage_state']); ?>" 
                                           class="btn btn-sm btn-outline-danger fw-bold px-4 rounded-pill">
                                            <?php echo $row['nr']; ?> ➜
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                <?php endif; ?>
            <?php else: ?>
                <div class="p-5 text-center">
                    <h4>Nicio pagină găsită!</h4>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<?php if($showChart): ?>
<script>
    const ctx = document.getElementById('hotChart').getContext('2d');
    const gradient = ctx.createLinearGradient(0, 0, 0, 400);
    gradient.addColorStop(0, 'rgba(13, 110, 253, 0.5)');
    gradient.addColorStop(1, 'rgba(13, 110, 253, 0.0)');

    new Chart(ctx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($chartData['labels']); ?>,
            datasets: [{
                label: 'Pagini Crawled',
                data: <?php echo json_encode($chartData['values']); ?>,
                borderColor: '#0d6efd',
                backgroundColor: gradient,
                borderWidth: 2,
                pointBackgroundColor: '#fff',
                fill: true,
                tension: 0.3
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: { legend: { display: false } },
            scales: {
                y: { beginAtZero: true, grid: { borderDash: [5, 5] }, ticks: { precision: 0 } },
                x: { grid: { display: false } }
            }
        }
    });
</script>
<?php endif; ?>
</body>
</html>