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

// تم إلغاء تسجيل الدخول - الوصول مفتوح للجميع
// session_start();

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

// المسار الأساسي للملفات - من جذر المشروع
$project_root = realpath(__DIR__ . '/../../..');
$base_path = $project_root; // جلب من جذر المشروع /kkl
$current_path = isset($_GET['path']) ? $_GET['path'] : '';
$full_path = realpath($base_path . '/' . $current_path);

// التحقق من أن المسار آمن
if ($full_path === false || strpos($full_path, $base_path) !== 0) {
    $full_path = $base_path;
    $current_path = '';
}

// مجلدات محظورة للحماية
$blocked_folders = ['.git', '.vscode', 'node_modules', '.env'];

// قراءة محتويات المجلد
$items = [];
if (is_dir($full_path)) {
    $files = scandir($full_path);
    foreach ($files as $file) {
        if ($file === '.' || $file === '..') continue;
        
        // تخطي المجلدات المحظورة
        if (in_array($file, $blocked_folders)) continue;
        
        $file_path = $full_path . '/' . $file;
        $relative_path = $current_path ? $current_path . '/' . $file : $file;
        
        $items[] = [
            'name' => $file,
            'path' => $relative_path,
            'type' => is_dir($file_path) ? 'folder' : 'file',
            'size' => is_file($file_path) ? filesize($file_path) : 0,
            'modified' => filemtime($file_path),
            'extension' => is_file($file_path) ? pathinfo($file, PATHINFO_EXTENSION) : ''
        ];
    }
}

// ترتيب: المجلدات أولاً ثم الملفات
usort($items, function($a, $b) {
    if ($a['type'] === $b['type']) {
        return strcasecmp($a['name'], $b['name']);
    }
    return $a['type'] === 'folder' ? -1 : 1;
});

// حساب الإحصائيات
$total_files = 0;
$total_folders = 0;
$total_size = 0;

function getDirSize($dir) {
    $size = 0;
    if (!is_dir($dir)) return 0;
    
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $size += $file->getSize();
            }
        }
    } catch (Exception $e) {
        // Fallback to old method
        foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $each) {
            $size += is_file($each) ? filesize($each) : getDirSize($each);
        }
    }
    
    return $size;
}

function countDirFiles($dir) {
    $count = 0;
    if (!is_dir($dir)) return 0;
    
    try {
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS)
        );
        
        foreach ($iterator as $file) {
            if ($file->isFile()) {
                $count++;
            }
        }
    } catch (Exception $e) {
        // Fallback
        foreach (glob(rtrim($dir, '/').'/*', GLOB_NOSORT) as $each) {
            $count += is_file($each) ? 1 : countDirFiles($each);
        }
    }
    
    return $count;
}

// حساب الإحصائيات الكلية للمجلد الأساسي
$total_size = getDirSize($base_path);
$total_files = countDirFiles($base_path);

// حساب عدد المجلدات في المسار الحالي فقط
foreach ($items as $item) {
    if ($item['type'] === 'folder') {
        $total_folders++;
    }
}

