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

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

try {
    $database = new Database();
    $db = $database->getConnection();
    
    if (!$db) {
        throw new Exception("فشل الاتصال بقاعدة البيانات");
    }
    
    $input = json_decode(file_get_contents('php://input'), true);
    $backupType = $input['type'] ?? 'full';
    $selectedTables = $input['tables'] ?? ['all'];
    
    $backupDir = __DIR__ . '/../../../backups/';
    if (!is_dir($backupDir)) {
        mkdir($backupDir, 0777, true);
    }
    
    $filename = $backupDir . 'backup_' . date('Y-m-d_H-i-s') . '.sql';
    
    // بناء أمر التصدير
    $command = "mysqldump -u root digitals_autotester_db";
    
    if ($backupType === 'structure') {
        $command .= " --no-data";
    } else if ($backupType === 'data') {
        $command .= " --no-create-info";
    }
    
    if ($selectedTables !== ['all']) {
        $tables = implode(' ', $selectedTables);
        $command .= " $tables";
    }
    
    $command .= " > " . $filename;
    
    // تنفيذ الأمر
    exec($command, $output, $returnCode);
    
    if ($returnCode === 0) {
        echo json_encode([
            'success' => true,
            'message' => 'تم إنشاء النسخة الاحتياطية بنجاح',
            'filename' => basename($filename)
        ]);
    } else {
        throw new Exception("فشل إنشاء النسخة الاحتياطية");
    }
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
?>