<?php
/**
 * أداة تحليل ملفات DEX واستخراج معلومات الكلاسات
 * @author DEX Analyzer Tool
 * @version 6.0
 */

// إعدادات الأداة
define('UPLOAD_DIR', 'uploads/');
define('MAX_FILE_SIZE', 50 * 1024 * 1024); // 50 ميجابايت

// إنشاء مجلد الرفع إذا لم يكن موجوداً
if (!is_dir(UPLOAD_DIR)) {
    mkdir(UPLOAD_DIR, 0777, true);
}

class DexAnalyzer {
    private $dexFile;
    private $outputFile;
    private $targetPath;
    private $extractedContent = [];
    private $fileCounter = 0;
    private $uploadedFileName;
    private $dexContent;
    private $classData = [];
    private $stringTable = [];

    public function __construct($dexFile, $outputFile = null) {
        $this->dexFile = $dexFile;
        $this->outputFile = $outputFile ?? 'dex_analysis_' . time() . '.txt';
        $this->targetPath = 'com/elmostadiratv/app/';
        $this->uploadedFileName = basename($dexFile);
    }

    /**
     * التحقق من وجود ملف DEX
     */
    private function validateDexFile() {
        if (!file_exists($this->dexFile)) {
            throw new Exception("❌ ملف DEX غير موجود: " . $this->dexFile);
        }

        $extension = strtolower(pathinfo($this->dexFile, PATHINFO_EXTENSION));
        if (!in_array($extension, ['dex', 'apk'])) {
            throw new Exception("⚠️ الملف يجب أن يكون بصيغة DEX أو APK");
        }

        return true;
    }

