<?php
/**
 * RSS Feed Monitoring Dashboard - Tabbed Version
 * Comprehensive monitoring and control panel for RSS feed processing
 */

require_once '../inc/con.php';

// Helper functions
function formatNumber($num)
{
    return number_format($num);
}

function formatTime($seconds)
{
    if ($seconds < 60)
        return round($seconds, 2) . 's';
    if ($seconds < 3600)
        return round($seconds / 60, 2) . 'm';
    return round($seconds / 3600, 2) . 'h';
}

// Get overview statistics
function getOverviewStats($db)
{
    $stats = [];

    $stmt = $db->query("SELECT COUNT(*) as total FROM social_media_content");
    $stats['total_posts'] = $stmt->fetch()['total'];

    $stmt = $db->query("SELECT * FROM rss_logs ORDER BY run_date DESC LIMIT 1");
    $stats['last_run'] = $stmt->fetch();

    $stmt = $db->query("
        SELECT COUNT(*) as count 
        FROM social_media_content 
        WHERE DATE(create_date) = CURDATE()
    ");
    $stats['today_posts'] = $stmt->fetch()['count'];

    // Total sources
    $stmt = $db->query("SELECT COUNT(*) as count FROM cat_sources WHERE status = 1");
    $stats['total_sources'] = $stmt->fetch()['count'];

    return $stats;
}

// Get current process status
function getCurrentProcessStatus($db)
{
    $stmt = $db->query("
        SELECT * FROM rss_logs 
        WHERE status = 'running' 
        ORDER BY run_date DESC 
        LIMIT 1
    ");
    return $stmt->fetch();
}

// Get video processing statistics
function getVideoProcessingStats($db)
{
    $stats = [];

    $stmt = $db->query("
        SELECT COUNT(*) as count 
        FROM social_media_content 
        WHERE video_url IS NOT NULL 
        AND video_url != '' 
        AND (video_processing = 0 OR video_processing IS NULL)
    ");
    $stats['pending'] = $stmt->fetch()['count'];

    $stmt = $db->query("
        SELECT COUNT(*) as count 
        FROM social_media_content 
        WHERE video_url IS NOT NULL 
        AND video_url != '' 
        AND video_processing = 1
    ");
    $stats['processing'] = $stmt->fetch()['count'];

    $stmt = $db->query("
        SELECT COUNT(*) as count 
        FROM social_media_content 
        WHERE video_url IS NOT NULL 
        AND video_url != '' 
        AND video_processing = 2
    ");
    $stats['completed'] = $stmt->fetch()['count'];

    return $stats;
}

// Get all sources with statistics
function getAllSources($db)
{
    $stmt = $db->query("
        SELECT 
            cs.id,
            cs.name,
            cs.json_feed,
            cs.last_fetch_time,
            cs.status,
            COUNT(smc.id) as total_posts,
            MAX(smc.create_date) as last_post_date,
            SUM(CASE WHEN smc.content_type = 1 THEN 1 ELSE 0 END) as images_count,
            SUM(CASE WHEN smc.content_type IN (2, 21) THEN 1 ELSE 0 END) as videos_count,
            SUM(CASE WHEN smc.content_type = 6 THEN 1 ELSE 0 END) as galleries_count
        FROM cat_sources cs
        LEFT JOIN social_media_content smc ON cs.id = smc.cat_sources
        WHERE cs.status = 1
        GROUP BY cs.id, cs.name, cs.json_feed, cs.last_fetch_time, cs.status
        ORDER BY cs.last_fetch_time DESC
    ");
    return $stmt->fetchAll();
}

// Get recent runs
function getRecentRuns($db, $limit = 20)
{
    $stmt = $db->prepare("
        SELECT * FROM rss_logs 
        ORDER BY run_date DESC 
        LIMIT ?
    ");
    $stmt->bindValue(1, (int) $limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}

// Get videos by status
function getVideosByStatus($db, $status, $limit = 50)
{
    $stmt = $db->prepare("
        SELECT id, post_id, content_type, video_url, photo, create_date, video_processing
        FROM social_media_content 
        WHERE video_url IS NOT NULL 
        AND video_url != '' 
        AND video_processing = ?
        ORDER BY create_date DESC
        LIMIT ?
    ");
    $stmt->bindValue(1, (int) $status, PDO::PARAM_INT);
    $stmt->bindValue(2, (int) $limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}

$stats = getOverviewStats($db);
$currentProcess = getCurrentProcessStatus($db);
$videoStats = getVideoProcessingStats($db);
$allSources = getAllSources($db);
$recentRuns = getRecentRuns($db, 20);

// Content type names
$contentTypeNames = [
    1 => 'صورة',
    2 => 'يوتيوب',
    3 => 'عاجل/خاص',
    6 => 'صور متعددة',
    10 => 'فيديو عام',
    21 => 'فيديو تويتر'
];
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>لوحة تحكم RSS</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            margin-bottom: 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .header h1 {
            color: #667eea;
            font-size: 28px;
        }

        .header-actions {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        .btn {
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
            transition: all 0.3s;
            text-decoration: none;
            display: inline-block;
        }

        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(56, 239, 125, 0.4);
        }

        .btn-warning {
            background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            color: white;
        }

        .btn-small {
            padding: 6px 12px;
            font-size: 12px;
        }

        .auto-refresh {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .auto-refresh input[type="checkbox"] {
            width: 20px;
            height: 20px;
            cursor: pointer;
        }

        /* Tabs */
        .tabs {
            background: white;
            border-radius: 15px 15px 0 0;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .tab-buttons {
            display: flex;
            background: #f8f9fa;
            border-bottom: 2px solid #dee2e6;
        }

        .tab-button {
            flex: 1;
            padding: 20px;
            background: none;
            border: none;
            font-size: 16px;
            font-weight: 600;
            color: #666;
            cursor: pointer;
            transition: all 0.3s;
            border-bottom: 3px solid transparent;
        }

        .tab-button:hover {
            background: #e9ecef;
            color: #667eea;
        }

        .tab-button.active {
            color: #667eea;
            background: white;
            border-bottom-color: #667eea;
        }

        .tab-content {
            display: none;
            padding: 25px;
            background: white;
            border-radius: 0 0 15px 15px;
        }

        .tab-content.active {
            display: block;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 25px;
        }

        .stat-card {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            transition: transform 0.3s;
        }

        .stat-card:hover {
            transform: translateY(-5px);
        }

        .stat-card h3 {
            color: #666;
            font-size: 14px;
            margin-bottom: 10px;
            text-transform: uppercase;
        }

        .stat-card .value {
            font-size: 36px;
            font-weight: bold;
            color: #667eea;
        }

        .stat-card .subtitle {
            color: #999;
            font-size: 12px;
            margin-top: 5px;
        }

        .section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .section h2 {
            color: #333;
            margin-bottom: 15px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 10px;
            overflow: hidden;
        }

        th,
        td {
            padding: 12px;
            text-align: right;
            border-bottom: 1px solid #eee;
        }

        th {
            background: #f8f9fa;
            font-weight: 600;
            color: #667eea;
        }

        tr:hover {
            background: #f8f9fa;
        }

        .badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }

        .badge-success {
            background: #d4edda;
            color: #155724;
        }

        .badge-warning {
            background: #fff3cd;
            color: #856404;
        }

        .badge-danger {
            background: #f8d7da;
            color: #721c24;
        }

        .badge-info {
            background: #d1ecf1;
            color: #0c5460;
        }

        .loading {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 30px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
            z-index: 9999;
        }

        .loading.active {
            display: block;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 15px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }

        .source-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 15px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
            transition: all 0.3s;
            cursor: pointer;
        }

        .source-card:hover {
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            transform: translateY(-2px);
        }

        .source-card h3 {
            color: #667eea;
            margin-bottom: 10px;
        }

        .source-stats {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-top: 10px;
        }

        .source-stat {
            display: flex;
            align-items: center;
            gap: 5px;
        }

        .source-stat .label {
            color: #666;
            font-size: 13px;
        }

        .source-stat .value {
            font-weight: bold;
            color: #333;
        }

        .status-box {
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .status-running {
            background: #fff3cd;
            border-left: 4px solid #ffc107;
        }

        .status-idle {
            background: #d4edda;
            border-left: 4px solid #28a745;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>📊 لوحة تحكم RSS</h1>
            <div class="header-actions">
                <div class="auto-refresh">
                    <input type="checkbox" id="autoRefresh">
                    <label for="autoRefresh">تحديث تلقائي</label>
                </div>
                <button class="btn btn-primary" onclick="location.reload()">🔄 تحديث</button>
                <button class="btn btn-success" onclick="triggerRSS()">▶️ تشغيل RSS</button>
            </div>
        </div>

        <!-- Tabs -->
        <div class="tabs">
            <div class="tab-buttons">
                <button class="tab-button active" onclick="switchTab('overview')">📈 نظرة عامة</button>
                <button class="tab-button" onclick="switchTab('videos')">📹 معالجة الفيديوهات</button>
                <button class="tab-button" onclick="switchTab('sources')">📊 المصادر</button>
                <button class="tab-button" onclick="switchTab('runs')">🕐 عمليات السحب</button>
            </div>

            <!-- Overview Tab -->
            <div id="tab-overview" class="tab-content active">
                <!-- Current Process Status -->
                <?php if ($currentProcess): ?>
                    <?php
                    $startTime = strtotime($currentProcess['run_date']);
                    $elapsed = time() - $startTime;
                    $hours = floor($elapsed / 3600);
                    $minutes = floor(($elapsed % 3600) / 60);
                    $seconds = $elapsed % 60;
                    $elapsedFormatted = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
                    ?>
                    <div class="status-box status-running">
                        <h3 style="color: #856404; margin-bottom: 10px;">⚡ العملية قيد التشغيل</h3>
                        <p style="color: #666; margin: 5px 0;">بدأت في: <?= date('Y-m-d H:i:s', $startTime) ?></p>
                        <p style="color: #666; margin: 5px 0;">الوقت المنقضي: <strong
                                id="elapsedTime"><?= $elapsedFormatted ?></strong></p>
                    </div>
                <?php else: ?>
                    <div class="status-box status-idle">
                        <h3 style="color: #155724; margin-bottom: 10px;">✅ النظام في وضع الخمول</h3>
                        <?php if ($stats['last_run']): ?>
                            <?php
                            $lastRunTime = strtotime($stats['last_run']['run_date']);
                            $timeSince = time() - $lastRunTime;
                            $hoursSince = floor($timeSince / 3600);
                            $minutesSince = floor(($timeSince % 3600) / 60);
                            ?>
                            <p style="color: #666;">آخر عملية اكتملت منذ:
                                <?php if ($hoursSince > 0): ?>
                                    <?= $hoursSince ?> ساعة و <?= $minutesSince ?> دقيقة
                                <?php else: ?>
                                    <?= $minutesSince ?> دقيقة
                                <?php endif; ?>
                            </p>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>

                <!-- Overview Statistics -->
                <div class="stats-grid">
                    <div class="stat-card">
                        <h3>إجمالي المنشورات</h3>
                        <div class="value"><?= formatNumber($stats['total_posts']) ?></div>
                        <div class="subtitle">في قاعدة البيانات</div>
                    </div>

                    <div class="stat-card">
                        <h3>منشورات اليوم</h3>
                        <div class="value"><?= formatNumber($stats['today_posts']) ?></div>
                        <div class="subtitle">تمت إضافتها اليوم</div>
                    </div>

                    <div class="stat-card">
                        <h3>عدد المصادر</h3>
                        <div class="value"><?= formatNumber($stats['total_sources']) ?></div>
                        <div class="subtitle">مصادر نشطة</div>
                    </div>

                    <div class="stat-card">
                        <h3>آخر تشغيل</h3>
                        <div class="value">
                            <?php if ($stats['last_run']): ?>
                                <?= date('H:i', strtotime($stats['last_run']['run_date'])) ?>
                            <?php else: ?>
                                --
                            <?php endif; ?>
                        </div>
                        <div class="subtitle">
                            <?php if ($stats['last_run']): ?>
                                <?= date('Y-m-d', strtotime($stats['last_run']['run_date'])) ?>
                            <?php else: ?>
                                لم يتم التشغيل بعد
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <!-- Quick Video Stats -->
                <div class="section">
                    <h2>📹 حالة الفيديوهات</h2>
                    <div class="stats-grid">
                        <div class="stat-card" style="background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%);">
                            <h3 style="color: #2d3436;">معلقة</h3>
                            <div class="value" style="color: #2d3436;"><?= formatNumber($videoStats['pending']) ?></div>
                            <div class="subtitle" style="color: #636e72;">بانتظار المعالجة</div>
                        </div>

                        <div class="stat-card" style="background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);">
                            <h3 style="color: white;">قيد المعالجة</h3>
                            <div class="value" style="color: white;"><?= formatNumber($videoStats['processing']) ?>
                            </div>
                            <div class="subtitle" style="color: #dfe6e9;">جاري التحويل</div>
                        </div>

                        <div class="stat-card" style="background: linear-gradient(135deg, #55efc4 0%, #00b894 100%);">
                            <h3 style="color: white;">مكتملة</h3>
                            <div class="value" style="color: white;"><?= formatNumber($videoStats['completed']) ?></div>
                            <div class="subtitle" style="color: #dfe6e9;">تمت المعالجة</div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Videos Tab -->
            <div id="tab-videos" class="tab-content">
                <div class="section">
                    <h2>📹 إحصائيات الفيديوهات</h2>
                    <div class="stats-grid">
                        <div class="stat-card" style="background: linear-gradient(135deg, #ffeaa7 0%, #fdcb6e 100%);">
                            <h3 style="color: #2d3436;">معلقة</h3>
                            <div class="value" style="color: #2d3436;"><?= formatNumber($videoStats['pending']) ?></div>
                            <div class="subtitle" style="color: #636e72;">بانتظار المعالجة</div>
                        </div>

                        <div class="stat-card" style="background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);">
                            <h3 style="color: white;">قيد المعالجة</h3>
                            <div class="value" style="color: white;"><?= formatNumber($videoStats['processing']) ?>
                            </div>
                            <div class="subtitle" style="color: #dfe6e9;">جاري التحويل</div>
                        </div>

                        <div class="stat-card" style="background: linear-gradient(135deg, #55efc4 0%, #00b894 100%);">
                            <h3 style="color: white;">مكتملة</h3>
                            <div class="value" style="color: white;"><?= formatNumber($videoStats['completed']) ?></div>
                            <div class="subtitle" style="color: #dfe6e9;">تمت المعالجة</div>
                        </div>
                    </div>
                </div>

                <?php if ($videoStats['pending'] > 0): ?>
                    <div style="margin-bottom: 20px; text-align: center;">
                        <button class="btn btn-warning" onclick="processAllVideos()"
                            style="padding: 15px 30px; font-size: 16px;">
                            🎬 معالجة جميع الفيديوهات المعلقة (<?= $videoStats['pending'] ?>)
                        </button>
                    </div>
                <?php endif; ?>

                <!-- Video Tabs -->
                <div style="margin-bottom: 20px;">
                    <button class="btn btn-primary" onclick="loadVideos('pending')" id="btn-pending">الفيديوهات
                        المعلقة</button>
                    <button class="btn btn-primary" onclick="loadVideos('processing')" id="btn-processing">قيد
                        المعالجة</button>
                    <button class="btn btn-primary" onclick="loadVideos('completed')"
                        id="btn-completed">المكتملة</button>
                </div>

                <div id="videos-container">
                    <p style="text-align: center; color: #666; padding: 40px;">اختر نوع الفيديوهات لعرضها</p>
                </div>
            </div>

            <!-- Sources Tab -->
            <div id="tab-sources" class="tab-content">
                <div class="section">
                    <h2>📊 جميع المصادر (<?= count($allSources) ?>)</h2>

                    <?php foreach ($allSources as $source): ?>
                        <div class="source-card" onclick="viewSourceDetails(<?= $source['id'] ?>)">
                            <h3><?= htmlspecialchars($source['name']) ?></h3>
                            <div class="source-stats">
                                <div class="source-stat">
                                    <span class="label">إجمالي المنشورات:</span>
                                    <span class="value"><?= formatNumber($source['total_posts']) ?></span>
                                </div>
                                <div class="source-stat">
                                    <span class="label">صور:</span>
                                    <span class="value"><?= formatNumber($source['images_count']) ?></span>
                                </div>
                                <div class="source-stat">
                                    <span class="label">فيديوهات:</span>
                                    <span class="value"><?= formatNumber($source['videos_count']) ?></span>
                                </div>
                                <div class="source-stat">
                                    <span class="label">معارض:</span>
                                    <span class="value"><?= formatNumber($source['galleries_count']) ?></span>
                                </div>
                                <div class="source-stat">
                                    <span class="label">آخر سحب:</span>
                                    <span class="value">
                                        <?php if ($source['last_fetch_time']): ?>
                                            <?php
                                            $fetchTime = strtotime($source['last_fetch_time']);
                                            $timeSince = time() - $fetchTime;
                                            $hoursAgo = floor($timeSince / 3600);

                                            if ($hoursAgo > 24) {
                                                echo floor($hoursAgo / 24) . ' يوم';
                                            } elseif ($hoursAgo > 0) {
                                                echo $hoursAgo . ' ساعة';
                                            } else {
                                                echo floor($timeSince / 60) . ' دقيقة';
                                            }
                                            ?>
                                        <?php else: ?>
                                            --
                                        <?php endif; ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

            <!-- Runs Tab -->
            <div id="tab-runs" class="tab-content">
                <div class="section">
                    <h2>🕐 آخر عمليات السحب</h2>
                    <table>
                        <thead>
                            <tr>
                                <th>التاريخ</th>
                                <th>المصادر</th>
                                <th>تمت معالجته</th>
                                <th>تم تخطيه</th>
                                <th>أخطاء</th>
                                <th>وقت التنفيذ</th>
                                <th>الحالة</th>
                                <th>تفاصيل</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($recentRuns as $run): ?>
                                <tr>
                                    <td><?= date('Y-m-d H:i:s', strtotime($run['run_date'])) ?></td>
                                    <td><?= $run['total_sources'] ?? 0 ?></td>
                                    <td><?= $run['total_processed'] ?? 0 ?></td>
                                    <td><?= $run['total_skipped'] ?? 0 ?></td>
                                    <td><?= $run['total_errors'] ?? 0 ?></td>
                                    <td><?= formatTime($run['execution_time'] ?? 0) ?></td>
                                    <td>
                                        <?php
                                        $status = $run['status'] ?? 'unknown';
                                        $badgeClass = 'badge-info';
                                        if ($status == 'completed')
                                            $badgeClass = 'badge-success';
                                        elseif ($status == 'failed')
                                            $badgeClass = 'badge-danger';
                                        elseif ($status == 'running')
                                            $badgeClass = 'badge-warning';
                                        ?>
                                        <span class="badge <?= $badgeClass ?>"><?= $status ?></span>
                                    </td>
                                    <td>
                                        <button class="btn btn-primary btn-small"
                                            onclick="showRunDetails(<?= $run['id'] ?>)">
                                            عرض التفاصيل
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <div id="run-details" style="display: none; margin-top: 20px;">
                    <div class="section">
                        <h2>📋 تفاصيل العملية</h2>
                        <div id="run-details-content"></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Loading Indicator -->
        <div id="loading" class="loading">
            <div class="spinner"></div>
            <p>جاري المعالجة...</p>
        </div>
    </div>

    <script>
        let autoRefreshInterval = null;
        let elapsedTimeInterval = null;

        // Load auto-refresh preference
        window.addEventListener('DOMContentLoaded', function () {
            const autoRefreshEnabled = localStorage.getItem('autoRefreshEnabled') === 'true';
            const checkbox = document.getElementById('autoRefresh');

            if (autoRefreshEnabled) {
                checkbox.checked = true;
                startAutoRefresh();
            }

            // Start elapsed time updater
            const elapsedTimeElement = document.getElementById('elapsedTime');
            if (elapsedTimeElement) {
                startElapsedTimeUpdater();
            }
        });

        // Auto-refresh toggle
        document.getElementById('autoRefresh').addEventListener('change', function () {
            localStorage.setItem('autoRefreshEnabled', this.checked);

            if (this.checked) {
                startAutoRefresh();
            } else {
                stopAutoRefresh();
            }
        });

        function startAutoRefresh() {
            autoRefreshInterval = setInterval(() => {
                location.reload();
            }, 30000);
        }

        function stopAutoRefresh() {
            if (autoRefreshInterval) {
                clearInterval(autoRefreshInterval);
            }
        }

        function startElapsedTimeUpdater() {
            const elapsedTimeElement = document.getElementById('elapsedTime');
            if (!elapsedTimeElement) return;

            elapsedTimeInterval = setInterval(() => {
                const currentText = elapsedTimeElement.textContent;
                const parts = currentText.split(':');
                let hours = parseInt(parts[0]);
                let minutes = parseInt(parts[1]);
                let seconds = parseInt(parts[2]);

                seconds++;
                if (seconds >= 60) {
                    seconds = 0;
                    minutes++;
                }
                if (minutes >= 60) {
                    minutes = 0;
                    hours++;
                }

                elapsedTimeElement.textContent =
                    String(hours).padStart(2, '0') + ':' +
                    String(minutes).padStart(2, '0') + ':' +
                    String(seconds).padStart(2, '0');
            }, 1000);
        }

        // Tab switching
        function switchTab(tabName) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });

            // Remove active class from all buttons
            document.querySelectorAll('.tab-button').forEach(btn => {
                btn.classList.remove('active');
            });

            // Show selected tab
            document.getElementById('tab-' + tabName).classList.add('active');

            // Add active class to clicked button
            event.target.classList.add('active');
        }

        // Trigger RSS
        function triggerRSS() {
            if (!confirm('هل تريد تشغيل عملية سحب RSS الآن؟')) {
                return;
            }

            document.getElementById('loading').classList.add('active');

            fetch('x_feeds.php?ajax=1')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    alert('تمت عملية السحب بنجاح!\n\nتمت معالجة: ' + data.processed + '\nتم تخطي: ' + data.skipped + '\nأخطاء: ' + data.errors);
                    location.reload();
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    alert('حدث خطأ أثناء التشغيل.');
                    console.error('Error:', error);
                });
        }

        // Process all videos
        function processAllVideos() {
            if (!confirm('هل تريد معالجة جميع الفيديوهات المعلقة؟\n\nقد تستغرق هذه العملية وقتاً طويلاً.')) {
                return;
            }

            document.getElementById('loading').classList.add('active');

            fetch('rss_dashboard_api.php?action=trigger_video_processing')
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    if (data.success) {
                        alert('تم بدء معالجة الفيديوهات!\n\nسيتم معالجة الفيديوهات في الخلفية.');
                        setTimeout(() => location.reload(), 2000);
                    } else {
                        alert('حدث خطأ: ' + (data.message || 'خطأ غير معروف'));
                    }
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    alert('حدث خطأ أثناء بدء المعالجة.');
                    console.error('Error:', error);
                });
        }

        // Load videos by status
        function loadVideos(status) {
            document.getElementById('loading').classList.add('active');

            const statusMap = {
                'pending': 0,
                'processing': 1,
                'completed': 2
            };

            fetch('rss_dashboard_api.php?action=get_videos_by_status&status=' + statusMap[status])
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    displayVideos(data, status);
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    alert('حدث خطأ أثناء جلب الفيديوهات.');
                    console.error('Error:', error);
                });
        }

        function displayVideos(videos, status) {
            const container = document.getElementById('videos-container');

            if (videos.length === 0) {
                container.innerHTML = '<p style="text-align: center; color: #666; padding: 40px;">لا توجد فيديوهات في هذه الفئة</p>';
                return;
            }

            let html = '<table><thead><tr>' +
                '<th>Post ID</th>' +
                '<th>النوع</th>' +
                '<th>رابط الفيديو</th>' +
                '<th>صورة الغلاف</th>' +
                '<th>تاريخ الإضافة</th>';

            if (status === 'pending') {
                html += '<th>إجراء</th>';
            }

            html += '</tr></thead><tbody>';

            videos.forEach(video => {
                const typeNames = {
                    2: 'يوتيوب',
                    21: 'فيديو تويتر'
                };

                html += '<tr>' +
                    '<td>' + video.post_id + '</td>' +
                    '<td><span class="badge badge-info">' + (typeNames[video.content_type] || 'غير معروف') + '</span></td>' +
                    '<td style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">' + video.video_url + '</td>' +
                    '<td>' + (video.photo ? '✅' : '❌') + '</td>' +
                    '<td>' + video.create_date + '</td>';

                if (status === 'pending') {
                    html += '<td><button class="btn btn-primary btn-small" onclick="processSingleVideo(' + video.id + ')">معالجة الآن</button></td>';
                }

                html += '</tr>';
            });

            html += '</tbody></table>';
            container.innerHTML = html;
        }

        // Process single video
        function processSingleVideo(videoId) {
            if (!confirm('هل تريد معالجة هذا الفيديو الآن؟')) {
                return;
            }

            document.getElementById('loading').classList.add('active');

            fetch('rss_dashboard_api.php?action=trigger_video_processing&video_id=' + videoId)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    if (data.success) {
                        alert('تم بدء معالجة الفيديو!');
                        setTimeout(() => loadVideos('pending'), 2000);
                    } else {
                        alert('حدث خطأ: ' + (data.message || 'خطأ غير معروف'));
                    }
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    alert('حدث خطأ أثناء معالجة الفيديو.');
                    console.error('Error:', error);
                });
        }

        // View source details
        function viewSourceDetails(sourceId) {
            window.location.href = 'source_details.php?id=' + sourceId;
        }

        // Show run details
        function showRunDetails(logId) {
            document.getElementById('loading').classList.add('active');

            fetch('rss_dashboard_api.php?action=get_source_stats&log_id=' + logId)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');

                    let html = '<table><thead><tr>' +
                        '<th>المصدر</th>' +
                        '<th>العناصر الموجودة</th>' +
                        '<th>تمت معالجته</th>' +
                        '<th>تم تخطيه</th>' +
                        '<th>أخطاء</th>' +
                        '<th>صور</th>' +
                        '<th>فيديوهات</th>' +
                        '<th>وقت التنفيذ</th>' +
                        '<th>الحالة</th>' +
                        '</tr></thead><tbody>';

                    data.forEach(source => {
                        let badgeClass = 'badge-success';
                        if (source.status == 'failed') badgeClass = 'badge-danger';
                        else if (source.status == 'partial') badgeClass = 'badge-warning';

                        html += '<tr>' +
                            '<td>' + source.source_name + '</td>' +
                            '<td>' + source.items_found + '</td>' +
                            '<td>' + source.items_processed + '</td>' +
                            '<td>' + source.items_skipped + '</td>' +
                            '<td>' + source.items_errors + '</td>' +
                            '<td>' + source.photos_downloaded + '</td>' +
                            '<td>' + source.videos_downloaded + '</td>' +
                            '<td>' + source.execution_time + 's</td>' +
                            '<td><span class="badge ' + badgeClass + '">' + source.status + '</span></td>' +
                            '</tr>';
                    });

                    html += '</tbody></table>';

                    document.getElementById('run-details-content').innerHTML = html;
                    document.getElementById('run-details').style.display = 'block';
                    document.getElementById('run-details').scrollIntoView({ behavior: 'smooth' });
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    alert('حدث خطأ أثناء جلب التفاصيل');
                    console.error('Error:', error);
                });
        }
    </script>
</body>

</html>