<?php
session_start();
require_once '../config/database.php';

set_time_limit(300); // 5 minutes

$database = new Database();
$db = $database->getConnection();

// Project root
$project_root = dirname(dirname(__DIR__));

// Analysis results
$analysis = [
    'structure' => [],
    'files' => [],
    'database' => [],
    'apis' => [],
    'models' => [],
    'views' => [],
    'dependencies' => [],
    'stats' => []
];

// 1. Analyze Directory Structure
function analyzeDirectory($dir, $base_path = '', $depth = 0, $max_depth = 5) {
    if ($depth > $max_depth) return [];
    
    $structure = [];
    $items = @scandir($dir);
    
    if (!$items) return [];
    
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $path = $dir . '/' . $item;
        $relative_path = $base_path ? $base_path . '/' . $item : $item;
        
        // Skip certain directories
        if (in_array($item, ['node_modules', '.git', 'vendor', 'backups'])) continue;
        
        if (is_dir($path)) {
            $structure[$item] = [
                'type' => 'directory',
                'path' => $relative_path,
                'children' => analyzeDirectory($path, $relative_path, $depth + 1, $max_depth)
            ];
        } else {
            $ext = pathinfo($item, PATHINFO_EXTENSION);
            $size = filesize($path);
            
            $structure[$item] = [
                'type' => 'file',
                'path' => $relative_path,
                'extension' => $ext,
                'size' => $size,
                'modified' => filemtime($path)
            ];
        }
    }
    
    return $structure;
}

// 2. Analyze Files by Type
function analyzeFilesByType($dir, &$files, $base_path = '') {
    $items = @scandir($dir);
    if (!$items) return;
    
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $path = $dir . '/' . $item;
        $relative_path = $base_path ? $base_path . '/' . $item : $item;
        
        if (in_array($item, ['node_modules', '.git', 'vendor', 'backups'])) continue;
        
        if (is_dir($path)) {
            analyzeFilesByType($path, $files, $relative_path);
        } else {
            $ext = pathinfo($item, PATHINFO_EXTENSION);
            
            if (!isset($files[$ext])) {
                $files[$ext] = ['count' => 0, 'size' => 0, 'files' => []];
            }
            
            $size = filesize($path);
            $files[$ext]['count']++;
            $files[$ext]['size'] += $size;
            $files[$ext]['files'][] = [
                'name' => $item,
                'path' => $relative_path,
                'size' => $size,
                'lines' => in_array($ext, ['php', 'js', 'css', 'html']) ? count(file($path)) : 0
            ];
        }
    }
}