    /**
     * تحليل ملف DEX
     */
    public function analyze() {
        try {
            $this->validateDexFile();
            
            $result = [
                'success' => true,
                'message' => '',
                'files' => [],
                'total_files' => 0,
                'output_file' => $this->outputFile
            ];
            
            // قراءة محتوى الملف
            $this->dexContent = file_get_contents($this->dexFile);
            $dexSize = filesize($this->dexFile);
            
            $result['message'] .= "📂 تحليل الملف: " . $this->uploadedFileName . "\n";
            $result['message'] .= "📊 حجم الملف: " . number_format($dexSize) . " بايت\n";
            $result['message'] .= "🎯 المسار المستهدف: " . $this->targetPath . "\n";
            $result['message'] .= "─────────────────────────────────────\n";
            
            // استخراج جميع المعلومات
            $this->extractClassInfo();
            
            // تجميع النتائج
            $this->compileResults();
            
            $result['files'] = $this->extractedContent;
            $result['total_files'] = $this->fileCounter;
            $result['message'] .= "✅ اكتمل التحليل بنجاح!\n";
            $result['message'] .= "📁 الملف الناتج: " . $this->outputFile . "\n";
            $result['message'] .= "📄 عدد الكلاسات المستخرجة: " . $this->fileCounter . "\n";
            
            return $result;
            
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => "❌ خطأ: " . $e->getMessage(),
                'files' => [],
                'total_files' => 0,
                'output_file' => $this->outputFile
            ];
        }
    }

    /**
     * استخراج معلومات الكلاسات
     */
    private function extractClassInfo() {
        // 1. استخراج أسماء الكلاسات من جدول السلاسل
        $this->extractStrings();
        
        // 2. استخراج الكلاسات من المسار المطلوب
        $this->extractClassesFromPath();
        
        // 3. إذا لم يتم العثور على شيء، جرب طريقة أخرى
        if ($this->fileCounter == 0) {
            $this->extractAllClasses();
        }
    }

    /**
     * استخراج جدول السلاسل
     */
    private function extractStrings() {
        // البحث عن جميع السلاسل في ملف DEX
        $pattern = '/[a-zA-Z0-9_\/\$]+/';
        preg_match_all($pattern, $this->dexContent, $matches);
        
        if (!empty($matches[0])) {
            foreach ($matches[0] as $string) {
                // تخزين السلاسل الفريدة
                if (strlen($string) > 3) {
                    $this->stringTable[$string] = true;
                }
            }
        }
    }

    /**
     * استخراج الكلاسات من المسار المطلوب
     */
    private function extractClassesFromPath() {
        // البحث عن الكلاسات في المسار المطلوب
        $pattern = '/' . preg_quote($this->targetPath, '/') . '[a-zA-Z0-9_\$]+/';
        preg_match_all($pattern, $this->dexContent, $matches);
        
        if (!empty($matches[0])) {
            $uniqueClasses = array_unique($matches[0]);
            
            foreach ($uniqueClasses as $classPath) {
                $className = basename($classPath);
                $package = dirname($classPath);
                
                // استخراج معلومات الكلاس
                $classInfo = $this->extractClassDetails($classPath);
                
                if ($classInfo) {
                    $this->extractedContent[] = [
                        'path' => $classPath,
                        'name' => $className,
                        'package' => $package,
                        'content' => $classInfo,
                        'size' => strlen($classInfo)
                    ];
                    $this->fileCounter++;
                }
            }
        }
    }

    /**
     * استخراج تفاصيل الكلاس
     */
    private function extractClassDetails($classPath) {
        $details = [];
        $escapedPath = preg_quote($classPath, '/');
        
        // 1. البحث عن الكلاس في الملف
        $pos = strpos($this->dexContent, $classPath);
        if ($pos === false) {
            return null;
        }
        
        // 2. استخراج المعلومات حول الكلاس
        $context = substr($this->dexContent, max(0, $pos - 500), 1500);
        
        // البحث عن superclass
        if (preg_match('/super\s+([a-zA-Z0-9_\/\$]+)/', $context, $match)) {
            $details[] = ".super " . $match[1];
        }
        
        // البحث عن interfaces
        if (preg_match_all('/implements\s+([a-zA-Z0-9_\/\$]+)/', $context, $matches)) {
            foreach ($matches[1] as $interface) {
                $details[] = ".implements " . $interface;
            }
        }
        
        // البحث عن annotations
        if (preg_match_all('/@([a-zA-Z0-9_]+)/', $context, $matches)) {
            foreach ($matches[1] as $annotation) {
                $details[] = "@" . $annotation;
            }
        }
        
        // 3. استخراج الـ methods
        $methods = $this->extractMethods($classPath);
        if (!empty($methods)) {
            $details[] = "";
            $details[] = "# methods:";
            foreach ($methods as $method) {
                $details[] = "  " . $method;
            }
        }
        
        // 4. استخراج الـ fields
        $fields = $this->extractFields($classPath);
        if (!empty($fields)) {
            $details[] = "";
            $details[] = "# fields:";
            foreach ($fields as $field) {
                $details[] = "  " . $field;
            }
        }
        
        // 5. استخراج المعلومات الإضافية
        $extraInfo = $this->extractExtraInfo($classPath);
        if (!empty($extraInfo)) {
            $details[] = "";
            $details[] = "# additional info:";
            foreach ($extraInfo as $info) {
                $details[] = "  " . $info;
            }
        }
        
        if (empty($details)) {
            // إذا لم يتم العثور على معلومات، عرض النص المحيط
            $surrounding = substr($this->dexContent, max(0, $pos - 100), 300);
            $surrounding = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $surrounding);
            return "Information extracted from DEX:\n" . $surrounding;
        }
        
        return implode("\n", $details);
    }

    /**
     * استخراج الـ methods
     */
    private function extractMethods($classPath) {
        $methods = [];
        $escapedPath = preg_quote($classPath, '/');
        
        // البحث عن الـ methods في السياق
        $pattern = '/' . $escapedPath . '[^}]*?([a-zA-Z0-9_]+)\s*\([^)]*\)/';
        preg_match_all($pattern, $this->dexContent, $matches);
        
        if (!empty($matches[1])) {
            $uniqueMethods = array_unique($matches[1]);
            foreach ($uniqueMethods as $method) {
                if (!in_array($method, ['<init>', '<clinit>'])) {
                    $methods[] = $method . "()";
                }
            }
        }
        
        // طريقة بديلة للبحث عن الـ methods
        $pattern2 = '/method\s+([a-zA-Z0-9_]+)/';
        preg_match_all($pattern2, $this->dexContent, $matches2);
        
        if (!empty($matches2[1])) {
            foreach ($matches2[1] as $method) {
                if (!in_array($method, ['<init>', '<clinit>']) && !in_array($method . "()", $methods)) {
                    $methods[] = $method . "()";
                }
            }
        }
        
        return array_slice($methods, 0, 20); // حد أقصى 20 method
    }

    /**
     * استخراج الـ fields
     */
    private function extractFields($classPath) {
        $fields = [];
        $escapedPath = preg_quote($classPath, '/');
        
        // البحث عن الـ fields
        $pattern = '/field\s+([a-zA-Z0-9_]+)/';
        preg_match_all($pattern, $this->dexContent, $matches);
        
        if (!empty($matches[1])) {
            $uniqueFields = array_unique($matches[1]);
            foreach ($uniqueFields as $field) {
                $fields[] = $field;
            }
        }
        
        return array_slice($fields, 0, 10); // حد أقصى 10 fields
    }

    /**
     * استخراج معلومات إضافية
     */
    private function extractExtraInfo($classPath) {
        $info = [];
        $escapedPath = preg_quote($classPath, '/');
        
        // البحث عن الكلاسات المستخدمة
        $pattern = '/L([a-zA-Z0-9_\/\$]+);/';
        preg_match_all($pattern, $this->dexContent, $matches);
        
        if (!empty($matches[1])) {
            $uniqueClasses = array_unique($matches[1]);
            $relatedClasses = [];
            
            foreach ($uniqueClasses as $class) {
                if (strpos($class, 'elmostadiratv') !== false && $class != $classPath) {
                    $relatedClasses[] = $class;
                }
            }
            
            if (!empty($relatedClasses)) {
                $info[] = "Related classes:";
                foreach (array_slice($relatedClasses, 0, 10) as $class) {
                    $info[] = "  - " . $class;
                }
            }
        }
        
        return $info;
    }

    /**
     * استخراج جميع الكلاسات (طريقة بديلة)
     */
    private function extractAllClasses() {
        // البحث عن جميع السلاسل التي تشبه أسماء الكلاسات
        $pattern = '/[a-zA-Z0-9_]+\/[a-zA-Z0-9_\/]+/';
        preg_match_all($pattern, $this->dexContent, $matches);
        
        if (!empty($matches[0])) {
            $uniquePaths = array_unique($matches[0]);
            $filteredPaths = [];
            
            foreach ($uniquePaths as $path) {
                if (strpos($path, 'elmostadiratv') !== false) {
                    $filteredPaths[] = $path;
                }
            }
            
            foreach ($filteredPaths as $path) {
                $className = basename($path);
                $package = dirname($path);
                
                // استخراج المعلومات المتاحة
                $info = $this->extractClassDetailsSimple($path);
                
                if ($info) {
                    $this->extractedContent[] = [
                        'path' => $path,
                        'name' => $className,
                        'package' => $package,
                        'content' => $info,
                        'size' => strlen($info)
                    ];
                    $this->fileCounter++;
                }
            }
        }
    }

    /**
     * استخراج تفاصيل الكلاس بطريقة بسيطة
     */
    private function extractClassDetailsSimple($path) {
        $details = [];
        
        // البحث عن الكلاس في الملف
        $pos = strpos($this->dexContent, $path);
        if ($pos === false) {
            return null;
        }
        
        // استخراج النص المحيط
        $start = max(0, $pos - 200);
        $end = min(strlen($this->dexContent), $pos + 500);
        $context = substr($this->dexContent, $start, $end - $start);
        
        // تنظيف النص
        $context = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $context);
        $context = trim($context);
        
        if (strlen($context) > 0) {
            $details[] = "📄 Class: " . $path;
            $details[] = "─────────────────────────────────────";
            $details[] = "📝 Context around class:";
            $details[] = $context;
            
            // محاولة استخراج بعض المعلومات الإضافية
            if (preg_match('/super\s+([a-zA-Z0-9_\/]+)/', $context, $match)) {
                $details[] = "Superclass: " . $match[1];
            }
            
            if (preg_match_all('/method\s+([a-zA-Z0-9_]+)/', $context, $matches)) {
                if (!empty($matches[1])) {
                    $details[] = "Methods found: " . implode(", ", array_slice(array_unique($matches[1]), 0, 10));
                }
            }
            
            return implode("\n", $details);
        }
        
        return null;
    }

    /**
     * تجميع النتائج في ملف واحد
     */
    private function compileResults() {
        if (empty($this->extractedContent)) {
            $this->writeEmptyResult();
            return;
        }

        $output = "════════════════════════════════════════════════════════\n";
        $output .= "📄 تقرير تحليل ملف DEX\n";
        $output .= "📂 الملف الأصلي: " . $this->uploadedFileName . "\n";
        $output .= "🎯 المسار المستهدف: " . $this->targetPath . "\n";
        $output .= "📅 تاريخ التحليل: " . date('Y-m-d H:i:s') . "\n";
        $output .= "📄 عدد الكلاسات: " . $this->fileCounter . "\n";
        $output .= "════════════════════════════════════════════════════════\n\n";

        $counter = 1;
        foreach ($this->extractedContent as $item) {
            $output .= "─────────────────────────────────────────────────────\n";
            $output .= "📄 الكلاس #" . $counter . "\n";
            $output .= "📁 المسار: " . $item['path'] . "\n";
            $output .= "📝 اسم الكلاس: " . $item['name'] . "\n";
            $output .= "📦 الحزمة: " . ($item['package'] ?? 'N/A') . "\n";
            $output .= "📏 حجم المحتوى: " . number_format($item['size']) . " حرف\n";
            $output .= "─────────────────────────────────────────────────────\n";
            $output .= $item['content'] . "\n";
            $output .= "\n" . str_repeat("─", 50) . "\n\n";
            $counter++;
        }

        // إضافة ملخص في النهاية
        $output .= "\n════════════════════════════════════════════════════════\n";
        $output .= "📊 ملخص التحليل\n";
        $output .= "─────────────────────────────────────────────────────\n";
        $output .= "📄 إجمالي الكلاسات المستخرجة: " . $this->fileCounter . "\n";
        $output .= "📁 المسار المستهدف: " . $this->targetPath . "\n";
        $output .= "════════════════════════════════════════════════════════\n";

        file_put_contents($this->outputFile, $output);
    }

    /**
     * كتابة نتيجة فارغة مع معلومات مفيدة
     */
    private function writeEmptyResult() {
        $output = "════════════════════════════════════════════════════════\n";
        $output .= "📄 تقرير تحليل ملف DEX\n";
        $output .= "📂 الملف الأصلي: " . $this->uploadedFileName . "\n";
        $output .= "🎯 المسار المستهدف: " . $this->targetPath . "\n";
        $output .= "📅 تاريخ التحليل: " . date('Y-m-d H:i:s') . "\n";
        $output .= "─────────────────────────────────────────────────────\n";
        $output .= "⚠️ لم يتم العثور على كلاسات في المسار المطلوب\n\n";
        
        // عرض بعض المعلومات عن الملف
        $output .= "📊 معلومات عن الملف:\n";
        $output .= "─────────────────────────────────────────────────────\n";
        
        // البحث عن أي كلاسات تحتوي على elmostadiratv
        $pattern = '/elmostadiratv[a-zA-Z0-9_\/]+/';
        preg_match_all($pattern, $this->dexContent, $matches);
        
        if (!empty($matches[0])) {
            $unique = array_unique($matches[0]);
            $output .= "🔍 تم العثور على " . count($unique) . " مرجع لـ 'elmostadiratv':\n";
            foreach (array_slice($unique, 0, 20) as $ref) {
                $output .= "  - " . $ref . "\n";
            }
            if (count($unique) > 20) {
                $output .= "  ... و " . (count($unique) - 20) . " مرجع آخر\n";
            }
        } else {
            $output .= "❌ لم يتم العثور على أي مرجع لـ 'elmostadiratv'\n";
            
            // عرض بعض الكلاسات الأخرى الموجودة
            $pattern2 = '/[a-zA-Z0-9_]+\/[a-zA-Z0-9_\/]+/';
            preg_match_all($pattern2, $this->dexContent, $matches2);
            if (!empty($matches2[0])) {
                $unique2 = array_unique($matches2[0]);
                $output .= "\n📂 بعض الكلاسات الموجودة في الملف:\n";
                foreach (array_slice($unique2, 0, 10) as $class) {
                    $output .= "  - " . $class . "\n";
                }
            }
        }
        
        $output .= "════════════════════════════════════════════════════════\n";
        
        file_put_contents($this->outputFile, $output);
    }

    /**
     * الحصول على إحصائيات التحليل
     */
    public function getStatistics() {
        return [
            'total_files' => $this->fileCounter,
            'output_file' => $this->outputFile,
            'target_path' => $this->targetPath,
            'source_file' => $this->uploadedFileName
        ];
    }
}

