<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET');

require_once __DIR__ . '/../../database.php';

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    // الحصول على آخر نسخة احتياطية
    $backupDir = __DIR__ . '/../../../backups/';
    $lastBackup = 'لم يتم';
    $backupFiles = [];
    
    if (is_dir($backupDir)) {
        $files = glob($backupDir . '*.sql');
        if (!empty($files)) {
            $latestFile = max($files);
            $lastBackup = date('Y-m-d H:i:s', filemtime($latestFile));
            
            foreach ($files as $file) {
                $backupFiles[] = basename($file);
            }
        }
    }
    
    // حجم قاعدة البيانات
    $sizeQuery = "SELECT 
                    SUM(data_length + index_length) as size 
                  FROM information_schema.tables 
                  WHERE table_schema = 'digitals_autotester_db'";
    $sizeStmt = $db->query($sizeQuery);
    $size = $sizeStmt->fetch(PDO::FETCH_ASSOC);
    
    $dbSize = $size['size'] ? round($size['size'] / 1024 / 1024, 2) . ' MB' : '0 MB';
    
    // عدد الجداول
    $tablesQuery = "SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = 'digitals_autotester_db'";
    $tablesStmt = $db->query($tablesQuery);
    $tables = $tablesStmt->fetch(PDO::FETCH_ASSOC);
    
    // قائمة الجداول
    $tablesListQuery = "SELECT table_name FROM information_schema.tables WHERE table_schema = 'digitals_autotester_db' ORDER BY table_name";
    $tablesListStmt = $db->query($tablesListQuery);
    $tablesList = $tablesListStmt->fetchAll(PDO::FETCH_COLUMN);
    
    echo json_encode([
        'success' => true,
        'data' => [
            'last_backup' => $lastBackup,
            'db_size' => $dbSize,
            'tables_count' => $tables['count'] ?? 0,
            'tables' => $tablesList,
            'backup_files' => $backupFiles
        ]
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>