<?php
require_once '../../config/database.php';

$database = new Database();
$db = $database->getConnection();

// المسار الأساسي للمشروع
$project_root = realpath(__DIR__ . '/../../..');
$base_url = 'http://' . $_SERVER['HTTP_HOST'] . dirname(dirname(dirname($_SERVER['SCRIPT_NAME'])));

// بدء الفحص
$scanning = isset($_GET['scan']) && $_GET['scan'] === 'start';

$links = [];
$stats = [
    'total' => 0,
    'working' => 0,
    'broken' => 0,
    'warning' => 0
];

if ($scanning) {
    // فحص ملفات المتجر (public)
    $public_dir = $project_root . '/backend/public';
    $files = glob($public_dir . '/*.php');
    
    foreach ($files as $file) {
        $filename = basename($file);
        $content = file_get_contents($file);
        
        // استخراج جميع الروابط من الملف
        // البحث عن href و action
        preg_match_all('/(href|action)=["\']([^"\']+)["\']/', $content, $matches);
        
        foreach ($matches[2] as $link) {
            // تخطي الروابط الخارجية والـ javascript
            if (strpos($link, 'http') === 0 || 
                strpos($link, 'javascript:') === 0 || 
                strpos($link, '#') === 0 ||
                strpos($link, 'mailto:') === 0 ||
                strpos($link, 'tel:') === 0) {
                continue;
            }
            
            // تنظيف الرابط
            $clean_link = strtok($link, '?'); // إزالة query string
            
            // التحقق من وجود الملف
            $file_path = $public_dir . '/' . $clean_link;
            
            // إذا كان مسار نسبي
            if (strpos($clean_link, '../') === 0) {
                $file_path = realpath($public_dir . '/' . $clean_link);
            }
            
            $status = 'broken';
            $status_text = 'غير موجود';
            
            if (file_exists($file_path)) {
                $status = 'working';
                $status_text = 'يعمل';
            } elseif (strpos($clean_link, 'api/') === 0 || strpos($clean_link, '../api/') === 0) {
                // فحص API
                $api_path = $project_root . '/backend/' . str_replace('../', '', $clean_link);
                if (file_exists($api_path)) {
                    $status = 'working';
                    $status_text = 'يعمل';
                }
            }
            
            // البحث عن نص الزر/الرابط
            $button_text = 'غير معروف';
            if (preg_match('/<[^>]*(href|action)=["\']' . preg_quote($link, '/') . '["\'][^>]*>([^<]+)</', $content, $text_match)) {
                $button_text = trim(strip_tags($text_match[2]));
            }
            
            $links[] = [
                'file' => $filename,
                'link' => $link,
                'text' => $button_text,
                'status' => $status,
                'status_text' => $status_text
            ];
            
            $stats['total']++;
            if ($status === 'working') {
                $stats['working']++;
            } else {
                $stats['broken']++;
            }
        }
    }
    
    // إزالة التكرارات
    $links = array_unique($links, SORT_REGULAR);
    $stats['total'] = count($links);
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>فحص روابط المتجر - Roz Skin</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Tajawal:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="../assets/css/admin-layout.css">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
        
        @keyframes slideInUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.5; }
        }
        
        .slide-in-up {
            animation: slideInUp 0.5s ease-out forwards;
        }
        
        .link-card {
            transition: all 0.3s ease;
            opacity: 0;
            animation: slideInUp 0.5s ease-out forwards;
        }
        
        .link-card:nth-child(1) { animation-delay: 0.05s; }
        .link-card:nth-child(2) { animation-delay: 0.1s; }
        .link-card:nth-child(3) { animation-delay: 0.15s; }
        .link-card:nth-child(4) { animation-delay: 0.2s; }
        .link-card:nth-child(5) { animation-delay: 0.25s; }
        
        .link-card:hover {
            transform: translateX(-5px);
            box-shadow: 0 10px 30px rgba(0,0,0,0.15);
        }
        
        .status-working {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }
        
        .status-broken {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }
        
        .status-warning {
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
        }
        
        .scan-line {
            position: fixed;
            left: 0;
            width: 100%;
            height: 3px;
            background: linear-gradient(90deg, transparent, #3b82f6, transparent);
            animation: scan 2s linear infinite;
            z-index: 9999;
            pointer-events: none;
        }
        
        @keyframes scan {
            0% { transform: translateY(-100%); }
            100% { transform: translateY(100vh); }
        }
    </style>
</head>
<body class="bg-gray-50">
    <?php include '../includes/sidebar.php'; ?>
    
    <div class="main-content">
        <!-- Top Bar -->
        <div class="top-bar">
            <div class="top-bar-left">
                <button class="mobile-menu-btn" onclick="openSidebar()">
                    <i class="fas fa-bars"></i>
                </button>
                <div>
                    <h1 class="page-title">🔗 فحص روابط المتجر</h1>
                    <p class="text-sm text-gray-500">فحص جميع الأزرار والروابط في المتجر</p>
                </div>
            </div>
            
            <div class="top-bar-right">
                <a href="../dashboard.php" class="text-gray-600 hover:text-gray-900">
                    <i class="fas fa-home text-xl"></i>
                </a>
            </div>
        </div>

        <div class="content-container">
            <?php if (!$scanning): ?>
            <!-- Start Screen -->
            <div class="max-w-4xl mx-auto">
                <div class="bg-gradient-to-br from-blue-600 to-purple-600 rounded-2xl shadow-2xl p-8 mb-8 text-white slide-in-up">
                    <div class="flex items-center justify-between">
                        <div>
                            <h2 class="text-3xl font-bold mb-3">🔍 جاهز لفحص الروابط؟</h2>
                            <p class="text-blue-100 mb-6">سنقوم بفحص جميع الأزرار والروابط في صفحات المتجر</p>
                            <a href="?scan=start" class="inline-flex items-center bg-white text-blue-600 px-8 py-4 rounded-xl font-bold hover:bg-blue-50 transition-all transform hover:scale-105">
                                <i class="fas fa-play-circle text-2xl ml-3"></i>
                                <span class="text-lg">ابدأ الفحص</span>
                            </a>
                        </div>
                        <div class="hidden md:block">
                            <i class="fas fa-link text-9xl opacity-20"></i>
                        </div>
                    </div>
                </div>

                <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition-all slide-in-up" style="animation-delay: 0.1s;">
                        <div class="bg-green-50 w-14 h-14 rounded-xl flex items-center justify-center mb-4">
                            <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                        </div>
                        <h3 class="font-bold text-gray-900 mb-2">روابط شغالة</h3>
                        <p class="text-sm text-gray-600">الروابط اللي تعمل بشكل صحيح</p>
                    </div>

                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition-all slide-in-up" style="animation-delay: 0.2s;">
                        <div class="bg-red-50 w-14 h-14 rounded-xl flex items-center justify-center mb-4">
                            <i class="fas fa-times-circle text-red-600 text-2xl"></i>
                        </div>
                        <h3 class="font-bold text-gray-900 mb-2">روابط مكسورة</h3>
                        <p class="text-sm text-gray-600">الروابط اللي مش شغالة</p>
                    </div>

                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition-all slide-in-up" style="animation-delay: 0.3s;">
                        <div class="bg-blue-50 w-14 h-14 rounded-xl flex items-center justify-center mb-4">
                            <i class="fas fa-chart-bar text-blue-600 text-2xl"></i>
                        </div>
                        <h3 class="font-bold text-gray-900 mb-2">إحصائيات</h3>
                        <p class="text-sm text-gray-600">تقرير شامل عن الروابط</p>
                    </div>
                </div>
            </div>

            <?php else: ?>
            <!-- Scanning Animation -->
            <div class="scan-line"></div>

            <!-- Results -->
            <div class="max-w-6xl mx-auto">
                <!-- Stats Cards -->
                <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-600">إجمالي الروابط</p>
                                <p class="text-3xl font-bold text-gray-900"><?php echo $stats['total']; ?></p>
                            </div>
                            <div class="bg-blue-50 p-3 rounded-lg">
                                <i class="fas fa-link text-blue-600 text-2xl"></i>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-600">روابط شغالة</p>
                                <p class="text-3xl font-bold text-green-600"><?php echo $stats['working']; ?></p>
                            </div>
                            <div class="bg-green-50 p-3 rounded-lg">
                                <i class="fas fa-check-circle text-green-600 text-2xl"></i>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6">
                        <div class="flex items-center justify-between">
                            <div>
                                <p class="text-sm font-medium text-gray-600">روابط مكسورة</p>
                                <p class="text-3xl font-bold text-red-600"><?php echo $stats['broken']; ?></p>
                            </div>
                            <div class="bg-red-50 p-3 rounded-lg">
                                <i class="fas fa-times-circle text-red-600 text-2xl"></i>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Links Board -->
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 mb-8">
                    <h3 class="text-xl font-bold text-gray-900 mb-6">
                        <i class="fas fa-list-ul text-blue-600 ml-2"></i>
                        جميع الروابط
                    </h3>

                    <div class="space-y-3">
                        <?php foreach ($links as $link): ?>
                        <div class="link-card flex items-center justify-between p-4 rounded-lg border-r-4 <?php echo $link['status'] === 'working' ? 'border-green-500 bg-green-50' : 'border-red-500 bg-red-50'; ?>">
                            <div class="flex items-center flex-1">
                                <div class="w-12 h-12 rounded-lg flex items-center justify-center status-<?php echo $link['status']; ?> text-white ml-4">
                                    <i class="fas <?php echo $link['status'] === 'working' ? 'fa-check' : 'fa-times'; ?> text-xl"></i>
                                </div>
                                <div class="flex-1">
                                    <div class="flex items-center mb-1">
                                        <span class="font-bold text-gray-900"><?php echo htmlspecialchars($link['text']); ?></span>
                                        <span class="text-xs text-gray-500 mr-2">في <?php echo $link['file']; ?></span>
                                    </div>
                                    <code class="text-xs text-gray-600 bg-white px-2 py-1 rounded"><?php echo htmlspecialchars($link['link']); ?></code>
                                </div>
                            </div>
                            <div class="text-left">
                                <span class="px-3 py-1 rounded-full text-xs font-bold <?php echo $link['status'] === 'working' ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                                    <?php echo $link['status_text']; ?>
                                </span>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Actions -->
                <div class="flex items-center justify-center space-x-4 space-x-reverse">
                    <a href="links-checker.php" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition-all">
                        <i class="fas fa-redo ml-2"></i>
                        إعادة الفحص
                    </a>
                    <a href="../dashboard.php" class="bg-gray-600 text-white px-6 py-3 rounded-lg hover:bg-gray-700 transition-all">
                        <i class="fas fa-home ml-2"></i>
                        العودة للرئيسية
                    </a>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>

    <script>
        function openSidebar() {
            document.getElementById('sidebar').classList.add('active');
            document.getElementById('sidebarOverlay').classList.add('active');
            document.body.style.overflow = 'hidden';
        }
    </script>
</body>
</html>