// ──────────────────────────────────────────────────────────────
// معالجة رفع الملفات
// ──────────────────────────────────────────────────────────────

$uploadMessage = '';
$analysisResult = null;
$downloadedFile = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['dex_file'])) {
    $file = $_FILES['dex_file'];
    
    if ($file['error'] !== UPLOAD_ERR_OK) {
        $uploadMessage = '❌ حدث خطأ في رفع الملف: ' . $file['error'];
    } elseif ($file['size'] > MAX_FILE_SIZE) {
        $uploadMessage = '❌ حجم الملف كبير جداً. الحد الأقصى هو 50 ميجابايت';
    } else {
        $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if (!in_array($extension, ['dex', 'apk'])) {
            $uploadMessage = '❌ الملف يجب أن يكون بصيغة DEX أو APK';
        } else {
            $filename = time() . '_' . basename($file['name']);
            $uploadPath = UPLOAD_DIR . $filename;
            
            if (move_uploaded_file($file['tmp_name'], $uploadPath)) {
                $uploadMessage = '✅ تم رفع الملف بنجاح!';
                
                $analyzer = new DexAnalyzer($uploadPath);
                $analysisResult = $analyzer->analyze();
                $downloadedFile = $analysisResult['output_file'] ?? '';
                
            } else {
                $uploadMessage = '❌ فشل في نقل الملف إلى المجلد المؤقت';
            }
        }
    }
}
?>