// 3. Analyze Database
function analyzeDatabase($db) {
    $analysis = [
        'tables' => [],
        'total_records' => 0,
        'total_size' => 0
    ];
    
    try {
        // Get all tables
        $stmt = $db->query("SHOW TABLES");
        $tables = $stmt->fetchAll(PDO::FETCH_COLUMN);
        
        foreach ($tables as $table) {
            // Get table info
            $stmt = $db->query("SELECT COUNT(*) as count FROM `{$table}`");
            $count = $stmt->fetch(PDO::FETCH_ASSOC)['count'];
            
            // Get columns
            $stmt = $db->query("SHOW COLUMNS FROM `{$table}`");
            $columns = $stmt->fetchAll(PDO::FETCH_ASSOC);
            
            // Get table size
            $stmt = $db->query("SELECT 
                ROUND((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2) as size_mb
                FROM information_schema.TABLES 
                WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = '{$table}'");
            $size = $stmt->fetch(PDO::FETCH_ASSOC)['size_mb'] ?? 0;
            
            $analysis['tables'][$table] = [
                'records' => $count,
                'columns' => count($columns),
                'column_list' => array_column($columns, 'Field'),
                'size_mb' => $size
            ];
            
            $analysis['total_records'] += $count;
            $analysis['total_size'] += $size;
        }
        
    } catch (Exception $e) {
        $analysis['error'] = $e->getMessage();
    }
    
    return $analysis;
}

// 4. Find API Endpoints
function findAPIEndpoints($dir, &$apis, $base_path = '') {
    $items = @scandir($dir);
    if (!$items) return;
    
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $path = $dir . '/' . $item;
        $relative_path = $base_path ? $base_path . '/' . $item : $item;
        
        if (is_dir($path)) {
            findAPIEndpoints($path, $apis, $relative_path);
        } elseif (pathinfo($item, PATHINFO_EXTENSION) === 'php' && strpos($relative_path, 'api/') !== false) {
            $content = file_get_contents($path);
            
            // Detect HTTP methods
            $methods = [];
            if (preg_match('/\$_GET/', $content)) $methods[] = 'GET';
            if (preg_match('/\$_POST/', $content)) $methods[] = 'POST';
            if (preg_match('/\$_PUT/', $content)) $methods[] = 'PUT';
            if (preg_match('/\$_DELETE/', $content)) $methods[] = 'DELETE';
            
            // Detect required parameters
            $params = [];
            preg_match_all('/\$_(GET|POST)\[[\'"](.*?)[\'"]\]/', $content, $matches);
            if (!empty($matches[2])) {
                $params = array_unique($matches[2]);
            }
            
            $apis[] = [
                'file' => $item,
                'path' => $relative_path,
                'methods' => $methods,
                'params' => $params,
                'lines' => count(file($path))
            ];
        }
    }
}

// 5. Find Models
function findModels($dir, &$models, $base_path = '') {
    $items = @scandir($dir);
    if (!$items) return;
    
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') continue;
        
        $path = $dir . '/' . $item;
        $relative_path = $base_path ? $base_path . '/' . $item : $item;
        
        if (is_dir($path)) {
            findModels($path, $models, $relative_path);
        } elseif (pathinfo($item, PATHINFO_EXTENSION) === 'php' && strpos($relative_path, 'models/') !== false) {
            $content = file_get_contents($path);
            
            // Detect class name
            preg_match('/class\s+(\w+)/', $content, $class_match);
            $class_name = $class_match[1] ?? pathinfo($item, PATHINFO_FILENAME);
            
            // Detect methods
            preg_match_all('/function\s+(\w+)\s*\(/', $content, $method_matches);
            $methods = $method_matches[1] ?? [];
            
            $models[] = [
                'file' => $item,
                'path' => $relative_path,
                'class' => $class_name,
                'methods' => $methods,
                'lines' => count(file($path))
            ];
        }
    }
}

// Run Analysis
$analysis['structure'] = analyzeDirectory($project_root);
analyzeFilesByType($project_root, $analysis['files']);
$analysis['database'] = analyzeDatabase($db);
findAPIEndpoints($project_root . '/backend', $analysis['apis']);
findModels($project_root . '/backend', $analysis['models']);

// Calculate Statistics
$total_files = 0;
$total_size = 0;
$total_lines = 0;

foreach ($analysis['files'] as $ext => $data) {
    $total_files += $data['count'];
    $total_size += $data['size'];
    foreach ($data['files'] as $file) {
        $total_lines += $file['lines'];
    }
}

$analysis['stats'] = [
    'total_files' => $total_files,
    'total_size' => $total_size,
    'total_lines' => $total_lines,
    'total_tables' => count($analysis['database']['tables']),
    'total_records' => $analysis['database']['total_records'],
    'total_apis' => count($analysis['apis']),
    'total_models' => count($analysis['models'])
];

// Export options
if (isset($_GET['export'])) {
    header('Content-Type: application/json');
    header('Content-Disposition: attachment; filename="project-analysis-' . date('Y-m-d') . '.json"');
    echo json_encode($analysis, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
    exit;
}

function formatBytes($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    }
    return $bytes . ' B';
}

function convertToMindMapData($structure, $name = 'المشروع', $maxDepth = 3, $currentDepth = 0) {
    if ($currentDepth >= $maxDepth) {
        return null;
    }
    
    $node = [
        'name' => $name,
        'children' => []
    ];
    
    $dirCount = 0;
    $fileCount = 0;
    
    foreach ($structure as $itemName => $item) {
        if ($item['type'] === 'directory') {
            $dirCount++;
            if ($currentDepth < $maxDepth - 1 && !empty($item['children'])) {
                $child = convertToMindMapData($item['children'], $itemName, $maxDepth, $currentDepth + 1);
                if ($child) {
                    $node['children'][] = $child;
                }
            } else {
                $node['children'][] = ['name' => $itemName . ' (مجلد)'];
            }
        } else {
            $fileCount++;
        }
    }
    
    // Add summary if there are files
    if ($fileCount > 0) {
        $node['children'][] = ['name' => "{$fileCount} ملف"];
    }
    
    return $node;
}

