<?php
require 'config.php';
// --- RESETARE MANUALĂ COTA (NOU) ---
if (isset($_POST['reset_quota'])) {
    $today = date('Y-m-d');
    // Resetăm contorul la 0 pentru ziua de azi
    $pdo->prepare("UPDATE api_usage SET count = 0 WHERE date = ?")->execute([$today]);
    header("Location: index.php");
    exit;
}

// --- CALCUL BADGE-URI (Notificari WhatsApp Style - CE E NOU) ---
$views = $pdo->query("SELECT * FROM report_views")->fetchAll(PDO::FETCH_KEY_PAIR);
function getLastView($key, $views) { return isset($views[$key]) ? $views[$key] : '2000-01-01'; }

// Datele pentru "Last Viewed"
$z_date = getLastView('zombie', $views);
$d_date = getLastView('discovered', $views);
$dusty_date = getLastView('dusty', $views);
$h_date = getLastView('hot', $views);
$t_date = getLastView('tech', $views);

// --- CALCUL TOTALURI & BADGE-URI ---
// Avem nevoie de doua seturi: 
// 1. $badge_... (Doar cele noi, nevizualizate) -> Cerculet Rosu
// 2. $count_... (Totalul existent in categorie) -> Text (X pag.)

// Zombie
$count_zombie = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_indexed=0 AND coverage_state LIKE '%CRAWLED%' AND is_ignored=0")->fetchColumn();
$badge_zombie = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_indexed=0 AND coverage_state LIKE '%CRAWLED%' AND is_ignored=0 AND last_checked_at > '$z_date'")->fetchColumn();

// Discovered
$count_discovered = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_indexed=0 AND coverage_state LIKE '%DISCOVERED%' AND is_ignored=0")->fetchColumn();
$badge_discovered = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_indexed=0 AND coverage_state LIKE '%DISCOVERED%' AND is_ignored=0 AND last_checked_at > '$d_date'")->fetchColumn();

// Dusty
$count_dusty = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE last_crawl < DATE_SUB(NOW(), INTERVAL 6 MONTH) AND is_ignored=0 AND last_crawl IS NOT NULL")->fetchColumn();
$badge_dusty = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE last_crawl < DATE_SUB(NOW(), INTERVAL 6 MONTH) AND is_ignored=0 AND last_checked_at > '$dusty_date'")->fetchColumn();

// Hot
$count_hot = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE last_crawl >= DATE_SUB(NOW(), INTERVAL 5 DAY) AND is_ignored=0")->fetchColumn();
$badge_hot = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE last_crawl >= DATE_SUB(NOW(), INTERVAL 5 DAY) AND is_ignored=0 AND last_checked_at > '$h_date'")->fetchColumn();

// Tech
$count_tech = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_indexed=0 AND is_ignored=0 AND coverage_state NOT LIKE '%CRAWLED%' AND coverage_state NOT LIKE '%DISCOVERED%'")->fetchColumn();
$badge_tech = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_indexed=0 AND is_ignored=0 AND coverage_state NOT LIKE '%CRAWLED%' AND coverage_state NOT LIKE '%DISCOVERED%' AND last_checked_at > '$t_date'")->fetchColumn();

// Instabile (Calcul mai complex, facem count pe subquery)
$sql_unstable_count = "SELECT COUNT(*) FROM (SELECT t1.id 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) as sub";
$count_unstable = $pdo->query($sql_unstable_count)->fetchColumn();
$badge_unstable = 0; // Instabile nu au badge de "nou" momentan, e complex de urmarit istoric diff