<!-- HTML Interface -->
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>أداة تحليل ملفات DEX</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;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        
        .container {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            padding: 40px;
            max-width: 1000px;
            width: 100%;
            animation: slideIn 0.5s ease;
        }
        
        @keyframes slideIn {
            from { opacity: 0; transform: translateY(-30px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .header { text-align: center; margin-bottom: 30px; }
        .header h1 { font-size: 28px; color: #2d3748; margin-bottom: 10px; }
        .header .subtitle { color: #718096; font-size: 16px; }
        
        .upload-area {
            border: 3px dashed #cbd5e0;
            border-radius: 15px;
            padding: 40px;
            text-align: center;
            transition: all 0.3s ease;
            background: #f7fafc;
            cursor: pointer;
        }
        
        .upload-area:hover { border-color: #667eea; background: #edf2f7; }
        .upload-area.dragover { border-color: #667eea; background: #e2e8f0; transform: scale(1.02); }
        .upload-icon { font-size: 60px; color: #667eea; margin-bottom: 15px; }
        .upload-text { font-size: 18px; color: #2d3748; margin-bottom: 10px; }
        .upload-hint { font-size: 14px; color: #a0aec0; }
        #fileInput { display: none; }
        
        .upload-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 10px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 15px;
            display: inline-block;
        }
        
        .upload-btn:hover { transform: translateY(-2px); box-shadow: 0 10px 20px rgba(102, 126, 234, 0.3); }
        .upload-btn:disabled { opacity: 0.6; cursor: not-allowed; }
        
        .message {
            padding: 15px;
            border-radius: 10px;
            margin-top: 20px;
            display: none;
            font-weight: 500;
        }
        
        .message.success { display: block; background: #f0fff4; border: 1px solid #48bb78; color: #22543d; }
        .message.error { display: block; background: #fff5f5; border: 1px solid #fc8181; color: #742a2a; }
        .message.info { display: block; background: #ebf8ff; border: 1px solid #63b3ed; color: #2a4365; }
        
        .results { margin-top: 30px; display: none; }
        .results.show { display: block; animation: slideIn 0.5s ease; }
        
        .results-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 15px 15px 0 0;
        }
        
        .results-header h2 { font-size: 20px; margin-bottom: 5px; }
        
        .results-body {
            background: #f7fafc;
            border-radius: 0 0 15px 15px;
            padding: 20px;
            max-height: 600px;
            overflow-y: auto;
        }
        
        .file-item {
            background: white;
            margin-bottom: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            overflow: hidden;
        }
        
        .file-header {
            padding: 15px 20px;
            background: #f7fafc;
            border-bottom: 2px solid #edf2f7;
            display: flex;
            justify-content: space-between;
            align-items: center;
            cursor: pointer;
        }
        
        .file-header:hover { background: #edf2f7; }
        .file-info { flex: 1; }
        .file-info .name { font-weight: 600; color: #2d3748; font-size: 16px; }
        .file-info .path { font-size: 12px; color: #a0aec0; margin-top: 3px; }
        
        .file-meta { display: flex; align-items: center; gap: 15px; }
        .file-meta .badge { background: #667eea; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; }
        .file-meta .size-badge { background: #48bb78; color: white; padding: 4px 12px; border-radius: 20px; font-size: 12px; }
        
        .toggle-btn {
            background: none;
            border: none;
            color: #667eea;
            font-size: 20px;
            cursor: pointer;
            padding: 5px 10px;
            transition: transform 0.3s ease;
        }
        
        .toggle-btn.expanded { transform: rotate(180deg); }
        
        .file-content {
            max-height: 0;
            overflow: hidden;
            transition: max-height 0.5s ease, padding 0.3s ease;
            background: #2d3748;
        }
        
        .file-content.open { max-height: 800px; padding: 20px; }
        
        .file-content pre {
            color: #e2e8f0;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            line-height: 1.6;
            white-space: pre-wrap;
            word-wrap: break-word;
            margin: 0;
            padding: 15px;
            background: #1a202c;
            border-radius: 8px;
            overflow-x: auto;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        
        .stat-box {
            background: white;
            padding: 15px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .stat-box .number { font-size: 24px; font-weight: bold; color: #667eea; }
        .stat-box .label { font-size: 12px; color: #a0aec0; margin-top: 5px; }
        
        .download-btn {
            display: inline-block;
            background: #48bb78;
            color: white;
            padding: 12px 25px;
            border-radius: 10px;
            text-decoration: none;
            margin-top: 15px;
            transition: all 0.3s ease;
        }
        
        .download-btn:hover { background: #38a169; transform: translateY(-2px); box-shadow: 0 10px 20px rgba(72, 187, 120, 0.3); }
        
        .loading { display: none; text-align: center; padding: 20px; }
        .loading.show { 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;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .file-name-display {
            margin-top: 10px;
            padding: 10px;
            background: #edf2f7;
            border-radius: 8px;
            display: none;
        }
        
        .file-name-display.show { display: block; }
        
        .search-box {
            margin-bottom: 20px;
            padding: 10px 15px;
            border: 2px solid #e2e8f0;
            border-radius: 10px;
            width: 100%;
            font-size: 14px;
        }
        
        .search-box:focus { outline: none; border-color: #667eea; }
        
        @media (max-width: 600px) {
            .container { padding: 20px; }
            .header h1 { font-size: 22px; }
            .upload-area { padding: 20px; }
            .file-header { flex-wrap: wrap; }
            .file-meta { flex-wrap: wrap; gap: 8px; }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔍 أداة تحليل ملفات DEX</h1>
            <p class="subtitle">ارفع ملف DEX أو APK لاستخراج معلومات الكلاسات من مسار com/elmostadiratv/app/</p>
        </div>
        
        <form id="uploadForm" method="POST" enctype="multipart/form-data">
            <div class="upload-area" id="dropArea">
                <div class="upload-icon">📁</div>
                <div class="upload-text">اسحب الملف هنا أو اضغط للاختيار</div>
                <div class="upload-hint">الملفات المدعومة: DEX, APK (الحد الأقصى: 50 ميجابايت)</div>
                <input type="file" name="dex_file" id="fileInput" accept=".dex,.apk">
                <button type="button" class="upload-btn" onclick="document.getElementById('fileInput').click()">اختيار ملف</button>
                <div class="file-name-display" id="fileNameDisplay"></div>
            </div>
            
            <div style="text-align: center; margin-top: 20px;">
                <button type="submit" class="upload-btn" id="submitBtn" style="background: linear-gradient(135deg, #48bb78 0%, #38a169 100%); padding: 15px 50px; font-size: 18px;">
                    🚀 تحليل الملف
                </button>
            </div>
        </form>
        
        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p style="margin-top: 15px; color: #4a5568;">جاري تحليل الملف...</p>
        </div>
        
        <div class="message" id="message"></div>
        
        <div class="results" id="results">
            <div class="results-header">
                <h2>📊 نتائج التحليل</h2>
                <p id="resultSummary" style="font-size: 14px; opacity: 0.9;"></p>
            </div>
            <div class="results-body" id="resultsBody"></div>
            
            <div class="stats" id="statsContainer"></div>
            
            <div style="text-align: center; margin-top: 20px;">
                <a href="#" class="download-btn" id="downloadBtn" style="display: none;">📥 تحميل ملف النتائج</a>
            </div>
        </div>
    </div>
    
    <script>
        const dropArea = document.getElementById('dropArea');
        const fileInput = document.getElementById('fileInput');
        const fileNameDisplay = document.getElementById('fileNameDisplay');
        const submitBtn = document.getElementById('submitBtn');
        const loading = document.getElementById('loading');
        const message = document.getElementById('message');
        const results = document.getElementById('results');
        const resultsBody = document.getElementById('resultsBody');
        const statsContainer = document.getElementById('statsContainer');
        const downloadBtn = document.getElementById('downloadBtn');
        const resultSummary = document.getElementById('resultSummary');
        
        fileInput.addEventListener('change', function() {
            if (this.files.length > 0) {
                const file = this.files[0];
                fileNameDisplay.textContent = '📄 ' + file.name + ' (' + (file.size / 1024 / 1024).toFixed(2) + ' MB)';
                fileNameDisplay.classList.add('show');
                showMessage('info', '✅ تم اختيار الملف: ' + file.name);
            }
        });
        
        dropArea.addEventListener('dragover', function(e) {
            e.preventDefault();
            this.classList.add('dragover');
        });
        
        dropArea.addEventListener('dragleave', function(e) {
            e.preventDefault();
            this.classList.remove('dragover');
        });
        
        dropArea.addEventListener('drop', function(e) {
            e.preventDefault();
            this.classList.remove('dragover');
            if (e.dataTransfer.files.length > 0) {
                fileInput.files = e.dataTransfer.files;
                fileInput.dispatchEvent(new Event('change'));
            }
        });
        
        dropArea.addEventListener('click', function() {
            fileInput.click();
        });
        
        function toggleContent(fileId) {
            const content = document.getElementById('content-' + fileId);
            const btn = document.getElementById('toggle-' + fileId);
            if (content.classList.contains('open')) {
                content.classList.remove('open');
                btn.classList.remove('expanded');
                btn.textContent = '▼';
            } else {
                content.classList.add('open');
                btn.classList.add('expanded');
                btn.textContent = '▲';
            }
        }
        
        function searchFiles() {
            const query = document.getElementById('searchBox').value.toLowerCase();
            document.querySelectorAll('.file-item').forEach(item => {
                const name = item.querySelector('.name').textContent.toLowerCase();
                const path = item.querySelector('.path').textContent.toLowerCase();
                item.style.display = (name.includes(query) || path.includes(query)) ? 'block' : 'none';
            });
        }
        
        document.getElementById('uploadForm').addEventListener('submit', function(e) {
            e.preventDefault();
            if (fileInput.files.length === 0) {
                showMessage('error', '❌ الرجاء اختيار ملف أولاً');
                return;
            }
            
            loading.classList.add('show');
            submitBtn.disabled = true;
            message.className = 'message';
            message.style.display = 'none';
            results.classList.remove('show');
            
            const formData = new FormData(this);
            fetch(window.location.href, { method: 'POST', body: formData })
            .then(response => response.text())
            .then(html => {
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                
                const msgElement = doc.querySelector('#message');
                if (msgElement) {
                    const msgText = msgElement.textContent || '';
                    if (msgText.includes('✅')) showMessage('success', msgText);
                    else if (msgText.includes('❌')) showMessage('error', msgText);
                    else showMessage('info', msgText);
                }
                
                const resultsElement = doc.querySelector('#results');
                if (resultsElement && resultsElement.innerHTML.trim() !== '') {
                    const bodyContent = doc.querySelector('#resultsBody');
                    const statsContent = doc.querySelector('#statsContainer');
                    const summaryContent = doc.querySelector('#resultSummary');
                    const downloadLink = doc.querySelector('#downloadBtn');
                    
                    if (bodyContent) resultsBody.innerHTML = bodyContent.innerHTML;
                    if (statsContent) statsContainer.innerHTML = statsContent.innerHTML;
                    if (summaryContent) resultSummary.textContent = summaryContent.textContent;
                    if (downloadLink) {
                        downloadBtn.href = downloadLink.href || '#';
                        downloadBtn.style.display = 'inline-block';
                    }
                    results.classList.add('show');
                }
                
                loading.classList.remove('show');
                submitBtn.disabled = false;
            })
            .catch(error => {
                showMessage('error', '❌ حدث خطأ: ' + error.message);
                loading.classList.remove('show');
                submitBtn.disabled = false;
            });
        });
        
        function showMessage(type, text) {
            message.className = 'message ' + type;
            message.textContent = text;
            message.style.display = 'block';
            if (type === 'success' || type === 'info') {
                setTimeout(() => { message.style.display = 'none'; }, 5000);
            }
        }
        
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        <?php if ($analysisResult && $analysisResult['success']): ?>
        document.addEventListener('DOMContentLoaded', function() {
            const result = <?php echo json_encode($analysisResult); ?>;
            let filesHtml = '';
            
            if (result.files && result.files.length > 0) {
                filesHtml += '<input type="text" class="search-box" id="searchBox" placeholder="🔍 بحث في الملفات..." onkeyup="searchFiles()">';
                
                result.files.forEach((file, index) => {
                    const fileId = 'file-' + index;
                    filesHtml += `
                        <div class="file-item" id="${fileId}">
                            <div class="file-header" onclick="toggleContent('${fileId}')">
                                <div class="file-info">
                                    <div class="name">📄 ${escapeHtml(file.name)}</div>
                                    <div class="path">📁 ${escapeHtml(file.path)}</div>
                                </div>
                                <div class="file-meta">
                                    <span class="size-badge">📏 ${file.size || 0} حرف</span>
                                    <span class="badge">#${index + 1}</span>
                                    <button class="toggle-btn" id="toggle-${fileId}" onclick="event.stopPropagation(); toggleContent('${fileId}')">▼</button>
                                </div>
                            </div>
                            <div class="file-content" id="content-${fileId}">
                                <pre>${escapeHtml(file.content || 'لا يوجد محتوى')}</pre>
                            </div>
                        </div>
                    `;
                });
            } else {
                filesHtml = '<p style="text-align: center; color: #a0aec0; padding: 20px;">⚠️ لم يتم العثور على كلاسات</p>';
            }
            
            resultsBody.innerHTML = filesHtml;
            
            statsContainer.innerHTML = `
                <div class="stat-box"><div class="number">${result.total_files || 0}</div><div class="label">📄 عدد الكلاسات</div></div>
                <div class="stat-box"><div class="number">${result.output_file ? '✅' : '❌'}</div><div class="label">📁 ملف النتائج</div></div>
                <div class="stat-box"><div class="number">com/elmostadiratv/app/</div><div class="label">🎯 المسار المستهدف</div></div>
            `;
            
            resultSummary.textContent = `تم العثور على ${result.total_files || 0} كلاس في المسار المستهدف`;
            
            if (result.output_file) {
                downloadBtn.href = 'download.php?file=' + encodeURIComponent(result.output_file);
                downloadBtn.style.display = 'inline-block';
            }
            
            results.classList.add('show');
            showMessage('success', '✅ تم تحليل الملف بنجاح!');
        });
        <?php endif; ?>
    </script>
</body>
</html>