function renderTree($structure, $name = 'root', $level = 0) {
    $html = '';
    
    if ($level === 0) {
        $html .= '<div class="tree-item" data-level="0">';
        $html .= '<div class="flex items-center gap-2 p-2 hover:bg-gray-50 rounded cursor-pointer" onclick="toggleNode(this)">';
        $html .= '<i class="fas fa-folder text-yellow-500"></i>';
        $html .= '<span class="font-bold text-lg">' . htmlspecialchars($name) . '</span>';
        $html .= '<i class="fas fa-chevron-down text-xs text-gray-400 ml-auto transition-transform"></i>';
        $html .= '</div>';
        $html .= '<div class="tree-children ml-6 border-r-2 border-gray-200">';
    }
    
    foreach ($structure as $itemName => $item) {
        if ($item['type'] === 'directory') {
            $childCount = count($item['children']);
            $html .= '<div class="tree-item" data-level="' . ($level + 1) . '">';
            $html .= '<div class="flex items-center gap-2 p-2 hover:bg-blue-50 rounded cursor-pointer" onclick="toggleNode(this)">';
            $html .= '<i class="fas fa-folder text-blue-500"></i>';
            $html .= '<span class="font-medium">' . htmlspecialchars($itemName) . '</span>';
            $html .= '<span class="text-xs text-gray-500">(' . $childCount . ')</span>';
            $html .= '<i class="fas fa-chevron-down text-xs text-gray-400 ml-auto transition-transform"></i>';
            $html .= '</div>';
            
            if (!empty($item['children'])) {
                $html .= '<div class="tree-children ml-6 border-r-2 border-gray-200">';
                $html .= renderTree($item['children'], $itemName, $level + 1);
                $html .= '</div>';
            }
            
            $html .= '</div>';
        } else {
            // File
            $icon = 'fa-file';
            $color = 'text-gray-500';
            
            switch ($item['extension']) {
                case 'php':
                    $icon = 'fa-file-code';
                    $color = 'text-purple-500';
                    break;
                case 'js':
                    $icon = 'fa-file-code';
                    $color = 'text-yellow-500';
                    break;
                case 'css':
                    $icon = 'fa-file-code';
                    $color = 'text-blue-500';
                    break;
                case 'html':
                    $icon = 'fa-file-code';
                    $color = 'text-orange-500';
                    break;
                case 'json':
                    $icon = 'fa-file-code';
                    $color = 'text-green-500';
                    break;
                case 'md':
                    $icon = 'fa-file-alt';
                    $color = 'text-gray-600';
                    break;
                case 'sql':
                    $icon = 'fa-database';
                    $color = 'text-red-500';
                    break;
                case 'jpg':
                case 'jpeg':
                case 'png':
                case 'gif':
                case 'svg':
                    $icon = 'fa-file-image';
                    $color = 'text-pink-500';
                    break;
            }
            
            $html .= '<div class="flex items-center gap-2 p-2 hover:bg-gray-50 rounded">';
            $html .= '<i class="fas ' . $icon . ' ' . $color . '"></i>';
            $html .= '<span class="text-sm">' . htmlspecialchars($itemName) . '</span>';
            $html .= '<span class="text-xs text-gray-400 ml-auto">' . formatBytes($item['size']) . '</span>';
            $html .= '</div>';
        }
    }
    
    if ($level === 0) {
        $html .= '</div></div>';
    }
    
    return $html;
}
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>محلل المشروع - Project Analyzer</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">
    <style>
        body { font-family: 'Tajawal', sans-serif; }
        .tab-content { display: none; }
        .tab-content.active { display: block; }
        .tree-item { cursor: pointer; }
        .tree-children { display: none; margin-right: 20px; }
        .tree-item.open > .tree-children { display: block; }
    </style>
</head>
<body class="bg-gray-50">

