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

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

// Smart Refresh API
if (isset($_GET['check_update'])) {


    // Disable error reporting to ensure clean JSON
    error_reporting(0);
    ini_set('display_errors', 0);

    header('Content-Type: application/json');
    $response = [];

    // Check for changes (simplified for demonstration, typically you'd check last_id or hash first)
    // Here we just return the rendered HTML components every time for the client to update
    // Ideally, we accept a 'hash' from client and only return data if changed, but for simplicity we return data.

    $activeVideo = getActiveProcessingVideo($db);
    $recentVideosList = getRecentVideosDetailed($db, 10);
    $recentContentList = getRecentAllContent($db, 10);

    // Define content type names here as they are needed for render
    $contentTypeNames = [
        1 => 'صورة',
        2 => 'يوتيوب',
        3 => 'عاجل/خاص',
        6 => 'صور متعددة',
        10 => 'فيديو عام',
        21 => 'فيديو تويتر'
    ];

    $response['active_html'] = renderActiveVideoComponent($activeVideo);
    $response['recent_html'] = renderRecentActivityComponent($recentVideosList, $recentContentList, $contentTypeNames);

    // Processing status changes
    $stmt = $db->query("SELECT COUNT(*) as cnt, SUM(processing_percentage) as sum_pct FROM social_media_content WHERE video_processing = 1");
    $row = $stmt->fetch();
    $response['processing_hash'] = $row['cnt'] . '-' . $row['sum_pct'];

    echo json_encode($response);
    exit;
}

// Set Timezone
date_default_timezone_set('Europe/Istanbul');

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

function truncateWords($text, $limit = 7)
{
    $words = explode(' ', $text);
    if (count($words) > $limit) {
        return implode(' ', array_slice($words, 0, $limit)) . '...';
    }
    return $text;
}

function renderActiveVideoComponent($activeVideo)
{
    if (!$activeVideo)
        return '';

    $html = '<div class="section" style="background: #e3f2fd; border-left: 5px solid #2196f3;">
        <h2 style="color: #0d47a1; border-color: #2196f3;">🎥 جاري معالجة الفيديو الآن</h2>
        <div style="background: white; padding: 20px; border-radius: 10px;">
            <h3 style="margin: 0 0 10px 0;">' . (htmlspecialchars($activeVideo['title']) ?: 'بدون عنوان') . ' (ID: ' . $activeVideo['id'] . ')</h3>
            <div class="progress" style="height: 30px; background-color: #e9ecef; border-radius: 5px; overflow: hidden; margin-top: 15px;">
                <div class="progress-bar progress-bar-striped progress-bar-animated bg-primary" 
                     role="progressbar" 
                     style="width: ' . $activeVideo['processing_percentage'] . '%; line-height: 30px; color: white; text-align: center; font-weight: bold;" 
                     aria-valuenow="' . $activeVideo['processing_percentage'] . '" 
                     aria-valuemin="0" 
                     aria-valuemax="100">
                    ' . $activeVideo['processing_percentage'] . '%
                </div>
            </div>
            <p style="margin-top: 10px; color: #666;">
                <strong>Post ID:</strong> ' . $activeVideo['post_id'] . ' | 
                <strong>المصدر:</strong> ' . htmlspecialchars($activeVideo['source_name'] ?? 'غير معروف') . ' |
                <strong>تاريخ الإضافة:</strong> ' . $activeVideo['create_date'] . '
            </p>
        </div>
    </div>';
    return $html;
}

function renderRecentActivityComponent($recentVideosList, $recentContentList, $contentTypeNames)
{
    ob_start();
    ?>
    <div class="section">
        <h2>📋 آخر النشاطات (توقيت إسطنبول)</h2>

        <!-- Sub-tabs for content -->
        <div style="border-bottom: 2px solid #ddd; margin-bottom: 20px;">
            <button onclick="switchSubTab('videos_list')" id="btn-videos_list" class="btn btn-primary btn-small"
                style="border-radius: 5px 5px 0 0; margin-bottom: -2px;">آخر 10 فيديوهات</button>
            <button onclick="switchSubTab('content_list')" id="btn-content_list" class="btn btn-secondary btn-small"
                style="border-radius: 5px 5px 0 0; margin-bottom: -2px; background: #f8f9fa; color: #666; border: 1px solid #ddd; border-bottom: none;">آخر
                10 مواد</button>
        </div>

        <!-- VIDEOS LIST -->
        <div id="subtab-videos_list" style="display: block;">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>المصدر</th>
                        <th>العنوان</th>
                        <th>الحالة</th>
                        <th>التقدم</th>
                        <th>التاريخ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentVideosList as $video): ?>
                        <tr>
                            <td><?= $video['id'] ?></td>
                            <td><span class="badge badge-info"><?= htmlspecialchars($video['source_name'] ?? 'N/A') ?></span>
                            </td>
                            <td title="<?= htmlspecialchars($video['title']) ?>">
                                <?= truncateWords(htmlspecialchars($video['title']) ?: 'بدون عنوان') ?>
                            </td>
                            <td>
                                <?php
                                if ($video['video_processing'] == 2)
                                    echo '<span class="badge badge-success">مكتمل</span>';
                                elseif ($video['video_processing'] == 1)
                                    echo '<span class="badge badge-info">جاري المعالجة</span>';
                                elseif ($video['video_processing'] == 0)
                                    echo '<span class="badge badge-warning">في الانتظار</span>';
                                else
                                    echo '<span class="badge badge-danger">خطأ/مجهول</span>';
                                ?>
                            </td>
                            <td>
                                <?php if ($video['video_processing'] == 1): ?>
                                    <div
                                        style="width: 80px; background: #eee; height: 10px; border-radius: 5px; display: inline-block;">
                                        <div
                                            style="background: #2196f3; width: <?= $video['processing_percentage'] ?>%; height: 100%; border-radius: 5px;">
                                        </div>
                                    </div>
                                    <small><?= $video['processing_percentage'] ?>%</small>
                                <?php elseif ($video['video_processing'] == 2): ?>
                                    100%
                                <?php else: ?>
                                    -
                                <?php endif; ?>
                            </td>
                            <td dir="ltr"><?= $video['create_date'] ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- CONTENT LIST -->
        <div id="subtab-content_list" style="display: none;">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>المصدر</th>
                        <th>النوع</th>
                        <th>العنوان</th>
                        <th>التاريخ</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentContentList as $item): ?>
                        <tr>
                            <td><?= $item['id'] ?></td>
                            <td><span class="badge badge-info"><?= htmlspecialchars($item['source_name'] ?? 'N/A') ?></span>
                            </td>
                            <td>
                                <?php
                                $typeName = $contentTypeNames[$item['content_type']] ?? 'غير معروف';
                                echo $typeName;
                                ?>
                            </td>
                            <td title="<?= htmlspecialchars($item['title']) ?>">
                                <?= truncateWords(htmlspecialchars($item['title']) ?: 'بدون عنوان') ?>
                            </td>
                            <td dir="ltr"><?= $item['create_date'] ?></td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php
    return ob_get_clean();
}

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 WHERE content_type != 2");
    $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()
        AND content_type != 2
    ");
    $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 content type distribution
