<?php
/**
 * Source Details Page
 * Detailed view of a specific RSS source
 */

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

$sourceId = $_GET['id'] ?? 0;

if (!$sourceId) {
    die('Source ID is required');
}

// Get source info
$stmt = $db->prepare("SELECT * FROM cat_sources WHERE id = ?");
$stmt->execute([$sourceId]);
$source = $stmt->fetch();

if (!$source) {
    die('Source not found');
}

// Get source statistics
$stmt = $db->prepare("
    SELECT 
        COUNT(*) as total_posts,
        SUM(CASE WHEN content_type = 1 THEN 1 ELSE 0 END) as images_count,
        SUM(CASE WHEN content_type IN (2, 21) THEN 1 ELSE 0 END) as videos_count,
        SUM(CASE WHEN content_type = 6 THEN 1 ELSE 0 END) as galleries_count,
        SUM(CASE WHEN content_type = 3 THEN 1 ELSE 0 END) as urgent_count,
        MAX(create_date) as last_post_date,
        MIN(create_date) as first_post_date
    FROM social_media_content 
    WHERE cat_sources = ?
");
$stmt->execute([$sourceId]);
$stats = $stmt->fetch();

// Get content type breakdown
$stmt = $db->prepare("
    SELECT content_type, COUNT(*) as count 
    FROM social_media_content 
    WHERE cat_sources = ?
    GROUP BY content_type
    ORDER BY count DESC
");
$stmt->execute([$sourceId]);
$contentBreakdown = $stmt->fetchAll();

// Get recent posts with title
$stmt = $db->prepare("
    SELECT id, post_id, title, content_type, photo, video_url, create_date, status
    FROM social_media_content 
    WHERE cat_sources = ?
    ORDER BY create_date DESC
    LIMIT 100
");
$stmt->execute([$sourceId]);
$recentPosts = $stmt->fetchAll();

// Get recent fetch logs
$stmt = $db->prepare("
    SELECT rsl.*, rl.run_date
    FROM rss_source_logs rsl
    LEFT JOIN rss_logs rl ON rsl.log_id = rl.id
    WHERE rsl.source_id = ?
    ORDER BY rl.run_date DESC
    LIMIT 20
");
$stmt->execute([$sourceId]);
$fetchLogs = $stmt->fetchAll();

$contentTypeNames = [
    1 => 'صورة',
    2 => 'يوتيوب',
    3 => 'عاجل/خاص',
    6 => 'صور متعددة',
    10 => 'فيديو عام',
    15 => 'نص فقط',
    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>تفاصيل المصدر - <?= htmlspecialchars($source['name']) ?></title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

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

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

        .header {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            margin-bottom: 25px;
        }

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

        .header .source-url {
            color: #666;
            font-size: 14px;
            word-break: break-all;
        }

        .back-btn {
            display: inline-block;
            padding: 10px 20px;
            background: #667eea;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            margin-bottom: 15px;
            transition: all 0.3s;
        }

        .back-btn:hover {
            background: #764ba2;
            transform: translateY(-2px);
        }

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

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

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

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

        .section {
            background: white;
            padding: 25px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 25px;
        }

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

        table {
            width: 100%;
            border-collapse: collapse;
        }

        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-info {
            background: #d1ecf1;
            color: #0c5460;
        }

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

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

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #eee;
            border-radius: 10px;
            overflow: hidden;
            margin-top: 5px;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
        }
    </style>
</head>

<body>
    <div class="container">
        <a href="index.php" class="back-btn">← العودة للوحة التحكم</a>

        <div class="header">
            <h1><?= htmlspecialchars($source['name']) ?></h1>
            <div class="source-url"><?= htmlspecialchars($source['json_feed']) ?></div>
        </div>

        <!-- Statistics -->
        <div class="stats-grid">
            <div class="stat-card">
                <h3>إجمالي المنشورات</h3>
                <div class="value"><?= number_format($stats['total_posts']) ?></div>
            </div>

            <div class="stat-card">
                <h3>صور</h3>
                <div class="value"><?= number_format($stats['images_count']) ?></div>
            </div>

            <div class="stat-card">
                <h3>فيديوهات</h3>
                <div class="value"><?= number_format($stats['videos_count']) ?></div>
            </div>

            <div class="stat-card">
                <h3>معارض</h3>
                <div class="value"><?= number_format($stats['galleries_count']) ?></div>
            </div>

            <div class="stat-card">
                <h3>عاجل/خاص</h3>
                <div class="value"><?= number_format($stats['urgent_count']) ?></div>
            </div>
        </div>

        <!-- Content Type Breakdown -->
        <div class="section">
            <h2>📊 توزيع أنواع المحتوى</h2>
            <table>
                <thead>
                    <tr>
                        <th>النوع</th>
                        <th>العدد</th>
                        <th>النسبة</th>
                        <th>التقدم</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($contentBreakdown as $item): ?>
                        <?php
                        $percentage = ($item['count'] / $stats['total_posts']) * 100;
                        $typeName = $contentTypeNames[$item['content_type']] ?? 'غير معروف';
                        ?>
                        <tr>
                            <td><?= $typeName ?> (<?= $item['content_type'] ?>)</td>
                            <td><?= number_format($item['count']) ?></td>
                            <td><?= number_format($percentage, 1) ?>%</td>
                            <td>
                                <div class="progress-bar">
                                    <div class="progress-fill" style="width: <?= $percentage ?>%"></div>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Recent Fetch Logs -->
        <div class="section">
            <h2>🕐 آخر عمليات السحب</h2>
            <table>
                <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 ($fetchLogs as $log): ?>
                        <tr>
                            <td><?= $log['run_date'] ? date('Y-m-d H:i:s', strtotime($log['run_date'])) : '--' ?></td>
                            <td><?= $log['items_found'] ?></td>
                            <td><?= $log['items_processed'] ?></td>
                            <td><?= $log['items_skipped'] ?></td>
                            <td><?= $log['items_errors'] ?></td>
                            <td><?= $log['photos_downloaded'] ?></td>
                            <td><?= $log['videos_downloaded'] ?></td>
                            <td><?= number_format($log['execution_time'], 2) ?>s</td>
                            <td>
                                <?php
                                $badgeClass = 'badge-success';
                                if ($log['status'] == 'failed')
                                    $badgeClass = 'badge-danger';
                                elseif ($log['status'] == 'partial')
                                    $badgeClass = 'badge-warning';
                                ?>
                                <span class="badge <?= $badgeClass ?>"><?= $log['status'] ?></span>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Recent Posts -->
        <div class="section">
            <h2>📝 آخر المنشورات (100)</h2>
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Post ID</th>
                        <th>العنوان</th>
                        <th>النوع</th>
                        <th>صورة</th>
                        <th>الفيديو</th>
                        <th>الحالة</th>
                        <th>تاريخ الإضافة</th>
                        <th>إجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($recentPosts as $post): ?>
                        <tr>
                            <td><strong><?= $post['id'] ?></strong></td>
                            <td>
                                <a href="../../post.php?id=<?= htmlspecialchars($post['post_id']) ?>" target="_blank"
                                    style="color: #667eea; text-decoration: none; font-weight: bold;">
                                    <?= htmlspecialchars($post['post_id']) ?>
                                </a>
                            </td>
                            <td style="max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;"
                                title="<?= htmlspecialchars($post['title'] ?? '') ?>">
                                <?= htmlspecialchars(mb_substr($post['title'] ?? 'بدون عنوان', 0, 50)) ?>
                                <?= mb_strlen($post['title'] ?? '') > 50 ? '...' : '' ?>
                            </td>
                            <td>
                                <span class="badge badge-info">
                                    <?= $contentTypeNames[$post['content_type']] ?? 'غير معروف' ?>
                                </span>
                            </td>
                            <td>
                                <?php if ($post['photo']): ?>
                                    <a href="<?= htmlspecialchars($post['photo']) ?>" target="_blank"
                                        style="color: #28a745; text-decoration: none; font-weight: bold;">
                                        🖼️ عرض
                                    </a>
                                <?php else: ?>
                                    ❌
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($post['video_url']): ?>
                                    <a href="<?= htmlspecialchars($post['video_url']) ?>" target="_blank"
                                        style="color: #dc3545; text-decoration: none; font-weight: bold;">
                                        🎥 عرض
                                    </a>
                                <?php else: ?>
                                    ❌
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($post['status'] == 1): ?>
                                    <span class="badge badge-success">منشور</span>
                                <?php else: ?>
                                    <span class="badge badge-secondary" style="background: #6c757d;">مخفي</span>
                                <?php endif; ?>
                            </td>
                            <td><?= date('Y-m-d H:i:s', strtotime($post['create_date'])) ?></td>
                            <td>
                                <a href="../../post.php?id=<?= htmlspecialchars($post['post_id']) ?>" target="_blank"
                                    class="btn btn-primary btn-small"
                                    style="padding: 4px 8px; font-size: 11px; display: inline-block; text-decoration: none;">
                                    عرض
                                </a>
                                <?php if ($post['status'] == 1): ?>
                                    <button onclick="toggleContentStatus(<?= $post['id'] ?>, 0)"
                                        class="btn btn-small btn-danger"
                                        style="padding: 4px 8px; font-size: 11px;">إخفاء</button>
                                <?php else: ?>
                                    <button onclick="toggleContentStatus(<?= $post['id'] ?>, 1)"
                                        class="btn btn-small btn-success"
                                        style="padding: 4px 8px; font-size: 11px;">نشر</button>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    </div>
    </div>

    <script>
        function toggleContentStatus(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) {
                        location.reload();
                    } else {
                        alert('حدث خطأ أثناء تغيير الحالة');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('حدث خطأ في الاتصال');
                });
        }
    </script>
</body>

</html>