<div class="min-h-screen py-8">
    <div class="max-w-7xl mx-auto px-4">
        
        <!-- Header -->
        <div class="bg-gradient-to-r from-blue-600 to-purple-600 rounded-xl shadow-lg p-6 mb-8 text-white">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold mb-2">
                        <i class="fas fa-project-diagram ml-2"></i>
                        محلل المشروع الشامل
                    </h1>
                    <p class="text-blue-100">تحليل كامل لهيكل المشروع والملفات وقاعدة البيانات</p>
                </div>
                <div class="flex gap-3">
                    <a href="?export=json" class="px-4 py-2 bg-white text-blue-600 rounded-lg hover:bg-blue-50 transition">
                        <i class="fas fa-download ml-1"></i>
                        تصدير JSON
                    </a>
                    <a href="dashboard.php" class="px-4 py-2 bg-white/20 text-white rounded-lg hover:bg-white/30 transition">
                        <i class="fas fa-arrow-right ml-1"></i>
                        العودة
                    </a>
                </div>
            </div>
        </div>

        <!-- Stats Overview -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
            <div class="bg-white rounded-xl shadow-md p-6 border-r-4 border-blue-500">
                <div class="text-sm text-gray-600 mb-1">إجمالي الملفات</div>
                <div class="text-3xl font-bold text-blue-600"><?php echo number_format($analysis['stats']['total_files']); ?></div>
            </div>
            <div class="bg-white rounded-xl shadow-md p-6 border-r-4 border-green-500">
                <div class="text-sm text-gray-600 mb-1">أسطر الكود</div>
                <div class="text-3xl font-bold text-green-600"><?php echo number_format($analysis['stats']['total_lines']); ?></div>
            </div>
            <div class="bg-white rounded-xl shadow-md p-6 border-r-4 border-purple-500">
                <div class="text-sm text-gray-600 mb-1">جداول قاعدة البيانات</div>
                <div class="text-3xl font-bold text-purple-600"><?php echo $analysis['stats']['total_tables']; ?></div>
            </div>
            <div class="bg-white rounded-xl shadow-md p-6 border-r-4 border-orange-500">
                <div class="text-sm text-gray-600 mb-1">API Endpoints</div>
                <div class="text-3xl font-bold text-orange-600"><?php echo $analysis['stats']['total_apis']; ?></div>
            </div>
        </div>

        <!-- Tabs -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <div class="border-b border-gray-200">
                <nav class="flex overflow-x-auto">
                    <button onclick="switchTab('files')" class="tab-btn px-6 py-4 text-sm font-medium border-b-2 border-blue-500 text-blue-600">
                        <i class="fas fa-file ml-1"></i> الملفات
                    </button>
                    <button onclick="switchTab('database')" class="tab-btn px-6 py-4 text-sm font-medium text-gray-500 hover:text-gray-700">
                        <i class="fas fa-database ml-1"></i> قاعدة البيانات
                    </button>
                    <button onclick="switchTab('apis')" class="tab-btn px-6 py-4 text-sm font-medium text-gray-500 hover:text-gray-700">
                        <i class="fas fa-plug ml-1"></i> APIs
                    </button>
                    <button onclick="switchTab('models')" class="tab-btn px-6 py-4 text-sm font-medium text-gray-500 hover:text-gray-700">
                        <i class="fas fa-cube ml-1"></i> Models
                    </button>
                    <button onclick="switchTab('structure')" class="tab-btn px-6 py-4 text-sm font-medium text-gray-500 hover:text-gray-700">
                        <i class="fas fa-sitemap ml-1"></i> الهيكل
                    </button>
                    <button onclick="switchTab('graph')" class="tab-btn px-6 py-4 text-sm font-medium text-gray-500 hover:text-gray-700">
                        <i class="fas fa-network-wired ml-1"></i> الرسم البياني
                    </button>
                </nav>
            </div>

            <div class="p-6">
                <!-- Files Tab -->
                <div id="files-tab" class="tab-content active">
                    <h3 class="text-xl font-bold mb-4">الملفات حسب النوع</h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <?php foreach ($analysis['files'] as $ext => $data): ?>
                        <div class="border rounded-lg p-4 hover:shadow-md transition">
                            <div class="flex items-center justify-between mb-2">
                                <span class="font-bold text-lg">.<?php echo $ext; ?></span>
                                <span class="text-sm text-gray-500"><?php echo $data['count']; ?> ملف</span>
                            </div>
                            <div class="text-sm text-gray-600">
                                <div>الحجم: <?php echo formatBytes($data['size']); ?></div>
                                <?php if (!empty($data['files'][0]['lines'])): ?>
                                <div>الأسطر: <?php echo number_format(array_sum(array_column($data['files'], 'lines'))); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Database Tab -->
                <div id="database-tab" class="tab-content">
                    <h3 class="text-xl font-bold mb-4">جداول قاعدة البيانات</h3>
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200">
                            <thead class="bg-gray-50">
                                <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>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php foreach ($analysis['database']['tables'] as $table => $info): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap font-medium"><?php echo $table; ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap"><?php echo number_format($info['records']); ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap"><?php echo $info['columns']; ?></td>
                                    <td class="px-6 py-4 whitespace-nowrap"><?php echo $info['size_mb']; ?> MB</td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- APIs Tab -->
                <div id="apis-tab" class="tab-content">
                    <h3 class="text-xl font-bold mb-4">API Endpoints (<?php echo count($analysis['apis']); ?>)</h3>
                    <div class="space-y-3">
                        <?php foreach ($analysis['apis'] as $api): ?>
                        <div class="border rounded-lg p-4 hover:shadow-md transition">
                            <div class="flex items-start justify-between">
                                <div class="flex-1">
                                    <div class="font-bold text-lg mb-1"><?php echo $api['file']; ?></div>
                                    <div class="text-sm text-gray-600 mb-2"><?php echo $api['path']; ?></div>
                                    <div class="flex gap-2 flex-wrap">
                                        <?php foreach ($api['methods'] as $method): ?>
                                        <span class="px-2 py-1 bg-blue-100 text-blue-700 rounded text-xs font-medium"><?php echo $method; ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php if (!empty($api['params'])): ?>
                                    <div class="mt-2 text-xs text-gray-500">
                                        Parameters: <?php echo implode(', ', $api['params']); ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div class="text-sm text-gray-500"><?php echo $api['lines']; ?> سطر</div>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Models Tab -->
                <div id="models-tab" class="tab-content">
                    <h3 class="text-xl font-bold mb-4">Models (<?php echo count($analysis['models']); ?>)</h3>
                    <div class="space-y-3">
                        <?php foreach ($analysis['models'] as $model): ?>
                        <div class="border rounded-lg p-4 hover:shadow-md transition">
                            <div class="flex items-start justify-between mb-2">
                                <div>
                                    <div class="font-bold text-lg"><?php echo $model['class']; ?></div>
                                    <div class="text-sm text-gray-600"><?php echo $model['path']; ?></div>
                                </div>
                                <div class="text-sm text-gray-500"><?php echo $model['lines']; ?> سطر</div>
                            </div>
                            <?php if (!empty($model['methods'])): ?>
                            <div class="mt-3">
                                <div class="text-sm font-medium text-gray-700 mb-2">Methods (<?php echo count($model['methods']); ?>):</div>
                                <div class="flex gap-2 flex-wrap">
                                    <?php foreach ($model['methods'] as $method): ?>
                                    <span class="px-2 py-1 bg-purple-100 text-purple-700 rounded text-xs"><?php echo $method; ?>()</span>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <!-- Graph Tab -->
                <div id="graph-tab" class="tab-content">
                    <h3 class="text-xl font-bold mb-4">الرسم البياني التفاعلي</h3>
                    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
                        <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-lg p-4 border-2 border-blue-200">
                            <div class="flex items-center gap-3">
                                <div class="bg-blue-500 p-3 rounded-full">
                                    <i class="fas fa-folder text-white text-xl"></i>
                                </div>
                                <div>
                                    <div class="text-sm text-blue-600 font-medium">المجلدات</div>
                                    <div class="text-2xl font-bold text-blue-700">
                                        <?php 
                                        function countDirs($structure) {
                                            $count = 0;
                                            foreach ($structure as $item) {
                                                if ($item['type'] === 'directory') {
                                                    $count++;
                                                    if (!empty($item['children'])) {
                                                        $count += countDirs($item['children']);
                                                    }
                                                }
                                            }
                                            return $count;
                                        }
                                        echo countDirs($analysis['structure']);
                                        ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-lg p-4 border-2 border-green-200">
                            <div class="flex items-center gap-3">
                                <div class="bg-green-500 p-3 rounded-full">
                                    <i class="fas fa-file-code text-white text-xl"></i>
                                </div>
                                <div>
                                    <div class="text-sm text-green-600 font-medium">ملفات PHP</div>
                                    <div class="text-2xl font-bold text-green-700">
                                        <?php echo $analysis['files']['php']['count'] ?? 0; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="bg-gradient-to-br from-purple-50 to-purple-100 rounded-lg p-4 border-2 border-purple-200">
                            <div class="flex items-center gap-3">
                                <div class="bg-purple-500 p-3 rounded-full">
                                    <i class="fas fa-database text-white text-xl"></i>
                                </div>
                                <div>
                                    <div class="text-sm text-purple-600 font-medium">الجداول</div>
                                    <div class="text-2xl font-bold text-purple-700">
                                        <?php echo count($analysis['database']['tables']); ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="bg-white rounded-lg border p-6">
                        <canvas id="projectChart" width="400" height="200"></canvas>
                    </div>
                </div>

                <!-- Structure Tab -->
                <div id="structure-tab" class="tab-content">
                    <div class="flex items-center justify-between mb-4">
                        <h3 class="text-xl font-bold">هيكل المشروع</h3>
                        <div class="flex gap-2">
                            <button onclick="expandAll()" class="px-3 py-1 bg-blue-100 text-blue-700 rounded text-sm hover:bg-blue-200">
                                <i class="fas fa-expand-alt ml-1"></i>فتح الكل
                            </button>
                            <button onclick="collapseAll()" class="px-3 py-1 bg-gray-100 text-gray-700 rounded text-sm hover:bg-gray-200">
                                <i class="fas fa-compress-alt ml-1"></i>إغلاق الكل
                            </button>
                            <button onclick="switchView('tree')" class="px-3 py-1 bg-green-100 text-green-700 rounded text-sm hover:bg-green-200">
                                <i class="fas fa-sitemap ml-1"></i>شجرة
                            </button>
                            <button onclick="switchView('mindmap')" class="px-3 py-1 bg-purple-100 text-purple-700 rounded text-sm hover:bg-purple-200">
                                <i class="fas fa-project-diagram ml-1"></i>خريطة ذهنية
                            </button>
                        </div>
                    </div>
                    
                    <!-- Tree View -->
                    <div id="tree-view" class="bg-white rounded-lg border p-4">
                        <div class="tree-root">
                            <?php echo renderTree($analysis['structure'], 'المشروع'); ?>
                        </div>
                    </div>
                    
                    <!-- Mind Map View -->
                    <div id="mindmap-view" class="hidden bg-white rounded-lg border p-4" style="min-height: 600px;">
                        <div id="mindmap-container" class="w-full h-full"></div>
                    </div>
                </div>
            </div>
        </div>

    </div>