// --- LOGICA STANDARD ---
$sitemapList = ['https://www.infocontact.ro/post-sitemap.xml', 'https://www.infocontact.ro/post-sitemap2.xml', 'https://www.infocontact.ro/post-sitemap3.xml', 'https://www.infocontact.ro/page-sitemap.xml', 'https://www.infocontact.ro/category-sitemap.xml'];
$import_message = '';
if (isset($_POST['sync_sitemap'])) {
    set_time_limit(300); 

    // 1. Functia de extragere (ramane la fel)
    if (!function_exists('getUrlsFromSitemap')) {
        function getUrlsFromSitemap($url) {
            $urls = []; 
            $xmlContent = @file_get_contents($url); 
            if (!$xmlContent) return []; 
            $xml = simplexml_load_string($xmlContent); 
            if (!$xml) return [];
            
            if (isset($xml->sitemap)) { 
                foreach ($xml->sitemap as $sitemap) {
                    $urls = array_merge($urls, getUrlsFromSitemap((string)$sitemap->loc)); 
                } 
            } elseif (isset($xml->url)) { 
                foreach ($xml->url as $urlEntry) {
                    $urls[] = trim((string)$urlEntry->loc); 
                } 
            } 
            return $urls;
        }
    }

    // 2. Colectam URL-urile din Sitemap (LIVE)
    $sitemapUrls = []; 
    foreach ($sitemapList as $sm) {
        $sitemapUrls = array_merge($sitemapUrls, getUrlsFromSitemap($sm));
    }
    $sitemapUrls = array_unique($sitemapUrls); // Lista curata din XML

    // PROTECTIE: Daca sitemap-ul e gol sau da eroare, NU stergem baza de date!
    if (count($sitemapUrls) > 0) {
        
        // A. Preluam URL-urile existente in DB
        $dbUrls = $pdo->query("SELECT url FROM seo_audit")->fetchAll(PDO::FETCH_COLUMN);

        // B. Calculam diferentele
        $urlsToAdd = array_diff($sitemapUrls, $dbUrls);   // Ce e nou
        $urlsToDelete = array_diff($dbUrls, $sitemapUrls); // Ce a disparut (cele 70 articole)

        // C. ADAUGARE (INSERT)
        $added = 0;
        if (!empty($urlsToAdd)) {
            $stmtInsert = $pdo->prepare("INSERT IGNORE INTO seo_audit (url) VALUES (?)");
            foreach ($urlsToAdd as $url) {
                $stmtInsert->execute([$url]);
                $added++;
            }
        }

        // D. STERGERE (DELETE)
        $deleted = 0;
        if (!empty($urlsToDelete)) {
            // Stergem in pachete pentru a nu bloca SQL daca sunt multe
            $chunks = array_chunk($urlsToDelete, 100);
            foreach ($chunks as $chunk) {
                $placeholders = implode(',', array_fill(0, count($chunk), '?'));
                $stmtDelete = $pdo->prepare("DELETE FROM seo_audit WHERE url IN ($placeholders)");
                $stmtDelete->execute($chunk);
                
                // Optional: Stergem si istoricul pentru ele ca sa nu ramana orfani
                // Dar baza ta are probabil ON DELETE CASCADE setat pe FK? 
                // Daca nu, ar fi bine sa cureti si seo_history, dar nu e critic acum.
                $deleted += count($chunk);
            }
        }

        $import_message = "Sincronizare Reușită:<br>➕ Adăugate: <strong>$added</strong><br>🗑️ Șterse (eliminate): <strong>$deleted</strong>";
    } else {
        $import_message = "❌ Eroare: Nu am putut citi sitemap-ul sau este gol. Nu s-a făcut nicio modificare pentru siguranță.";
    }
}

if (isset($_POST['reset_all'])) { $pdo->query("UPDATE seo_audit SET status = 'pending' WHERE is_ignored = 0"); header("Location: index.php"); exit; }
if (isset($_POST['ignore_urls'])) {
    $raw = explode("\n", $_POST['ignore_text']);
    $upd = $pdo->prepare("UPDATE seo_audit SET is_ignored=1, status='success', verdict='IGNORED' WHERE url=?");
    $ins = $pdo->prepare("INSERT IGNORE INTO seo_audit (url, is_ignored, status, verdict) VALUES (?, 1, 'success', 'IGNORED')");
    foreach($raw as $l) { $u=trim($l); if($u){ $upd->execute([$u]); if($upd->rowCount()==0) $ins->execute([$u]); } }
}