function getContentDistribution($db)
{
    // Group 1: Image (1), Gallery (6) -> 'image'
    // Group 2: Video (10), YouTube (2), Urgent (3), Twitter (21) -> 'video'

    $stmt = $db->query("
        SELECT 
            CASE 
                WHEN content_type IN (1, 6) THEN 'image'
                WHEN content_type IN (2, 3, 10, 21) THEN 'video'
                ELSE 'other'
            END as type_group,
            COUNT(*) as count
        FROM social_media_content
        GROUP BY type_group
        ORDER BY count DESC
    ");
    return $stmt->fetchAll();
}

// 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)
        AND content_type != 2
    ");
    $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
        AND content_type != 2
    ");
    $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
        AND content_type != 2
    ");
    $stats['completed'] = $stmt->fetch()['count'];

    // YouTube Stats
    $stmt = $db->query("
        SELECT COUNT(*) as count 
        FROM social_media_content 
        WHERE content_type = 2
    ");
    $stats['youtube_count'] = $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(CASE WHEN smc.content_type != 2 THEN smc.id END) 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 = 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
        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 with source names
function getRecentRuns($db, $limit = 20)
{
    $stmt = $db->prepare("
        SELECT 
            rl.*,
            GROUP_CONCAT(DISTINCT cs.name ORDER BY cs.name SEPARATOR ', ') as source_names
        FROM rss_logs rl
        LEFT JOIN rss_source_logs rsl ON rl.id = rsl.log_id
        LEFT JOIN cat_sources cs ON rsl.source_id = cs.id
        GROUP BY rl.id
        ORDER BY rl.run_date DESC 
        LIMIT ?
    ");
    $stmt->bindValue(1, (int) $limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll();
}

// Get daily statistics for last N days
function getDailyStats($db, $days = 30)
{
    $stmt = $db->prepare("
        SELECT 
            DATE(run_date) as date,
            COUNT(*) as total_runs,
            SUM(total_processed) as total_processed,
            SUM(total_skipped) as total_skipped,
            SUM(total_errors) as total_errors,
            AVG(execution_time) as avg_execution_time,
            SUM(CASE WHEN status = 'completed' THEN 1 ELSE 0 END) as successful_runs,
            SUM(CASE WHEN status = 'failed' THEN 1 ELSE 0 END) as failed_runs
        FROM rss_logs
        WHERE run_date >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
        GROUP BY DATE(run_date)
        ORDER BY date DESC
    ");
    $stmt->bindValue(1, (int) $days, 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, title, cat_sources 
        FROM social_media_content 
        WHERE video_url IS NOT NULL 
        AND video_url != '' 
        AND video_processing = ?
        AND content_type != 2
        ORDER BY create_date DESC
        LIMIT ?
    ");
    $stmt->bindValue(1, (int) $status, PDO::PARAM_INT);
    $stmt->bindValue(2, (int) $limit, PDO::PARAM_INT);
    $stmt->execute();

    // Fetch source names manually if needed or join above
    // Ideally join with cat_sources for display
    // But since the original query didn't have joins, we keep it simple or upgrade it.
    // Let's upgrade it to include source name for the display table
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Enrich with source names (quick fix to avoid complex join resize issues)
    foreach ($results as &$row) {
        $src = $db->prepare("SELECT name FROM cat_sources WHERE id = ?");
        $src->execute([$row['cat_sources']]);
        $s = $src->fetch();
        $row['source_name'] = $s ? $s['name'] : 'غير معروف';
    }

    return $results;
}

// Get currently processing video
function getActiveProcessingVideo($db)
{
    $stmt = $db->query("
        SELECT smc.*, cs.name as source_name 
        FROM social_media_content smc
        LEFT JOIN cat_sources cs ON smc.cat_sources = cs.id
        WHERE smc.video_processing = 1 
        AND smc.content_type != 2
        ORDER BY smc.id DESC LIMIT 1
    ");
    return $stmt->fetch(PDO::FETCH_ASSOC);
}

// Get recent videos detailed
function getRecentVideosDetailed($db, $limit = 10)
{
    $stmt = $db->prepare("
        SELECT smc.id, smc.post_id, smc.title, smc.video_url, smc.video_processing, smc.processing_percentage, smc.create_date, cs.name as source_name 
        FROM social_media_content smc
        LEFT JOIN cat_sources cs ON smc.cat_sources = cs.id
        WHERE smc.video_url != ''
        AND smc.content_type != 2 
        ORDER BY smc.id DESC LIMIT ?
    ");
    $stmt->bindValue(1, (int) $limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

// Get recent all content
function getRecentAllContent($db, $limit = 10)
{
    $stmt = $db->prepare("
        SELECT smc.id, smc.post_id, smc.title, smc.content_type, smc.status, smc.create_date, cs.name as source_name 
        FROM social_media_content smc
        LEFT JOIN cat_sources cs ON smc.cat_sources = cs.id
        WHERE smc.content_type != 2
        ORDER BY smc.id DESC LIMIT ?
    ");
    $stmt->bindValue(1, (int) $limit, PDO::PARAM_INT);
    $stmt->execute();
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$stats = getOverviewStats($db);
$currentProcess = getCurrentProcessStatus($db);
$videoStats = getVideoProcessingStats($db);
$contentDistribution = getContentDistribution($db);
$allSources = getAllSources($db);
$recentRuns = getRecentRuns($db, 20);
$recentRunsOverview = getRecentRuns($db, 10); // Last 10 for overview
$dailyStats = getDailyStats($db, 30); // Last 30 days
$dailyStatsOverview = getDailyStats($db, 10); // Last 10 days for overview
$activeVideo = getActiveProcessingVideo($db);
$recentVideosList = getRecentVideosDetailed($db, 10);
$recentContentList = getRecentAllContent($db, 10);

// 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>
    <!-- IBM Plex Sans Arabic Font -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+Arabic:wght@100;200;300;400;500;600;700&display=swap"
        rel="stylesheet">

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'IBM Plex Sans Arabic', '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;
            font-family: 'IBM Plex Sans Arabic', sans-serif;
        }

        .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;
        }

        /* Popup Modal Overlay */
        .modal-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            z-index: 9998;
            animation: fadeIn 0.3s ease-out;
        }

        .modal-overlay.active {
            display: block;
        }

        /* Popup Modal Container */
        .modal-container {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 90%;
            max-width: 1200px;
            max-height: 85vh;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
            z-index: 9999;
            overflow: hidden;
            animation: slideUp 0.3s ease-out;
        }

        .modal-container.active {
            display: block;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
            }

            to {
                opacity: 1;
            }
        }

        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translate(-50%, -40%);
            }

            to {
                opacity: 1;
                transform: translate(-50%, -50%);
            }
        }

        /* Modal Header */
        .modal-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px 25px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 3px solid #5568d3;
        }

        .modal-header h2 {
            margin: 0;
            font-size: 22px;
            color: white;
        }

        .modal-close {
            background: rgba(255, 255, 255, 0.2);
            border: 2px solid white;
            color: white;
            padding: 8px 16px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            font-weight: bold;
            transition: all 0.3s;
        }

        .modal-close:hover {
            background: white;
            color: #667eea;
            transform: scale(1.05);
        }

        /* Modal Body */
        .modal-body {
            padding: 25px;
            overflow-y: auto;
            max-height: calc(85vh - 80px);
        }

        .modal-body::-webkit-scrollbar {
            width: 10px;
        }

        .modal-body::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        .modal-body::-webkit-scrollbar-thumb {
            background: #667eea;
            border-radius: 10px;
        }

        .modal-body::-webkit-scrollbar-thumb:hover {
            background: #5568d3;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- Header -->
        <div class="header">
            <h1>📊 لوحة تحكم RSS</h1>
            <div class="header-actions">
                <button class="btn btn-warning" onclick="processAllVideos()">
                    تشغيل معالجة الفيديو
                </button>
                <div class="auto-refresh"><button class="btn btn-primary" onclick="location.reload()">🔄 تحديث
                        <?= date('Y-m-d H:i:s') ?></button>
                    <button class="btn btn-success" onclick="triggerRSS()">▶️ تشغيل RSS</button>
                </div>
            </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('content')">المحتوى</button>
                    <button class="tab-button" onclick="switchTab('sources')">المصادر</button>
                    <button class="tab-button" onclick="switchTab('videos')">الفيديوهات</button>
                    <button class="tab-button" onclick="switchTab('runs')">🕐 عمليات السحب</button>
                    <button class="tab-button" onclick="switchTab('statistics')">📊 الإحصائيات اليومية</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: #999; font-size: 13px; margin: 5px 0; font-style: italic;">
                                    (جاري سحب المنشورات من مصادر RSS الآن)
                                </p>
                                <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; ?>

                    <!-- Active Processing Video -->
                    <div id="active-video-container">
                        <?= renderActiveVideoComponent($activeVideo) ?>
                    </div>

                    <!-- 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>

                    <!-- Recent Activity Tabs -->
                    <div id="recent-activity-container">
                        <?= renderRecentActivityComponent($recentVideosList, $recentContentList, $contentTypeNames) ?>
                    </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>

                    <!-- Content Distribution -->
                    <div class="section">
                        <h2>📊 توزيع أنواع المحتوى</h2>
                        <div class="stats-grid">
                            <?php
                            $totalContent = array_sum(array_column($contentDistribution, 'count'));
                            foreach ($contentDistribution as $content):
                                $percentage = $totalContent > 0 ? ($content['count'] / $totalContent) * 100 : 0;
                                // Map groups to names
                                $typeName = 'غير محدد';
                                if ($content['type_group'] === 'image') {
                                    $typeName = 'الصورة';
                                } elseif ($content['type_group'] === 'video') {
                                    $typeName = 'فيديو عام';
                                } else {
                                    continue; // Skip 'other' or unknowns if not needed, or show them
                                }
                                ?>
                                    <div class="stat-card">
                                        <h3><?= $typeName ?></h3>
                                        <div class="value"><?= formatNumber($content['count']) ?></div>
                                        <div class="subtitle"><?= number_format($percentage, 1) ?>% من المحتوى</div>
                                    </div>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <!-- Last 10 Runs -->
                    <div class="section">
                        <h2>🕐 آخر 10 عمليات سحب</h2>
                        <table>
                            <thead>
                                <tr>
                                    <th>التاريخ</th>
                                    <th>تمت معالجته</th>
                                    <th>تم تخطيه</th>
                                    <th>أخطاء</th>
                                    <th>وقت التنفيذ</th>
                                    <th>الحالة</th>
                                    <th>إجراءات</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentRunsOverview as $run): ?>
                                        <tr>
                                            <td><?= date('Y-m-d H:i:s', strtotime($run['run_date'])) ?></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="showRunContent(<?= $run['id'] ?>)">
                                                    عرض السحب
                                                </button>
                                            </td>
                                        </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>

                        <!-- Last 10 Days Summary -->
                        <div class="section">
                            <h2>📊 ملخص آخر 10 أيام</h2>
                            <table>
                                <thead>
                                    <tr>
                                        <th>التاريخ</th>
                                        <th>عدد العمليات</th>
                                        <th>تمت معالجته</th>
                                        <th>عمليات ناجحة</th>
                                        <th>إجراءات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($dailyStatsOverview as $day): ?>
                                            <tr>
                                                <td><?= $day['date'] ?></td>
                                                <td><?= $day['total_runs'] ?></td>
                                                <td><?= formatNumber($day['total_processed'] ?? 0) ?></td>
                                                <td><span class="badge badge-success"><?= $day['successful_runs'] ?></span></td>
                                                <td>
                                                    <button class="btn btn-primary btn-small"
                                                        onclick="showDayDetails('<?= $day['date'] ?>')">
                                                        عرض التفاصيل
                                                    </button>
                                                </td>
                                            </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </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 class="stat-card"
                                style="background: linear-gradient(135deg, #ff7675 0%, #d63031 100%);">
                                <h3 style="color: white;">YouTube</h3>
                                <div class="value" style="color: white;">
                                    <?= formatNumber($videoStats['youtube_count']) ?>
                                </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; display: flex; gap: 10px; flex-wrap: wrap;">
                        <button class="btn btn-outline-primary active" onclick="switchVideoTab('all')"
                            id="btn-all">الكل</button>
                        <button class="btn btn-outline-primary" onclick="switchVideoTab('pending')"
                            id="btn-pending">معلقة</button>
                        <button class="btn btn-outline-primary" onclick="switchVideoTab('processing')"
                            id="btn-processing">معالجة</button>
                        <button class="btn btn-outline-primary" onclick="switchVideoTab('completed')"
                            id="btn-completed">مكتملة</button>
                        <button class="btn btn-outline-danger" onclick="switchVideoTab('failed')"
                            id="btn-failed">فشلت</button>
                        <button class="btn btn-outline-danger" onclick="switchVideoTab('youtube')" id="btn-youtube"
                            style="border-color: #ff0000; color: #ff0000;">YouTube</button>
                    </div>

                    <div id="videos-container">
                        <p style="text-align: center; color: #666; padding: 40px;">اختر نوع الفيديوهات لعرضها</p>
                    </div>
                    <div style="text-align: center; margin-top: 20px; display: none;" id="video-load-more-container">
                        <button class="btn btn-secondary" onclick="loadMoreVideos()">تحميل المزيد</button>
                    </div>
                </div>

                <div id="tab-content" class="tab-content">
                    <div class="section">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                            <h2>📄 إدارة المحتوى</h2>
                            <div style="display: flex; gap: 10px;">
                                <input type="text" id="contentSearch" placeholder="بحث في العنوان أو المصدر..."
                                    style="padding: 8px; border: 1px solid #ddd; border-radius: 5px; width: 250px;"
                                    onkeyup="params.search = this.value; if(event.key === 'Enter') loadContent(1);">
                                <select id="contentTypeFilter" onchange="params.type = this.value; loadContent(1);"
                                    style="padding: 8px; border-radius: 5px; border: 1px solid #ddd;">
                                    <option value="all">كل الأنواع</option>
                                    <?php foreach ($contentTypeNames as $id => $name): ?>
                                            <option value="<?= $id ?>"><?= $name ?></option>
                                    <?php endforeach; ?>
                                </select>
                                <button class="btn btn-primary" onclick="loadContent(1)">بحث</button>
                            </div>
                        </div>

                        <div id="content-table-container">
                            <!-- Content Table Loaded Here -->
                            <div style="text-align: center; padding: 50px;">
                                <div class="spinner"></div>
                                <p>جاري تحميل المحتوى...</p>
                            </div>
                        </div>

                        <div class="pagination" id="content-pagination"
                            style="display: flex; justify-content: center; gap: 5px; margin-top: 20px;">
                            <!-- Pagination Links -->
                        </div>
                    </div>
                </div>

                <!-- Sources Tab -->
                <div id="tab-sources" class="tab-content">
                    <div class="section">
                        <div
                            style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <h2>📊 جميع المصادر (<?= count($allSources) ?>)</h2>
                                <div class="filter-buttons">
                                    <button class="btn btn-outline active"
                                        onclick="filterSources('all', this)">الكل</button>
                                    <button class="btn btn-outline" onclick="filterSources('active', this)">نشط</button>
                                    <button class="btn btn-outline"
                                        onclick="filterSources('stopped', this)">متوقف</button>
                                </div>
                            </div>
                            <button class="btn btn-primary" onclick="openAddSourceModal()">+ إضافة مصدر جديد</button>
                        </div>

                        <style>
                            .filter-buttons .btn-outline {
                                background: transparent;
                                border: 1px solid #667eea;
                                color: #667eea;
                                padding: 5px 15px;
                                border-radius: 20px;
                                cursor: pointer;
                                transition: all 0.3s;
                            }

                            .filter-buttons .btn-outline.active,
                            .filter-buttons .btn-outline:hover {
                                background: #667eea;
                                color: white;
                            }
                        </style>

                        <script>
                            function filterSources(filter, btn) {
                                // Update buttons state
                                document.querySelectorAll('.filter-buttons .btn-outline').forEach(b => b.classList.remove('active'));
                                btn.classList.add('active');

                                // Filter cards
                                const cards = document.querySelectorAll('.source-card');
                                cards.forEach(card => {
                                    const isStopped = card.classList.contains('status-stopped');
                                    if (filter === 'all') {
                                        card.style.display = 'block';
                                    } else if (filter === 'active') {
                                        card.style.display = isStopped ? 'none' : 'block';
                                    } else if (filter === 'stopped') {
                                        card.style.display = isStopped ? 'block' : 'none';
                                    }
                                });
                            }
                        </script>

                        <?php foreach ($allSources as $source): ?>
                                <div class="source-card <?= $source['status'] == 0 ? 'status-stopped' : '' ?>"
                                    onclick="viewSourceDetails(<?= $source['id'] ?>)">
                                    <div style="display: flex; justify-content: space-between; align-items: flex-start;">
                                        <h3 style="margin: 0;"><?= htmlspecialchars($source['name']) ?></h3>
                                        <div class="card-actions" onclick="event.stopPropagation()">
                                            <?php if ($source['status'] == 1): ?>
                                                    <button class="btn btn-small btn-danger"
                                                        onclick="toggleSourceStatus(<?= $source['id'] ?>, 0)">إيقاف</button>
                                            <?php else: ?>
                                                    <button class="btn btn-small btn-success"
                                                        onclick="toggleSourceStatus(<?= $source['id'] ?>, 1)">تشغيل</button>
                                            <?php endif; ?>
                                            <button class="btn btn-small btn-secondary"
                                                onclick="editSource(<?= $source['id'] ?>)">تعديل</button>
                                        </div>
                                    </div>

                                    <!-- Status Badge for Stopped Sources -->
                                    <?php if ($source['status'] == 0): ?>
                                            <span class="badge badge-danger"
                                                style="margin-top: 5px; display: inline-block;">متوقف</span>
                                    <?php endif; ?>

                                    <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>

            <!-- Statistics Tab -->
            <div id="tab-statistics" class="tab-content">
                <div class="section">
                    <h2>📊 الإحصائيات اليومية التفصيلية</h2>

                    <!-- Filters -->
                    <div style="margin-bottom: 20px; display: flex; gap: 15px; align-items: center; flex-wrap: wrap;">
                        <div>
                            <label style="margin-left: 5px;">من:</label>
                            <input type="date" id="statsStartDate"
                                style="padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
                        </div>
                        <div>
                            <label style="margin-left: 5px;">إلى:</label>
                            <input type="date" id="statsEndDate"
                                style="padding: 8px; border: 1px solid #ddd; border-radius: 5px;">
                        </div>
                        <div>
                            <label style="margin-left: 5px;">المصدر:</label>
                            <select id="statsSourceFilter"
                                style="padding: 8px; border: 1px solid #ddd; border-radius: 5px; min-width: 150px;">
                                <option value="">كل المصادر</option>
                                <?php foreach ($allSources as $source): ?>
                                        <option value="<?= $source['id'] ?>"><?= htmlspecialchars($source['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <button class="btn btn-primary" onclick="applyStatsFilter()">تطبيق</button>
                        <button class="btn btn-primary" onclick="resetStatsFilter()">إعادة تعيين</button>
                    </div>

                    <!-- Statistics Table -->
                    <table id="statsTable">
                        <thead>
                            <tr>
                                <th>التاريخ</th>
                                <th>عدد العمليات</th>
                                <th>تمت معالجته</th>
                                <th>تم تخطيه</th>
                                <th>أخطاء</th>
                                <th>متوسط وقت التنفيذ</th>
                                <th>عمليات ناجحة</th>
                                <th>عمليات فاشلة</th>
                                <th>إجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($dailyStats as $day): ?>
                                    <tr style="cursor: pointer;" onclick="showDayDetails('<?= $day['date'] ?>')">
                                        <td><?= $day['date'] ?></td>
                                        <td><?= $day['total_runs'] ?></td>
                                        <td><?= formatNumber($day['total_processed'] ?? 0) ?></td>
                                        <td><?= formatNumber($day['total_skipped'] ?? 0) ?></td>
                                        <td><?= formatNumber($day['total_errors'] ?? 0) ?></td>
                                        <td><?= formatTime($day['avg_execution_time'] ?? 0) ?></td>
                                        <td><span class="badge badge-success"><?= $day['successful_runs'] ?></span></td>
                                        <td><span class="badge badge-danger"><?= $day['failed_runs'] ?></span></td>
                                        <td>
                                            <button class="btn btn-primary btn-small"
                                                onclick="event.stopPropagation(); showDayDetails('<?= $day['date'] ?>')">
                                                عرض التفاصيل
                                            </button>
                                        </td>
                                    </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Modal Overlay -->
        <div id="modal-overlay" class="modal-overlay" onclick="closeDayDetails()"></div>

        <!-- Add/Edit Source Modal -->
        <div id="source-modal" class="modal-container">
            <div class="modal-header">
                <h2 id="source-modal-title">إضافة مصدر جديد</h2>
                <button class="modal-close" onclick="closeSourceModal()">✕ إغلاق</button>
            </div>
            <div class="modal-body">
                <form id="source-form" onsubmit="saveSource(event)">
                    <input type="hidden" id="source_id" name="source_id" value="">

                    <div class="form-group" style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: bold;">اسم المصدر</label>
                        <input type="text" id="source_name" name="name" required
                            style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                    </div>

                    <div class="form-group" style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: bold;">رابط JSON Feed</label>
                        <input type="url" id="source_feed" name="json_feed" required
                            style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                    </div>

                    <div class="form-group" style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: bold;">رابط الموقع
                            (اختياري)</label>
                        <input type="url" id="source_link" name="link_url"
                            style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 5px;">
                    </div>

                    <div style="text-align: left; margin-top: 20px;">
                        <button type="submit" class="btn btn-primary">حفظ</button>
                    </div>
                </form>
            </div>
        </div>

        <style>
            .source-card.status-stopped {
                background: #f8f9fa;
                border-left: 4px solid #dc3545;
                opacity: 0.8;
            }

            .card-actions button {
                margin-left: 5px;
                font-size: 12px;
                padding: 5px 10px;
            }
        </style>

        <!-- Details Popup Modal -->
        <div id="details-modal" class="modal-container">
            <div class="modal-header">
                <h2 id="modal-title">📅 تفاصيل</h2>
                <button class="modal-close" onclick="closeDayDetails()">✕ إغلاق</button>
            </div>
            <div class="modal-body">
                <div id="modal-content"></div>
            </div>
        </div>


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

    <script src="day_details.js"></script>
    <script src="run_content.js"></script>
    <script>
        // Init state for polling
        let lastIdState = <?= json_encode($stats['last_id'] ?? 0) ?>;
        // Hash for processing
        <?php
        $stmt = $db->query("SELECT COUNT(*) as cnt, SUM(processing_percentage) as sum_pct FROM social_media_content WHERE video_processing = 1");
        $row = $stmt->fetch();
        $initialHash = $row['cnt'] . '-' . $row['sum_pct'];
        ?>
        let processingState = "<?= $initialHash ?>";

        function switchSubTab(subTabName) {
            // Hide all subtabs
            document.getElementById('subtab-videos_list').style.display = 'none';
            document.getElementById('subtab-content_list').style.display = 'none';

            // Reset buttons
            document.getElementById('btn-videos_list').style.background = '#f8f9fa';
            document.getElementById('btn-videos_list').style.color = '#666';
            document.getElementById('btn-videos_list').classList.remove('btn-primary');
            document.getElementById('btn-videos_list').classList.add('btn-secondary');

            document.getElementById('btn-content_list').style.background = '#f8f9fa';
            document.getElementById('btn-content_list').style.color = '#666';
            document.getElementById('btn-content_list').classList.remove('btn-primary');
            document.getElementById('btn-content_list').classList.add('btn-secondary');

            // Show selected
            document.getElementById('subtab-' + subTabName).style.display = 'block';

            // Highlight button
            let btn = document.getElementById('btn-' + subTabName);
            btn.style.background = ''; // reset
            btn.style.color = '';
            btn.classList.remove('btn-secondary');
            btn.classList.add('btn-primary');
        }

        // Smart Polling for Partial Updates (Every 3 seconds)
        // Fetches JSON with stats and HTML fragments, updates DOM only if needed (based on hash or always if we want smooth progress bar).
        // Since we want live progress bar, we might want to update active video whenever we get data.

        // Let's store current SubTab to restore it after update
        let currentSubTab = 'videos_list';

        function updateContent(data) {
            // Update Active Video Container
            const activeContainer = document.getElementById('active-video-container');
            if (activeContainer && data.active_html !== undefined) {
                // Only update if changed or force update (for progress bar smoothness we might update provided server sends it)
                // For optimal DOM usage, we could check if HTML changed. 
                // But replacing innerHTML is fast enough for this size.
                if (activeContainer.innerHTML != data.active_html) {
                    activeContainer.innerHTML = data.active_html;
                }
            }

            // Update Recent Activity Container
            const recentContainer = document.getElementById('recent-activity-container');
            if (recentContainer && data.recent_html !== undefined) {
                // Check if content hash changed (optimized way)
                // or just replace (simple way since user complained about page reload, not DOM repaint)
                // However, replacing innerHTML destroys tab state (which tab is open).
                // We need to preserve tab state.

                // Check current visible subtab before replace
                let isVideosVisible = document.getElementById('subtab-videos_list').style.display === 'block';
                let isContentVisible = document.getElementById('subtab-content_list').style.display === 'block';

                // If hashes match, maybe skip? (We rely on processing_hash)
                // But simply replacing is safer to ensure data consistency.

                if (recentContainer.innerHTML != data.recent_html) {
                    recentContainer.innerHTML = data.recent_html;

                    // Restore Tab State
                    if (isContentVisible) {
                        switchSubTab('content_list');
                    } else {
                        switchSubTab('videos_list'); // Default
                    }
                }
            }
        }

        setInterval(function () {
            fetch('index.php?check_update=1')
                .then(response => response.json())
                .then(data => {
                    updateContent(data);
                })
                .catch(err => console.error("Polling error:", err));
        }, 3000);

        // Global parameters for content tab
        const params = {
            page: 1,
            limit: 20,
            type: 'all',
            search: ''
        };

        // Auto-refresh logic REMOVED.

        let elapsedTimeInterval = null;

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


        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
            if (event) {
                event.target.classList.add('active');
            } else {
                // If called programmatically without event
                const buttons = document.querySelectorAll('.tab-button');
                // Logic to find button by index or attribute if needed, but simple toggle is enough for now
            }

            // Load content if switching to content tab
            if (tabName === 'content') {
                loadContent(1);
            }
        }

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

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

            fetch('../api/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);
                });
        }

        // ==========================================
        // Source Management Functions
        // ==========================================

        function openAddSourceModal() {
            document.getElementById('source-modal-title').textContent = 'إضافة مصدر جديد';
            document.getElementById('source_id').value = '';
            document.getElementById('source_name').value = '';
            document.getElementById('source_feed').value = '';
            document.getElementById('source_link').value = '';

            document.getElementById('modal-overlay').classList.add('active');
            document.getElementById('source-modal').classList.add('active');
        }

        function closeSourceModal() {
            document.getElementById('modal-overlay').classList.remove('active');
            document.getElementById('source-modal').classList.remove('active');
        }

        function editSource(sourceId) {
            document.getElementById('loading').classList.add('active');

            fetch(`api.php?action=get_source_details&source_id=${sourceId}`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    if (data.success) {
                        const source = data.data;
                        document.getElementById('source-modal-title').textContent = 'تعديل مصدر';
                        document.getElementById('source_id').value = source.id;
                        document.getElementById('source_name').value = source.name;
                        document.getElementById('source_feed').value = source.json_feed;
                        document.getElementById('source_link').value = source.link_url;

                        document.getElementById('modal-overlay').classList.add('active');
                        document.getElementById('source-modal').classList.add('active');
                    } else {
                        alert('حدث خطأ أثناء جلب بيانات المصدر');
                    }
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    console.error('Error:', error);
                    alert('حدث خطأ في الاتصال');
                });
        }

        function saveSource(event) {
            event.preventDefault();

            const formData = new FormData(document.getElementById('source-form'));
            document.getElementById('loading').classList.add('active');

            fetch('api.php?action=save_source', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    if (data.success) {
                        alert('تم الحفظ بنجاح!');
                        closeSourceModal();
                        location.reload(); // Reload to show changes
                    } else {
                        alert('حدث خطأ أثناء الحفظ');
                    }
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    console.error('Error:', error);
                    alert('حدث خطأ في الاتصال');
                });
        }

        function toggleSourceStatus(sourceId, newStatus) {
            const action = newStatus === 1 ? 'تشغيل' : 'إيقاف';
            if (!confirm(`هل أنت متأكد من ${action} هذا المصدر؟`)) {
                return;
            }

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

            const formData = new FormData();
            formData.append('source_id', sourceId);
            formData.append('status', newStatus);

            fetch('api.php?action=toggle_source_status', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    if (data.success) {
                        location.reload();
                    } else {
                        alert('حدث خطأ أثناء تغيير الحالة');
                    }
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    console.error('Error:', error);
                    alert('حدث خطأ في الاتصال');
                });
        }

        function loadContent(page = 1) {
            params.page = page;
            const container = document.getElementById('content-table-container');
            const pagination = document.getElementById('content-pagination');

            console.log('Loading content page:', page); // DEBUG
            container.innerHTML = '<div style="text-align: center; padding: 50px;"><div class="spinner"></div><p>جاري تحميل المحتوى...</p></div>';

            const queryString = new URLSearchParams(params).toString();
            console.log('Fetching:', `api.php?action=get_all_content&${queryString}`); // DEBUG

            fetch(`api.php?action=get_all_content&${queryString}`)
                .then(response => {
                    console.log('Response status:', response.status); // DEBUG
                    return response.text().then(text => {
                        console.log('Raw response:', text); // DEBUG
                        try {
                            return JSON.parse(text);
                        } catch (e) {
                            console.error('JSON Parse Error:', e);
                            throw new Error('Invalid JSON response: ' + text.substring(0, 100));
                        }
                    });
                })
                .then(data => {
                    console.log('Parsed data:', data); // DEBUG
                    if (data.success) {
                        renderContentTable(data.data);
                        renderPagination(data.pages, data.page);
                    } else {
                        console.error('API Error:', data);
                        container.innerHTML = `<p style="text-align: center; color: red;">فشل تحميل المحتوى: ${data.message || 'خطأ غير معروف'}</p>`;
                    }
                })
                .catch(error => {
                    console.error('Fetch Error:', error);
                    container.innerHTML = `<p style="text-align: center; color: red;">حدث خطأ في الاتصال: ${error.message}</p>`;
                    alert('خطأ في تحميل البيانات. يرجى مراجعة Console للمزيد من التفاصيل.');
                });
        }

        function renderContentTable(items) {
            const container = document.getElementById('content-table-container');
            if (items.length === 0) {
                container.innerHTML = '<p style="text-align: center; padding: 20px;">لا يوجد محتوى للعرض</p>';
                return;
            }

            let html = '<table class="data-table"><thead><tr>' +
                '<th>ID</th>' +
                '<th>المصدر</th>' +
                '<th>العنوان</th>' +
                '<th>النوع</th>' +
                '<th>الحالة</th>' +
                '<th>تاريخ الإضافة</th>' +
                '<th>إجراءات</th>' +
                '</tr></thead><tbody>';

            const contentTypeNames = {
                1: 'صورة', 2: 'يوتيوب', 3: 'عاجل/خاص', 6: 'صور متعددة', 10: 'فيديو عام', 15: 'نص فقط', 21: 'فيديو تويتر'
            };

            items.forEach(item => {
                const typeName = contentTypeNames[item.content_type] || 'غير معروف';
                const statusBadge = item.status == 1
                    ? '<span class="badge badge-success">منشور</span>'
                    : '<span class="badge badge-secondary" style="background: #6c757d;">مخفي</span>';

                const toggleBtn = item.status == 1
                    ? `<button onclick="toggleContentStatusInTab(${item.id}, 0)" class="btn btn-small btn-danger">إخفاء</button>`
                    : `<button onclick="toggleContentStatusInTab(${item.id}, 1)" class="btn btn-small btn-success">نشر</button>`;

                html += `<tr>
                    <td>${item.id}</td>
                    <td><span class="badge badge-secondary">${item.source_name || 'غير معروف'}</span></td>
                    <td title="${item.title || ''}">${(item.title || 'بدون عنوان').substring(0, 50)}</td>
                    <td>${typeName}</td>
                    <td>${statusBadge}</td>
                    <td>${item.create_date}</td>
                    <td>
                        <a href="../../post.php?id=${item.post_id}" target="_blank" class="btn btn-primary btn-small">عرض</a>
                        ${toggleBtn}
                    </td>
                </tr>`;
            });

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

        function renderPagination(totalPages, currentPage) {
            const container = document.getElementById('content-pagination');
            let html = '';

            if (totalPages <= 1) {
                container.innerHTML = '';
                return;
            }

            // Previous
            if (currentPage > 1) {
                html += `<button class="btn btn-secondary btn-small" onclick="loadContent(${currentPage - 1})">السابق</button>`;
            }

            // Pages
            let start = Math.max(1, currentPage - 2);
            let end = Math.min(totalPages, currentPage + 2);

            if (start > 1) html += '<span style="padding: 5px;">...</span>';

            for (let i = start; i <= end; i++) {
                const activeClass = i === currentPage ? 'btn-primary' : 'btn-secondary';
                html += `<button class="btn ${activeClass} btn-small" onclick="loadContent(${i})">${i}</button>`;
            }

            if (end < totalPages) html += '<span style="padding: 5px;">...</span>';

            // Next
            if (currentPage < totalPages) {
                html += `<button class="btn btn-secondary btn-small" onclick="loadContent(${currentPage + 1})">التالي</button>`;
            }

            container.innerHTML = html;
        }

        function toggleContentStatusInTab(postId, newStatus) {
            const action = newStatus === 1 ? 'نشر' : 'إخفاء';
            if (!confirm(`هل أنت متأكد من ${action} هذا المحتوى؟`)) {
                return;
            }

            const formData = new FormData();
            formData.append('post_id', postId);
            formData.append('status', newStatus);

            fetch('api.php?action=toggle_content_status', {
                method: 'POST',
                body: formData
            })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        loadContent(params.page); // Reload current page
                    } else {
                        alert('حدث خطأ أثناء تغيير الحالة');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('حدث خطأ في الاتصال');
                });
        }

        // ==========================================

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

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

            fetch('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);
                });
        }

        // Video Tabs Logic
        let currentVideoStatus = 'all';
        let currentVideoPage = 1;

        function switchVideoTab(status) {
            // Update active button
            document.querySelectorAll('#tab-videos .btn-outline-primary, #tab-videos .btn-outline-danger').forEach(btn => {
                btn.classList.remove('active');
            });
            document.getElementById('btn-' + status).classList.add('active');

            // Reset and load
            currentVideoStatus = status;
            currentVideoPage = 1;
            loadVideos(status, 1);
        }

        function loadMoreVideos() {
            currentVideoPage++;
            loadVideos(currentVideoStatus, currentVideoPage, true);
        }

        function loadVideos(status, page = 1, append = false) {
            if (!append) {
                document.getElementById('loading').classList.add('active');
                document.getElementById('videos-container').innerHTML = ''; // Clear if not appending
                document.getElementById('video-load-more-container').style.display = 'none';
            } else {
                // Show small spinner or text? For now just keep button
                document.getElementById('video-load-more-container').querySelector('button').innerText = 'جاري التحميل...';
            }

            console.log('Loading videos:', status, 'Page:', page);

            fetch(`api.php?action=get_videos_by_status&status=${status}&page=${page}&limit=20`)
                .then(response => response.json())
                .then(data => {
                    document.getElementById('loading').classList.remove('active');
                    if (append) {
                        document.getElementById('video-load-more-container').querySelector('button').innerText = 'تحميل المزيد';
                    }

                    if (data.length > 0) {
                        displayVideos(data, status, append);
                        // Show load more if we got a full page (assuming limit 20)
                        if (data.length >= 20) {
                            document.getElementById('video-load-more-container').style.display = 'block';
                        } else {
                            document.getElementById('video-load-more-container').style.display = 'none';
                        }
                    } else {
                        if (!append) {
                            displayVideos([], status, false); // Show empty state
                        }
                        document.getElementById('video-load-more-container').style.display = 'none';
                    }
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    alert('حدث خطأ أثناء جلب الفيديوهات.');
                    console.error('Error:', error);
                });
        }

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

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

            let html = '';
            if (!append) {
                // Create table header if new list
                html = '<table class="data-table"><thead><tr>' +
                    '<th>ID</th>' +
                    '<th>المصدر</th>' +
                    '<th>العنوان</th>' +
                    '<th>النوع</th>' +
                    '<th>تاريخ الإضافة</th>' +
                    '<th>الحالة</th>' +
                    '<th>إجراءات</th>' +
                    '</tr></thead><tbody id="video-table-body">';
            }

            // Generate rows
            let rows = videos.map(video => {
                let statusText = 'معلق';
                let statusClass = 'badge-warning';
                if (video.video_processing == 1) {
                    statusText = 'قيد المعالجة';
                    statusClass = 'badge-info';
                } else if (video.video_processing == 2) {
                    statusText = 'مكتمل';
                    statusClass = 'badge-success';
                } else if (video.video_processing == 3) {
                    statusText = 'فشل/تخطي';
                    statusClass = 'badge-danger';
                    // statusClass = 'badge-danger'; // Already defined?
                }

                const contentTypeName = {
                    2: 'يوتيوب',
                    10: 'فيديو عام',
                    21: 'فيديو تويتر'
                }[video.content_type] || 'فيديو';

                return `<tr>
                    <td>${video.id}</td>
                    <td><span class="badge badge-secondary">${video.source_name || 'غير معروف'}</span></td>
                    <td title="${video.title || ''}">${(video.title || 'بدون عنوان').substring(0, 50)}</td>
                    <td>${contentTypeName}</td>
                    <td dir="ltr">${video.create_date}</td>
                    <td><span class="badge ${statusClass}">${statusText}</span></td>
                    <td>
                        <a href="../../post.php?id=${video.post_id}" target="_blank" class="btn btn-primary btn-small">عرض</a>
                        ${(video.video_processing == 3) ? `<button class="btn btn-secondary btn-small" onclick="retryVideo(${video.id})">إعادة</button>` : ''}
                    </td>
                </tr>`;
            }).join('');

            if (append) {
                // Append rows to existing table body
                const tbody = document.getElementById('video-table-body');
                if (tbody) {
                    tbody.insertAdjacentHTML('beforeend', rows);
                } else {
                    // Should not happen if flow is correct, but fallback
                    container.innerHTML += rows;
                }
            } else {
                // Set full HTML
                html += rows + '</tbody></table>';
                container.innerHTML = html;
            }
        }
        // Process single video
        function processSingleVideo(videoId) {
            if (!confirm('هل تريد معالجة هذا الفيديو الآن؟')) {
                return;
            }

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

            fetch('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(currentVideoStatus), 2000);
                    } else {
                        alert('حدث خطأ: ' + (data.message || 'خطأ غير معروف'));
                    }
                })
                .catch(error => {
                    document.getElementById('loading').classList.remove('active');
                    alert('حدث خطأ أثناء معالجة الفيديو.');
                    console.error('Error:', error);
                });
        }

        function retryVideo(videoId) {
            if (!confirm('هل تريد إعادة محاولة معالجة هذا الفيديو Failed/Skipped؟\n\nسيتم تغيير حالته إلى "Pending" (0) ليقوم السكريبت بالتقاطه مجدداً.')) {
                return;
            }

            // We can reuse a simple API endpoint to reset status to 0
            // Since we don't have a direct "retry" action, we can use toggle_content_status or make a new one?
            // Actually process_videos.php picks up 0 or NULL. So we just need to set video_processing = 0.
            // Let's use a quick fetch to update it. We might need a new action in api.php or use an existing one if adaptable.
            // Let's assume we add 'reset_video_status' to api.php or use a direct update if available.
            // For now, let's use the 'processSingleVideo' approach but just reset the status in DB first? 
            // Or better, let's implement a clean 'reset_video' action.

            // Wait, I don't have 'reset_video' in api.php. I should add it.
            // But I can also just use `processSingleVideo` if it forces processing?
            // `trigger_video_processing` just runs the script. It doesn't reset status.

            // Let's add `action=reset_video_status` to api.php effectively. 
            // Since I cannot edit api.php in this step, I will add the JS here and then go to api.php.

            fetch('api.php?action=reset_video_status&id=' + videoId)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        alert('تم إعادة تعيين الحالة. سيقوم النظام بمحاولة المعالجة قريباً.');
                        loadVideos(currentVideoStatus);
                    } else {
                        alert('حدث خطأ: ' + (data.message || 'غير معروف'));
                    }
                })
                .catch(error => {
                    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('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);
                });
        }

        // Filter daily stats by date range
        function filterDailyStats() {
            const startDate = document.getElementById('startDate').value;
            const endDate = document.getElementById('endDate').value;

            if (!startDate || !endDate) {
                alert('الرجاء تحديد تاريخ البداية والنهاية');
                return;
            }

            const table = document.getElementById('dailyStatsTable');
            const rows = table.querySelectorAll('tbody tr');

            rows.forEach(row => {
                const dateCell = row.cells[0].textContent;
                if (dateCell >= startDate && dateCell <= endDate) {
                    row.style.display = '';
                } else {
                    row.style.display = 'none';
                }
            });
        }

        // Reset daily stats filter
        function resetDailyStats() {
            document.getElementById('startDate').value = '';
            document.getElementById('endDate').value = '';

            const table = document.getElementById('dailyStatsTable');
            const rows = table.querySelectorAll('tbody tr');

            rows.forEach(row => {
                row.style.display = '';
            });
        }

        // Apply statistics filter (new tab)
        function applyStatsFilter() {
            const startDate = document.getElementById('statsStartDate').value;
            const endDate = document.getElementById('statsEndDate').value;
            const sourceId = document.getElementById('statsSourceFilter').value;

            const table = document.getElementById('statsTable');
            const rows = table.querySelectorAll('tbody tr');

            rows.forEach(row => {
                const dateCell = row.cells[0].textContent;
                let showRow = true;

                // Date filter
                if (startDate && endDate) {
                    if (dateCell < startDate || dateCell > endDate) {
                        showRow = false;
                    }
                }

                // Note: Source filtering would require additional data attributes or API call
                // For now, we'll just filter by date

                row.style.display = showRow ? '' : 'none';
            });
        }

        // Reset statistics filter
        function resetStatsFilter() {
            document.getElementById('statsStartDate').value = '';
            document.getElementById('statsEndDate').value = '';
            document.getElementById('statsSourceFilter').value = '';

            const table = document.getElementById('statsTable');
            const rows = table.querySelectorAll('tbody tr');

            rows.forEach(row => {
                row.style.display = '';
            });
        }

        // Close day details modal
        function closeDayDetails() {
            document.getElementById('modal-overlay').classList.remove('active');
            document.getElementById('details-modal').classList.remove('active');
        }

        // Open details modal
        function openDetailsModal(title, content) {
            document.getElementById('modal-title').textContent = title;
            document.getElementById('modal-content').innerHTML = content;
            document.getElementById('modal-overlay').classList.add('active');
            document.getElementById('details-modal').classList.add('active');
        }
    </script>
</body>

</html>