</div>

<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
function switchTab(tabName) {
    // Hide all tabs
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.remove('active');
    });
    
    // Remove active state from all buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('border-blue-500', 'text-blue-600');
        btn.classList.add('text-gray-500');
    });
    
    // Show selected tab
    document.getElementById(tabName + '-tab').classList.add('active');
    
    // Activate button
    event.target.classList.add('border-blue-500', 'text-blue-600');
    event.target.classList.remove('text-gray-500');
    
    // Initialize mindmap if structure tab
    if (tabName === 'structure') {
        setTimeout(() => {
            if (document.getElementById('mindmap-view').style.display !== 'none') {
                initMindMap();
            }
        }, 100);
    }
}

// Tree View Functions
function toggleNode(element) {
    const parent = element.parentElement;
    const children = parent.querySelector('.tree-children');
    const icon = element.querySelector('.fa-chevron-down');
    
    if (children) {
        if (children.style.display === 'none') {
            children.style.display = 'block';
            icon.style.transform = 'rotate(0deg)';
        } else {
            children.style.display = 'none';
            icon.style.transform = 'rotate(-90deg)';
        }
    }
}

function expandAll() {
    document.querySelectorAll('.tree-children').forEach(el => {
        el.style.display = 'block';
    });
    document.querySelectorAll('.fa-chevron-down').forEach(el => {
        el.style.transform = 'rotate(0deg)';
    });
}