$today = date('Y-m-d');
$usage_count = $pdo->query("SELECT count FROM api_usage WHERE date = '$today'")->fetchColumn() ?: 0;
$limit_daily = 2000;
$percent_usage = ($usage_count / $limit_daily) * 100;
$limit_color = ($percent_usage > 90) ? 'bg-danger' : (($percent_usage > 50) ? 'bg-warning' : 'bg-success');

$total = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_ignored = 0")->fetchColumn();
$pending = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE status = 'pending' AND is_ignored = 0")->fetchColumn();
$indexed = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_indexed = 1 AND is_ignored = 0")->fetchColumn();
$not_indexed = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE status='success' AND is_indexed = 0 AND is_ignored = 0")->fetchColumn();

// Tabel Principal
$valid_columns = ['url', 'is_indexed', 'status', 'last_crawl', 'last_checked_at'];
$sort_col = isset($_GET['sort']) && in_array($_GET['sort'], $valid_columns) ? $_GET['sort'] : 'id';
$sort_order = isset($_GET['order']) && $_GET['order'] === 'DESC' ? 'DESC' : 'ASC';
$next_order = ($sort_order === 'ASC') ? 'DESC' : 'ASC';
function getSortLink($column, $label, $current_col, $current_order, $next_order) {
    $icon = ($column === $current_col) ? (($current_order === 'ASC') ? ' ▲' : ' ▼') : '';
    return '<a href="?sort=' . $column . '&order=' . $next_order . '" class="text-white text-decoration-none">' . $label . $icon . '</a>';
}
$sql = "SELECT a.*, (SELECT GROUP_CONCAT(is_indexed ORDER BY checked_at ASC SEPARATOR ',') FROM (SELECT * FROM seo_history ORDER BY checked_at DESC LIMIT 10) as sub WHERE sub.url_id = a.id) as history_spark FROM seo_audit a ORDER BY $sort_col $sort_order";
$existing_results = $pdo->query($sql)->fetchAll();
?>