function formatBytes($bytes, $precision = 2) {
    $units = ['B', 'KB', 'MB', 'GB', 'TB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);
    return round($bytes, $precision) . ' ' . $units[$pow];
}
?>
<!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; }
        .file-item:hover { background: #f3f4f6; transform: translateX(-2px); }
        .file-item { transition: all 0.2s ease; cursor: pointer; }
        .folder-icon { color: #f59e0b; }
        .file-icon { color: #3b82f6; }
        .image-icon { color: #10b981; }
        .video-icon { color: #ef4444; }
        .document-icon { color: #8b5cf6; }
        .archive-icon { color: #6b7280; }
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); }
        .modal.active { display: flex; align-items: center; justify-content: center; }
        .modal-content { background: white; padding: 2rem; border-radius: 1rem; max-width: 500px; width: 90%; box-shadow: 0 20px 60px rgba(0,0,0,0.3); }
        .dropzone { border: 2px dashed #cbd5e1; border-radius: 0.5rem; padding: 2rem; text-align: center; transition: all 0.3s; }
        .dropzone.dragover { border-color: #3b82f6; background: #eff6ff; }
        .progress-bar { height: 4px; background: #e5e7eb; border-radius: 9999px; overflow: hidden; margin-top: 0.5rem; }
        .progress-fill { height: 100%; background: linear-gradient(90deg, #3b82f6, #8b5cf6); transition: width 0.3s; }
        .breadcrumb-item { display: inline-flex; align-items: center; }
        .breadcrumb-item:not(:last-child)::after { content: '/'; margin: 0 0.5rem; color: #9ca3af; }
        
        /* Storage Progress Bar */
        .storage-progress { 
            height: 8px; 
            background: #e5e7eb; 
            border-radius: 9999px; 
            overflow: hidden; 
            margin-top: 0.5rem;
        }
        .storage-progress-fill { 
            height: 100%; 
            background: linear-gradient(90deg, #10b981, #059669); 
            transition: width 0.5s ease;
            border-radius: 9999px;
        }
        .storage-progress-fill.warning { background: linear-gradient(90deg, #f59e0b, #d97706); }
        .storage-progress-fill.danger { background: linear-gradient(90deg, #ef4444, #dc2626); }
        
        /* Action Buttons */
        .action-btn { 
            display: inline-flex; 
            align-items: center; 
            gap: 0.5rem;
            transition: all 0.2s ease;
        }
        .action-btn:hover { transform: translateY(-2px); box-shadow: 0 4px 12px rgba(0,0,0,0.15); }
        
        /* File Preview */
        .file-preview { 
            width: 40px; 
            height: 40px; 
            border-radius: 0.5rem; 
            object-fit: cover;
            border: 2px solid #e5e7eb;
        }
        
        /* Empty State */
        .empty-state {
            padding: 4rem 2rem;
            text-align: center;
        }
        .empty-state i {
            font-size: 4rem;
            color: #d1d5db;
            margin-bottom: 1rem;
        }
        
        /* Loading Spinner */
        .spinner {
            border: 3px solid #f3f4f6;
            border-top: 3px solid #3b82f6;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 2rem auto;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </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">
            <!-- Warning Alert -->
            <div class="bg-yellow-50 border-r-4 border-yellow-400 p-4 mb-6 rounded-lg">
                <div class="flex items-start">
                    <i class="fas fa-exclamation-triangle text-yellow-600 text-xl mt-1 ml-3"></i>
                    <div>
                        <h3 class="text-sm font-bold text-yellow-800 mb-1">⚠️ تحذير أمني</h3>
                        <p class="text-sm text-yellow-700">
                            أنت الآن تتصفح <strong>جذر المشروع الكامل</strong> (<?php echo htmlspecialchars($base_path); ?>).
                            كن حذراً عند حذف أو تعديل الملفات. بعض المجلدات محمية تلقائياً (.git, .vscode, node_modules).
                        </p>
                    </div>
                </div>
            </div>

            <!-- Statistics Cards -->
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition-shadow">
                    <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 number_format($total_files); ?></p>
                            <p class="text-xs text-gray-500 mt-1">في جميع المجلدات</p>
                        </div>
                        <div class="bg-blue-50 p-3 rounded-lg">
                            <i class="fas fa-file text-blue-600 text-2xl"></i>
                        </div>
                    </div>
                </div>

                <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-6 hover:shadow-lg transition-shadow">
                    <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 number_format($total_folders); ?></p>
                            <p class="text-xs text-gray-500 mt-1">في هذا المجلد</p>
                        </div>
                        <div class="bg-yellow-50 p-3 rounded-lg">
                            <i class="fas fa-folder text-yellow-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 mb-3">
                        <div>
                            <p class="text-sm font-medium text-gray-600">المساحة المستخدمة</p>
                            <p class="text-3xl font-bold text-gray-900"><?php echo formatBytes($total_size); ?></p>
                            <?php
                            // حساب النسبة المئوية (افتراض 1GB كحد أقصى)
                            $max_storage = 1024 * 1024 * 1024; // 1GB
                            $storage_percent = min(($total_size / $max_storage) * 100, 100);
                            $storage_class = $storage_percent > 80 ? 'danger' : ($storage_percent > 60 ? 'warning' : '');
                            ?>
                            <p class="text-xs text-gray-500 mt-1">
                                <?php echo number_format($storage_percent, 1); ?>% من 1GB
                            </p>
                        </div>
                        <div class="bg-green-50 p-3 rounded-lg">
                            <i class="fas fa-hdd text-green-600 text-2xl"></i>
                        </div>
                    </div>
                    <div class="storage-progress">
                        <div class="storage-progress-fill <?php echo $storage_class; ?>" 
                             style="width: <?php echo $storage_percent; ?>%"></div>
                    </div>
                </div>
            </div>

            <!-- Action Buttons -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-6">
                <div class="flex items-center justify-between flex-wrap gap-4">
                    <!-- Breadcrumb -->
                    <div class="flex items-center text-sm text-gray-600">
                        <i class="fas fa-folder-open ml-2"></i>
                        <a href="index.php" class="breadcrumb-item hover:text-blue-600">الرئيسية</a>
                        <?php
                        if ($current_path) {
                            $path_parts = explode('/', $current_path);
                            $accumulated_path = '';
                            foreach ($path_parts as $part) {
                                $accumulated_path .= ($accumulated_path ? '/' : '') . $part;
                                echo '<a href="index.php?path=' . urlencode($accumulated_path) . '" class="breadcrumb-item hover:text-blue-600">' . htmlspecialchars($part) . '</a>';
                            }
                        }
                        ?>
                    </div>

                    <!-- Action Buttons -->
                    <div class="flex items-center space-x-3 space-x-reverse flex-wrap gap-2">
                        <a href="index.php" class="action-btn bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition-all">
                            <i class="fas fa-home"></i>
                            <span>الجذر</span>
                        </a>
                        <a href="index.php?path=backend/uploads" class="action-btn bg-teal-600 text-white px-4 py-2 rounded-lg hover:bg-teal-700 transition-all">
                            <i class="fas fa-cloud"></i>
                            <span>مجلد Uploads</span>
                        </a>
                        <button onclick="openUploadModal()" class="action-btn bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-all">
                            <i class="fas fa-upload"></i>
                            <span>رفع ملف</span>
                        </button>
                        <button onclick="openCreateFolderModal()" class="action-btn bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700 transition-all">
                            <i class="fas fa-folder-plus"></i>
                            <span>مجلد جديد</span>
                        </button>
                        <button onclick="downloadFromServer()" class="action-btn bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700 transition-all">
                            <i class="fas fa-cloud-download-alt"></i>
                            <span>جلب من الاستضافة</span>
                        </button>
                        <button onclick="refreshPage()" class="action-btn bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-all">
                            <i class="fas fa-sync-alt"></i>
                            <span>تحديث</span>
                        </button>
                        <button onclick="showServerInfo()" class="action-btn bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-all">
                            <i class="fas fa-server"></i>
                            <span>معلومات الاستضافة</span>
                        </button>
                        <?php if ($current_path): ?>
                        <a href="index.php?path=<?php echo urlencode(dirname($current_path) === '.' ? '' : dirname($current_path)); ?>" 
                           class="action-btn bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-all">
                            <i class="fas fa-arrow-right"></i>
                            <span>رجوع</span>
                        </a>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Files and Folders List -->
            <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
                <div class="overflow-x-auto">
                    <table class="w-full">
                        <thead class="bg-gray-50 border-b border-gray-200">
                            <tr>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الاسم</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">النوع</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الحجم</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">آخر تعديل</th>
                                <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase">الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-200">
                            <?php if (empty($items)): ?>
                            <tr>
                                <td colspan="5" class="px-6 py-12 text-center text-gray-500">
                                    <i class="fas fa-folder-open text-4xl mb-3 text-gray-300"></i>
                                    <p>المجلد فارغ</p>
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($items as $item): ?>
                            <tr class="file-item">
                                <td class="px-6 py-4">
                                    <div class="flex items-center">
                                        <?php if ($item['type'] === 'folder'): ?>
                                        <?php
                                        // أيقونات خاصة للمجلدات المهمة
                                        $folder_icon = 'fa-folder';
                                        $folder_color = 'folder-icon';
                                        
                                        if ($item['name'] === 'backend') {
                                            $folder_icon = 'fa-server';
                                            $folder_color = 'text-purple-600';
                                        } elseif ($item['name'] === 'uploads') {
                                            $folder_icon = 'fa-cloud-upload-alt';
                                            $folder_color = 'text-blue-600';
                                        } elseif ($item['name'] === 'config') {
                                            $folder_icon = 'fa-cog';
                                            $folder_color = 'text-red-600';
                                        } elseif ($item['name'] === 'admin') {
                                            $folder_icon = 'fa-user-shield';
                                            $folder_color = 'text-indigo-600';
                                        } elseif ($item['name'] === 'public') {
                                            $folder_icon = 'fa-globe';
                                            $folder_color = 'text-green-600';
                                        }
                                        ?>
                                        <i class="fas <?php echo $folder_icon; ?> <?php echo $folder_color; ?> text-2xl ml-3"></i>
                                        <a href="index.php?path=<?php echo urlencode($item['path']); ?>" class="font-medium text-gray-900 hover:text-blue-600">
                                            <?php echo htmlspecialchars($item['name']); ?>
                                        </a>
                                        <?php else: ?>
                                        <?php
                                        $ext = strtolower($item['extension']);
                                        $icon_class = 'file-icon';
                                        $icon = 'fa-file';
                                        
                                        if (in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg'])) {
                                            $icon_class = 'image-icon';
                                            $icon = 'fa-file-image';
                                        } elseif (in_array($ext, ['mp4', 'avi', 'mov', 'wmv'])) {
                                            $icon_class = 'video-icon';
                                            $icon = 'fa-file-video';
                                        } elseif (in_array($ext, ['pdf', 'doc', 'docx', 'txt'])) {
                                            $icon_class = 'document-icon';
                                            $icon = 'fa-file-alt';
                                        } elseif (in_array($ext, ['zip', 'rar', '7z'])) {
                                            $icon = 'fa-file-archive';
                                        }
                                        ?>
                                        <i class="fas <?php echo $icon; ?> <?php echo $icon_class; ?> text-2xl ml-3"></i>
                                        <span class="font-medium text-gray-900"><?php echo htmlspecialchars($item['name']); ?></span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?php echo $item['type'] === 'folder' ? 'مجلد' : strtoupper($item['extension']); ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?php echo $item['type'] === 'folder' ? '-' : formatBytes($item['size']); ?>
                                </td>
                                <td class="px-6 py-4 text-sm text-gray-500">
                                    <?php echo date('Y-m-d H:i', $item['modified']); ?>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex items-center space-x-2 space-x-reverse">
                                        <?php if ($item['type'] === 'file'): ?>
                                        <a href="view.php?file=<?php echo urlencode($item['path']); ?>&action=view" target="_blank" 
                                           class="text-blue-600 hover:text-blue-800" title="عرض">
                                            <i class="fas fa-eye"></i>
                                        </a>
                                        <a href="view.php?file=<?php echo urlencode($item['path']); ?>&action=download" 
                                           class="text-green-600 hover:text-green-800" title="تحميل">
                                            <i class="fas fa-download"></i>
                                        </a>
                                        <?php endif; ?>
                                        <button onclick="deleteItem('<?php echo addslashes($item['path']); ?>', '<?php echo $item['type']; ?>')" 
                                                class="text-red-600 hover:text-red-800" title="حذف">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Upload Modal -->
    <div id="uploadModal" class="modal">
        <div class="modal-content">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-bold text-gray-900">رفع ملف جديد</h3>
                <button onclick="closeUploadModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form id="uploadForm" enctype="multipart/form-data">
                <input type="hidden" name="current_path" value="<?php echo htmlspecialchars($current_path); ?>">
                <div class="dropzone" id="dropzone">
                    <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
                    <p class="text-gray-600 mb-2">اسحب الملفات هنا أو انقر للاختيار</p>
                    <input type="file" name="files[]" id="fileInput" multiple class="hidden">
                    <button type="button" onclick="document.getElementById('fileInput').click()" 
                            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 mt-3">
                        اختر ملفات
                    </button>
                </div>
                
                <div id="fileList" class="mt-4 space-y-2"></div>
                
                <div class="flex justify-end space-x-3 space-x-reverse mt-6">
                    <button type="button" onclick="closeUploadModal()" 
                            class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                        إلغاء
                    </button>
                    <button type="submit" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700">
                        رفع الملفات
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Create Folder Modal -->
    <div id="createFolderModal" class="modal">
        <div class="modal-content">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-bold text-gray-900">إنشاء مجلد جديد</h3>
                <button onclick="closeCreateFolderModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form id="createFolderForm">
                <input type="hidden" name="current_path" value="<?php echo htmlspecialchars($current_path); ?>">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">اسم المجلد</label>
                    <input type="text" name="folder_name" required 
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500"
                           placeholder="أدخل اسم المجلد">
                </div>
                
                <div class="flex justify-end space-x-3 space-x-reverse">
                    <button type="button" onclick="closeCreateFolderModal()" 
                            class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                        إلغاء
                    </button>
                    <button type="submit" class="bg-green-600 text-white px-4 py-2 rounded-lg hover:bg-green-700">
                        إنشاء المجلد
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- Download from Server Modal -->
    <div id="downloadServerModal" class="modal">
        <div class="modal-content" style="max-width: 700px;">
            <div class="flex items-center justify-between mb-4">
                <h3 class="text-xl font-bold text-gray-900">
                    <i class="fas fa-cloud-download-alt text-purple-600 ml-2"></i>
                    جلب ملفات من الاستضافة
                </h3>
                <button onclick="closeDownloadServerModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times text-xl"></i>
                </button>
            </div>
            
            <form id="downloadServerForm">
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">رابط الملف على الاستضافة</label>
                    <input type="url" name="server_url" required 
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-purple-500"
                           placeholder="https://example.com/file.zip">
                    <p class="text-xs text-gray-500 mt-1">أدخل رابط الملف المباشر للتحميل</p>
                </div>
                
                <div class="mb-4">
                    <label class="block text-sm font-medium text-gray-700 mb-2">اسم الملف (اختياري)</label>
                    <input type="text" name="file_name" 
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:border-purple-500"
                           placeholder="اترك فارغاً لاستخدام الاسم الأصلي">
                </div>
                
                <div id="downloadProgress" class="hidden mb-4">
                    <div class="flex items-center justify-between mb-2">
                        <span class="text-sm text-gray-600">جاري التحميل...</span>
                        <span class="text-sm font-medium text-purple-600" id="downloadPercent">0%</span>
                    </div>
                    <div class="progress-bar">
                        <div class="progress-fill" id="downloadProgressBar" style="width: 0%"></div>
                    </div>
                </div>
                
                <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mb-4">
                    <div class="flex items-start">
                        <i class="fas fa-info-circle text-blue-600 mt-1 ml-2"></i>
                        <div class="text-sm text-blue-800">
                            <p class="font-medium mb-1">أمثلة للاستخدام:</p>
                            <ul class="list-disc list-inside space-y-1 text-xs">
                                <li>تحميل ملف ZIP من موقع آخر</li>
                                <li>جلب صور من رابط مباشر</li>
                                <li>استيراد ملفات من استضافة أخرى</li>
                            </ul>
                        </div>
                    </div>
                </div>
                
                <div class="flex justify-end space-x-3 space-x-reverse">
                    <button type="button" onclick="closeDownloadServerModal()" 
                            class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50">
                        إلغاء
                    </button>
                    <button type="submit" class="bg-purple-600 text-white px-4 py-2 rounded-lg hover:bg-purple-700">
                        <i class="fas fa-download ml-2"></i>
                        تحميل الملف
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Upload Modal
        function openUploadModal() {
            document.getElementById('uploadModal').classList.add('active');
        }

        function closeUploadModal() {
            document.getElementById('uploadModal').classList.remove('active');
            document.getElementById('uploadForm').reset();
            document.getElementById('fileList').innerHTML = '';
        }

        // Create Folder Modal
        function openCreateFolderModal() {
            document.getElementById('createFolderModal').classList.add('active');
        }

        function closeCreateFolderModal() {
            document.getElementById('createFolderModal').classList.remove('active');
            document.getElementById('createFolderForm').reset();
        }

        // Drag and Drop
        const dropzone = document.getElementById('dropzone');
        const fileInput = document.getElementById('fileInput');

        dropzone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropzone.classList.add('dragover');
        });

        dropzone.addEventListener('dragleave', () => {
            dropzone.classList.remove('dragover');
        });

        dropzone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropzone.classList.remove('dragover');
            fileInput.files = e.dataTransfer.files;
            displayFiles();
        });

        fileInput.addEventListener('change', displayFiles);

        function displayFiles() {
            const fileList = document.getElementById('fileList');
            fileList.innerHTML = '';
            
            Array.from(fileInput.files).forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'flex items-center justify-between p-3 bg-gray-50 rounded-lg';
                fileItem.innerHTML = `
                    <div class="flex items-center">
                        <i class="fas fa-file text-blue-600 ml-2"></i>
                        <span class="text-sm text-gray-700">${file.name}</span>
                    </div>
                    <span class="text-xs text-gray-500">${formatBytes(file.size)}</span>
                `;
                fileList.appendChild(fileItem);
            });
        }

        function formatBytes(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
        }

        // Upload Form Submit
        document.getElementById('uploadForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            
            try {
                const response = await fetch('api.php?action=upload', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('تم رفع الملفات بنجاح');
                    location.reload();
                } else {
                    alert('خطأ: ' + result.message);
                }
            } catch (error) {
                alert('حدث خطأ أثناء رفع الملفات');
            }
        });

        // Create Folder Form Submit
        document.getElementById('createFolderForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            
            try {
                const response = await fetch('api.php?action=create_folder', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('تم إنشاء المجلد بنجاح');
                    location.reload();
                } else {
                    alert('خطأ: ' + result.message);
                }
            } catch (error) {
                alert('حدث خطأ أثناء إنشاء المجلد');
            }
        });

        // Delete Item
        async function deleteItem(path, type) {
            const confirmMsg = type === 'folder' 
                ? 'هل أنت متأكد من حذف هذا المجلد وجميع محتوياته؟' 
                : 'هل أنت متأكد من حذف هذا الملف؟';
            
            if (!confirm(confirmMsg)) return;
            
            try {
                const formData = new FormData();
                formData.append('path', path);
                formData.append('type', type);
                
                const response = await fetch('api.php?action=delete', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (result.success) {
                    alert('تم الحذف بنجاح');
                    location.reload();
                } else {
                    alert('خطأ: ' + result.message);
                }
            } catch (error) {
                alert('حدث خطأ أثناء الحذف');
            }
        }

        // Download from Server Modal
        function downloadFromServer() {
            document.getElementById('downloadServerModal').classList.add('active');
        }

        function closeDownloadServerModal() {
            document.getElementById('downloadServerModal').classList.remove('active');
            document.getElementById('downloadServerForm').reset();
            document.getElementById('downloadProgress').classList.add('hidden');
        }

        // Download from Server Form Submit
        document.getElementById('downloadServerForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            
            const formData = new FormData(e.target);
            const progressDiv = document.getElementById('downloadProgress');
            const progressBar = document.getElementById('downloadProgressBar');
            const progressPercent = document.getElementById('downloadPercent');
            
            progressDiv.classList.remove('hidden');
            progressBar.style.width = '0%';
            progressPercent.textContent = '0%';
            
            try {
                // Simulate progress (in real implementation, you'd use XMLHttpRequest for progress tracking)
                let progress = 0;
                const interval = setInterval(() => {
                    progress += 10;
                    if (progress <= 90) {
                        progressBar.style.width = progress + '%';
                        progressPercent.textContent = progress + '%';
                    }
                }, 200);
                
                const response = await fetch('api.php?action=download_from_server', {
                    method: 'POST',
                    body: formData
                });
                
                clearInterval(interval);
                
                const result = await response.json();
                
                progressBar.style.width = '100%';
                progressPercent.textContent = '100%';
                
                if (result.success) {
                    setTimeout(() => {
                        alert('تم تحميل الملف بنجاح');
                        location.reload();
                    }, 500);
                } else {
                    alert('خطأ: ' + result.message);
                    progressDiv.classList.add('hidden');
                }
            } catch (error) {
                alert('حدث خطأ أثناء التحميل');
                progressDiv.classList.add('hidden');
            }
        });

        // Refresh Page
        function refreshPage() {
            location.reload();
        }

        // Mobile Menu
        function openSidebar() {
            document.getElementById('sidebar').classList.add('active');
            document.getElementById('sidebarOverlay').classList.add('active');
            document.body.style.overflow = 'hidden';
        }

        // Show Server Info
        async function showServerInfo() {
            try {
                const response = await fetch('server-info.php');
                const info = await response.json();
                
                const formatBytes = (bytes) => {
                    if (bytes === 0) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
                };
                
                const diskUsedPercent = ((info.disk_total_space - info.disk_free_space) / info.disk_total_space * 100).toFixed(1);
                
                const message = `
📊 معلومات الاستضافة والمساحة

📁 مساحة الملفات:
   • الحجم الكلي: ${formatBytes(info.total_size)}
   • عدد الملفات: ${info.total_files.toLocaleString()}

💾 مساحة القرص:
   • المساحة الكلية: ${formatBytes(info.disk_total_space)}
   • المساحة المستخدمة: ${formatBytes(info.disk_total_space - info.disk_free_space)} (${diskUsedPercent}%)
   • المساحة المتاحة: ${formatBytes(info.disk_free_space)}

⚙️ إعدادات PHP:
   • حد رفع الملف: ${info.upload_max_filesize}
   • حد POST: ${info.post_max_size}
   • وقت التنفيذ: ${info.max_execution_time} ثانية
   • حد الذاكرة: ${info.memory_limit}
                `;
                
                alert(message);
            } catch (error) {
                alert('حدث خطأ أثناء جلب معلومات الاستضافة');
            }
        }
    </script>
</body>
</html>