function collapseAll() {
    document.querySelectorAll('.tree-children').forEach(el => {
        el.style.display = 'none';
    });
    document.querySelectorAll('.fa-chevron-down').forEach(el => {
        el.style.transform = 'rotate(-90deg)';
    });
}

function switchView(view) {
    if (view === 'tree') {
        document.getElementById('tree-view').classList.remove('hidden');
        document.getElementById('mindmap-view').classList.add('hidden');
    } else {
        document.getElementById('tree-view').classList.add('hidden');
        document.getElementById('mindmap-view').classList.remove('hidden');
        initMindMap();
    }
}

// Mind Map with D3.js
let mindmapInitialized = false;

function initMindMap() {
    if (mindmapInitialized) return;
    mindmapInitialized = true;
    
    const container = document.getElementById('mindmap-container');
    const width = container.clientWidth;
    const height = 600;
    
    // Sample data structure
    const data = <?php echo json_encode(convertToMindMapData($analysis['structure'])); ?>;
    
    const svg = d3.select('#mindmap-container')
        .append('svg')
        .attr('width', width)
        .attr('height', height);
    
    const g = svg.append('g')
        .attr('transform', `translate(${width/2},${height/2})`);
    
    // Create tree layout
    const tree = d3.tree()
        .size([2 * Math.PI, Math.min(width, height) / 2 - 100])
        .separation((a, b) => (a.parent == b.parent ? 1 : 2) / a.depth);
    
    const root = d3.hierarchy(data);
    tree(root);
    
    // Links
    g.selectAll('.link')
        .data(root.links())
        .enter()
        .append('path')
        .attr('class', 'link')
        .attr('d', d3.linkRadial()
            .angle(d => d.x)
            .radius(d => d.y))
        .style('fill', 'none')
        .style('stroke', '#ccc')
        .style('stroke-width', 2);
    
    // Nodes
    const node = g.selectAll('.node')
        .data(root.descendants())
        .enter()
        .append('g')
        .attr('class', 'node')
        .attr('transform', d => `rotate(${d.x * 180 / Math.PI - 90}) translate(${d.y},0)`);
    
    node.append('circle')
        .attr('r', d => d.children ? 8 : 5)
        .style('fill', d => d.children ? '#4F46E5' : '#10B981')
        .style('stroke', '#fff')
        .style('stroke-width', 2);
    
    node.append('text')
        .attr('dy', '.31em')
        .attr('x', d => d.x < Math.PI === !d.children ? 6 : -6)
        .attr('text-anchor', d => d.x < Math.PI === !d.children ? 'start' : 'end')
        .attr('transform', d => d.x >= Math.PI ? 'rotate(180)' : null)
        .text(d => d.data.name)
        .style('font-size', '12px')
        .style('fill', '#333');
    
    // Add zoom
    const zoom = d3.zoom()
        .scaleExtent([0.5, 3])
        .on('zoom', (event) => {
            g.attr('transform', `translate(${width/2},${height/2}) ${event.transform}`);
        });
    
    svg.call(zoom);
}