<!DOCTYPE html>
<html lang="ro">
<head>
    <meta charset="UTF-8">
    <title>SEO Monitor Dashboard</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: #f0f2f5; }
        /* Widget Styles */
        .report-widget { transition: transform 0.2s; cursor: pointer; position: relative; border: none; overflow: hidden; }
        .report-widget:hover { transform: translateY(-5px); box-shadow: 0 10px 20px rgba(0,0,0,0.1); }
        .widget-icon { font-size: 2.5rem; margin-bottom: 5px; }
        .notify-badge {
            position: absolute; top: 10px; right: 10px;
            background: #dc3545; color: white;
            border-radius: 50%; width: 30px; height: 30px;
            display: flex; align-items: center; justify-content: center;
            font-weight: bold; font-size: 14px; box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            animation: popIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
            z-index: 10;
        }
        @keyframes popIn { from {transform: scale(0);} to {transform: scale(1);} }
        
        .status-box { padding: 15px; border-radius: 12px; color: white; text-align: center; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .bg-pending { background-color: #6c757d; }
        .bg-indexed { background-color: #198754; }
        .bg-warning-custom { background-color: #fd7e14; }
        .table-container { max-height: 600px; overflow-y: auto; border-radius: 0 0 8px 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.05); }
        thead th { position: sticky; top: 0; z-index: 10; }
        .spin-anim { animation: spin 1s linear infinite; display: inline-block; } @keyframes spin { 100% { transform: rotate(360deg); } }
        .sparkline-container { width: 60px; height: 20px; display: inline-block; vertical-align: middle; cursor: pointer; }
        .spark-dot { height: 6px; width: 6px; border-radius: 50%; display: inline-block; margin-right: 2px; }
        .spark-green { background-color: #198754; } .spark-red { background-color: #dc3545; }
        
        /* Count style in widget */
        .widget-count { font-size: 0.85rem; color: #6c757d; font-weight: normal; margin-left: 5px; }
    </style>
</head>
<body>

<div class="container-fluid px-5 mt-4">
    
    <?php if($import_message): ?><div class="alert alert-success alert-dismissible fade show"><?php echo $import_message; ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>
    
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h3 class="fw-bold text-dark">🚀 SEO Command Center</h3>
        <div class="d-flex align-items-center gap-3">
          <div class="bg-white px-3 py-2 rounded shadow-sm border d-flex align-items-center">
    <div class="me-3 text-end" style="line-height:1.2">
        <small class="text-muted d-block">Cota API</small>
        <strong class="<?php echo ($percent_usage > 90) ? 'text-danger' : 'text-dark'; ?>">
            <?php echo $usage_count; ?> / <?php echo $limit_daily; ?>
        </strong>
    </div>
    
    <div class="progress me-2" style="width: 80px; height: 8px;">
        <div class="progress-bar <?php echo $limit_color; ?>" style="width: <?php echo $percent_usage; ?>%"></div>
    </div>

    <form method="POST" onsubmit="return confirm('⚠️ Atenție!\nAsta resetează doar contorul LOCAL.\nDacă Google nu a resetat cota reală, scanarea va da eroare.\n\nContinui?');" class="m-0 d-flex">
        <button type="submit" name="reset_quota" class="btn btn-link p-0 text-secondary text-decoration-none" title="Resetează contorul manual">
            <span style="font-size: 1.2rem;">♻</span>
        </button>
  </form>
</div>

<a href="analytics.php" class="btn btn-primary btn-sm fw-bold d-flex align-items-center gap-2 shadow-sm">
    <span>📊 GSC Analytics</span>
</a>
<button class="btn btn-outline-danger btn-sm" data-bs-toggle="modal" data-bs-target="#ignoreModal">⛔ Ignoră</button>
<button onclick="exportTableToCSV('raport_seo.csv')" class="btn btn-dark btn-sm">⬇ CSV</button>
        </div>
    </div>

    <?php
    // Calcul Scor
    $total_valid = $total - $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE is_ignored=1")->fetchColumn();
    $score = ($total_valid > 0) ? round(($indexed / $total_valid) * 100, 1) : 0;
    
    // Calcul Conflicte
    $conflicts_count = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE user_canonical != '' AND google_canonical != '' AND user_canonical != google_canonical AND is_ignored=0")->fetchColumn();
    
    // Calcul Orfane
    $orphans_count = $pdo->query("SELECT COUNT(*) FROM seo_audit WHERE in_sitemap = 0 AND is_ignored=0")->fetchColumn();
    ?>

    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card text-white bg-dark h-100 justify-content-center text-center p-3">
                <h6 class="text-uppercase text-white-50 small">SEO Health Score</h6>
                <div class="display-4 fw-bold text-white"><?php echo $score; ?>%</div>
                <div class="progress mt-2" style="height: 5px;">
                    <div class="progress-bar bg-success" style="width: <?php echo $score; ?>%"></div>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card h-100 text-center p-3 border-danger <?php echo ($conflicts_count>0)?'bg-danger text-white':'bg-white'; ?>" 
                 style="cursor:pointer;" onclick="window.location.href='conflicts.php'">
                <div class="widget-icon">⚔️</div>
                <h6 class="fw-bold">Conflicte Canonice</h6>
                <h3 class="fw-bold mb-0"><?php echo $conflicts_count; ?></h3>
                <small><?php echo ($conflicts_count>0) ? 'Necesită Atenție!' : 'Nicio problemă'; ?></small>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card h-100 text-center p-3 bg-white" style="cursor:pointer;">
                <div class="widget-icon">👻</div>
                <h6 class="fw-bold">Pagini Orfane</h6>
                <h3 class="fw-bold mb-0"><?php echo $orphans_count; ?></h3>
                <small class="text-muted">În DB, dar nu în Sitemap</small>
            </div>
        </div>
<div class="col-md-3">
    <div class="card h-100 text-center p-3 bg-white border-warning" onclick="window.location.href='insights.php'" style="cursor:pointer; border-width:2px;">
        <div class="widget-icon">🕵️</div>
        <h6 class="fw-bold">Smart Insights</h6>
        <small class="text-muted">Analiză On-Page & Soluții</small>
    </div>
</div>
<div class="col-md-3">
    <div class="card h-100 text-center p-3 bg-white border-warning" onclick="window.location.href='insights_analytics.php'" style="cursor:pointer; border-width:2px;">
        <div class="widget-icon">🕵️</div>
        <h6 class="fw-bold">Smart Monitor & Strategy</h6>
        <small class="text-muted">Sugestii SEO si analiza pagini</small>
    </div>
</div>
        <div class="col-md-3">
            <div class="card h-100 text-center p-3 bg-primary text-white" onclick="window.location.href='reports.php?type=hot'" style="cursor:pointer;">
                <div class="widget-icon">🔥</div>
                <h6 class="fw-bold">Activitate Recentă</h6>
                <small>Vezi ce scanează Google acum</small>
            </div>
        </div>
    </div>

    <div class="row mb-5 g-3">
        <div class="col-md-2 col-6">
            <div class="card report-widget h-100 text-center p-2" onclick="window.location.href='reports.php?type=zombie'">
                <div class="text-danger fw-bold fs-4">🧟</div>
                <small class="fw-bold">Zombie</small>
                <div class="text-muted small"><?php echo $count_zombie; ?></div>
            </div>
        </div>
        <div class="col-md-2 col-6">
            <div class="card report-widget h-100 text-center p-2" onclick="window.location.href='reports.php?type=discovered'">
                <div class="text-warning fw-bold fs-4">⏳</div>
                <small class="fw-bold">La Coadă</small>
                <div class="text-muted small"><?php echo $count_discovered; ?></div>
            </div>
        </div>
        <div class="col-md-2 col-6">
            <div class="card report-widget h-100 text-center p-2" onclick="window.location.href='reports.php?type=tech'">
                <div class="text-dark fw-bold fs-4">🛠️</div>
                <small class="fw-bold">Erori</small>
                <div class="text-muted small"><?php echo $count_tech; ?></div>
            </div>
        </div>
        </div>

    <div class="card mb-4 shadow-sm border-0">
        <div class="card-body py-3">
            <div class="row align-items-center">
                <div class="col-md-8 d-flex gap-2">
                    <?php if($usage_count >= $limit_daily): ?>
                        <button class="btn btn-danger px-4" disabled>⛔ Limita Atinsă</button>
                    <?php elseif($pending > 0): ?>
                        <button id="btnStart" class="btn btn-success px-4 fw-bold">▶ Continuă Scanarea</button>
                        <button id="btnStop" class="btn btn-danger px-4" disabled>⏹ Stop</button>
                    <?php else: ?>
                        <button class="btn btn-secondary px-4" disabled>✅ Totul Verificat</button>
                    <?php endif; ?>
                    
                    <div class="vr mx-2"></div>
                    <form method="POST" onsubmit="return confirm('Resetezi scanarea?');" class="m-0"><button name="reset_all" class="btn btn-warning fw-bold">🔄 Resetează Tot</button></form>
                    <div class="vr mx-2"></div>
                    <form method="POST" class="m-0"><button name="sync_sitemap" class="btn btn-primary fw-bold">📥 Sync Sitemap</button></form>
                </div>
                <div class="col-md-4">
                    <div class="d-flex justify-content-between small text-muted mb-1"><span>Progres</span><span id="statusText">Așteptare...</span></div>
                    <div class="progress" style="height: 10px;"><div id="progressBar" class="progress-bar progress-bar-striped progress-bar-animated bg-success" style="width: 0%"></div></div>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow-sm border-0">
        <div class="card-header bg-white border-bottom-0 pt-3">
            <div class="d-flex justify-content-between">
                <h5 class="fw-bold">📋 Listă Generală URL-uri</h5>
                <div class="filter-container d-flex gap-2">
                    <button class="btn btn-sm btn-outline-secondary active" onclick="filterTable('all', this)">Toate</button>
                    <button class="btn btn-sm btn-outline-success" onclick="filterTable('indexed', this)">Indexate</button>
                    <button class="btn btn-sm btn-outline-warning" onclick="filterTable('not_indexed', this)">Neindexate</button>
                </div>
            </div>
        </div>
        <div class="card-body p-0 table-container">
            <table class="table table-striped table-hover mb-0 align-middle" id="resultsTable" style="font-size: 0.9rem;">
                <thead class="table-dark">
                    <tr>
                        <th class="text-center" style="width: 40px;"><input type="checkbox" id="selectAll" class="form-check-input" onclick="toggleSelectAll()"></th>
                        <th style="width: 40%;"><?php echo getSortLink('url', 'URL', $sort_col, $sort_order, $next_order); ?></th>
                        <th class="text-center">Istoric</th>
                        <th class="text-center"><?php echo getSortLink('is_indexed', 'Idx?', $sort_col, $sort_order, $next_order); ?></th>
                        <th><?php echo getSortLink('status', 'Status', $sort_col, $sort_order, $next_order); ?></th>
                        <th><?php echo getSortLink('last_crawl', 'Crawl', $sort_col, $sort_order, $next_order); ?></th>
                        <th><?php echo getSortLink('last_checked_at', 'Verificat', $sort_col, $sort_order, $next_order); ?></th>
                        <th class="text-center">Act.</th>
                    </tr>
                </thead>
                <tbody id="logBody">
                    <?php foreach($existing_results as $row): ?>
                        <?php 
                            $isIgnored=$row['is_ignored']; $st='pending';
                            if($isIgnored==1)$st='ignored'; elseif($row['status']=='error')$st='error'; elseif($row['is_indexed']==1)$st='indexed'; elseif($row['status']=='success')$st='not_indexed';
                            $cl=''; $ic='⏳'; if($st=='ignored'){$cl='table-secondary text-muted';$ic='🚫';} elseif($st=='error'){$cl='table-danger';$ic='⚠';} elseif($st=='indexed'){$cl='table-success';$ic='✅';} elseif($st=='not_indexed'){$cl='table-warning';$ic='❌';}
                            
                            // CORECAT DATA: Folosim format cu AN (d.m.Y H:i)
                            $lastCrawl=($row['last_crawl'])?date("d.m.Y H:i",strtotime($row['last_crawl'])):'-';
                            $checkDate=($row['last_checked_at'])?date("d.m.Y H:i",strtotime($row['last_checked_at'])):'-';
                            
                            $histHtml='<span class="text-muted" style="font-size:10px;">-</span>';
                            if($row['history_spark']){
                                $h=explode(',',$row['history_spark']); $histHtml='<div class="sparkline-container" onclick="openHistoryModal('.$row['id'].')">';
                                foreach($h as $v){ $histHtml.='<span class="spark-dot '.($v=='1'?'spark-green':'spark-red').'"></span>'; } $histHtml.='</div>';
                            }
                        ?>
                        <tr id="row-<?php echo $row['id']; ?>" class="<?php echo $cl; ?>" style="<?php echo ($isIgnored)?'display:none;':''; ?>" data-status="<?php echo $st; ?>">
                            <td class="text-center"><input type="checkbox" class="form-check-input row-checkbox" value="<?php echo $row['id']; ?>" onclick="updateBulk()"></td>
                            <td><a href="<?php echo htmlspecialchars($row['url']); ?>" target="_blank" class="text-decoration-none text-dark"><?php echo htmlspecialchars($row['url']); ?></a></td>
                            <td class="text-center"><?php echo $histHtml; ?></td>
                            <td class="text-center col-idx"><strong><?php echo $ic; ?></strong></td>
                            <td class="col-verdict"><?php echo htmlspecialchars($row['verdict']??$row['error_message']); ?></td>
                            <td class="col-crawl"><?php echo $lastCrawl; ?></td>
                            <td class="col-check text-secondary fw-bold"><?php echo $checkDate; ?></td>
                            <td class="text-center"><?php if(!$isIgnored): ?><button class="btn-refresh" onclick="recheckUrl(<?php echo $row['id']; ?>)">🔄</button><?php else: ?><small>Ignorat</small><?php endif; ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="ignoreModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h5 class="modal-title">🚫 Ignoră URL-uri</h5><button class="btn-close" data-bs-dismiss="modal"></button></div><form method="POST"><div class="modal-body"><textarea name="ignore_text" class="form-control" rows="10" placeholder="https://..."></textarea></div><div class="modal-footer"><button type="submit" name="ignore_urls" class="btn btn-danger">Salvează</button></div></form></div></div></div>
<div class="modal fade" id="historyModal" tabindex="-1"><div class="modal-dialog modal-xl"><div class="modal-content" style="height:90vh;"><div class="modal-header"><h5 class="modal-title" id="historyModalLabel">Istoric</h5><button class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body d-flex flex-column"><div style="flex:1;min-height:400px;"><canvas id="historyChart"></canvas></div><div class="mt-4" style="flex:1;overflow-y:auto;"><table class="table table-sm"><tbody id="historyTableBody"></tbody></table></div></div></div></div></div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // Paste aici scriptul tau JS existent (cel cu scanarea, filtrarea, bulk), este compatibil.
    // Doar asigura-te ca ai inclus functiile: recheckUrl, scanNext, updateVisuals, openHistoryModal etc.
    let scanning=false, bulkQueue=[], isBulkScanning=false;
    let totalUrls=<?php echo $total; ?>, processed=<?php echo $total-$pending; ?>, dailyLimit=<?php echo $limit_daily; ?>, historyChart=null;

    function updateProgress(){ if(totalUrls>0){ let p=(processed/totalUrls)*100; $('#progressBar').css('width',p+'%'); }} updateProgress();
    function updateUsageUI(c){ let p=(c/dailyLimit)*100, cl='bg-success'; if(p>50)cl='bg-warning'; if(p>90)cl='bg-danger'; $('#usageDisplay').text(c+' / '+dailyLimit); $('#usageBar').css('width',p+'%').attr('class','progress-bar '+cl); if(c>=dailyLimit){ scanning=false; $('#btnStart').prop('disabled',true).text('⛔ Limita Atinsă').removeClass('btn-success').addClass('btn-danger'); } }

    function filterTable(c,b){
        $('.btn-outline-secondary, .btn-outline-success, .btn-outline-warning').removeClass('active'); $(b).addClass('active');
        $('#resultsTable tbody tr').each(function(){
            let r=$(this), s=r.data('status'), show=false;
            if(s==='ignored'){ show=false; }
            else {
                if(c=='all') show=true;
                else if(c=='indexed' && s=='indexed') show=true;
                else if(c=='not_indexed' && (s=='not_indexed'||s=='error')) show=true;
            }
            if(show) r.show(); else r.hide();
        });
    }

    function openHistoryModal(id){
        var myModal=new bootstrap.Modal(document.getElementById('historyModal')); myModal.show();
        $('#historyTableBody').html('<tr><td colspan="3" class="text-center">Loading...</td></tr>');
        if(historyChart){historyChart.destroy();historyChart=null;}
        $.ajax({url:'get_history.php?id='+id,dataType:'json',success:function(r){
            if(r.success){ $('#historyModalLabel').text(r.url); if(r.data.length>0){renderChart(r.data);renderHistoryTable(r.data);}else{$('#historyTableBody').html('<tr><td colspan="3">Fara date.</td></tr>');} }
            else{$('#historyTableBody').html('<tr><td>Eroare</td></tr>');}
        }});
    }
    function renderChart(d){ const ctx=document.getElementById('historyChart').getContext('2d'); const l=d.map(i=>i.checked_at), v=d.map(i=>i.is_indexed); historyChart=new Chart(ctx,{type:'line',data:{labels:l,datasets:[{label:'Idx',data:v,borderColor:'#0d6efd',tension:0.1,stepped:true}]},options:{maintainAspectRatio:false,scales:{y:{min:0,max:1.2}}}}); }
    function renderHistoryTable(d){ let h=''; [...d].reverse().forEach(i=>{ let b=(i.is_indexed==1)?'<span class="badge bg-success">DA</span>':'<span class="badge bg-danger">NU</span>'; h+=`<tr><td>${i.checked_at}</td><td>${b}</td><td>${i.verdict}</td></tr>`; }); $('#historyTableBody').html(h); }
    
    function recheckUrl(id,auto=false){
        let btn=$('#row-'+id+' .btn-refresh'); if(!auto)btn.addClass('spin-anim').prop('disabled',true); if(auto)$('#row-'+id).css('opacity','0.5');
        $.ajax({url:'scan.php?id='+id,dataType:'json',success:function(d){
            if(d.usage_count!==undefined)updateUsageUI(d.usage_count);
            if(d.is_quota){alert(d.error);scanning=false;isBulkScanning=false;if(!auto)btn.removeClass('spin-anim').prop('disabled',false);return;}
            updateVisuals(d); if(!auto)btn.removeClass('spin-anim').prop('disabled',false); if(auto){$('#row-'+id).css('opacity','1');setTimeout(processBulkQueue,1000);}
        },error:function(){if(auto)setTimeout(processBulkQueue,2000);else{btn.removeClass('spin-anim').prop('disabled',false);alert('Err');}}});
    }
    function scanNext(){ if(!scanning)return; $.ajax({url:'scan.php',dataType:'json',success:function(d){ 
        if(d.usage_count!==undefined)updateUsageUI(d.usage_count); if(d.is_quota){alert(d.error);scanning=false;return;} 
        if(d.finished){scanning=false;$('#btnStart').prop('disabled',false);$('#btnStop').prop('disabled',true);alert("Gata!");location.reload();return;}
        updateVisuals(d); processed++; updateProgress(); setTimeout(scanNext,1200); 
    },error:function(){setTimeout(scanNext,3000);}}); }
    
    function updateVisuals(d){
        let r=$('#row-'+d.id); if(r.length===0)return; r.data('days',0);
        let s='not_indexed', c='table-warning', i='❌';
        if(!d.success){s='error';c='table-danger';i='⚠';r.find('.col-verdict').html(d.error);}
        else if(d.is_indexed){s='indexed';c='table-success';i='✅';}
        r.removeClass('table-danger table-success table-warning bg-pending').addClass(c).data('status',s);
        r.find('.col-idx').html('<strong>'+i+'</strong>');
        if(d.success){r.find('.col-verdict').html(d.verdict);r.find('.col-crawl').text(d.last_crawl);}
        r.find('.col-check').text(d.last_check); r.fadeOut(100).fadeIn(100);
    }
    
    function toggleSelectAll(){ let c=$('#selectAll').is(':checked'); $('.row-checkbox:visible').prop('checked',c); updateBulk(); }
    function updateBulk(){ let c=$('.row-checkbox:checked').length; if(c>0)$('#btnStart').text('Bulk Check ('+c+')').removeClass('btn-success').addClass('btn-primary'); else $('#btnStart').text('▶ Continuă Scanarea').addClass('btn-success').removeClass('btn-primary'); }
    // Aici poti re-activa functia de bulk daca doresti.
    
    $('#btnStart').click(function(){scanning=true;$(this).prop('disabled',true);$('#btnStop').prop('disabled',false);scanNext();});
    $('#btnStop').click(function(){scanning=false;$(this).prop('disabled',true);$('#btnStart').prop('disabled',false);});
    function exportTableToCSV(f){var c=[],r=document.querySelectorAll("table tr");for(var i=0;i<r.length;i++){if(r[i].style.display==='none')continue;var l=[],d=r[i].querySelectorAll("td,th");for(var j=1;j<d.length-1;j++)l.push('"'+d[j].innerText.replace(/"/g,'""')+'"');c.push(l.join(","));}var b=new Blob([c.join("\n")],{type:"text/csv"}),a=document.createElement("a");a.download=f;a.href=window.URL.createObjectURL(b);a.style.display="none";document.body.appendChild(a);a.click();}
</script>
</body>
</html>