// Chart.js for Graph Tab
let chartInitialized = false;

function initChart() {
    if (chartInitialized) return;
    chartInitialized = true;
    
    const ctx = document.getElementById('projectChart');
    if (!ctx) return;
    
    const fileTypes = <?php echo json_encode(array_keys($analysis['files'])); ?>;
    const fileCounts = <?php echo json_encode(array_column($analysis['files'], 'count')); ?>;
    
    new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: fileTypes.map(ext => '.' + ext),
            datasets: [{
                label: 'عدد الملفات',
                data: fileCounts,
                backgroundColor: [
                    '#3B82F6', '#10B981', '#F59E0B', '#EF4444', '#8B5CF6',
                    '#EC4899', '#14B8A6', '#F97316', '#6366F1', '#84CC16'
                ],
                borderWidth: 2,
                borderColor: '#fff'
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    rtl: true,
                    labels: {
                        font: {
                            family: 'Tajawal',
                            size: 14
                        },
                        padding: 15,
                        usePointStyle: true
                    }
                },
                title: {
                    display: true,
                    text: 'توزيع الملفات حسب النوع',
                    font: {
                        family: 'Tajawal',
                        size: 18,
                        weight: 'bold'
                    },
                    padding: 20
                }
            }
        }
    });
}

// Initialize chart when graph tab is opened
document.addEventListener('DOMContentLoaded', function() {
    const graphTab = document.querySelector('[onclick*="graph"]');
    if (graphTab) {
        graphTab.addEventListener('click', function() {
            setTimeout(initChart, 100);
        });
    }
});
</script>

</body>
</html>
