<?php
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

// Create backups directory on activation
function moesec_create_backup_directory() {
    $backup_dir = WP_CONTENT_DIR . '/moesec-backups';
    if (!file_exists($backup_dir)) {
        wp_mkdir_p($backup_dir);
        
        // Create .htaccess to prevent direct access
        $htaccess_content = "# MoeSec Backup Protection\n";
        $htaccess_content .= "Order deny,allow\n";
        $htaccess_content .= "Deny from all\n";
        $htaccess_content .= "<Files ~ \"\\.(zip|tar\\.gz|sql)$\">\n";
        $htaccess_content .= "    Order deny,allow\n";
        $htaccess_content .= "    Deny from all\n";
        $htaccess_content .= "</Files>\n";
        
        file_put_contents($backup_dir . '/.htaccess', $htaccess_content);
        
        // Create index.php to prevent directory listing
        file_put_contents($backup_dir . '/index.php', '<?php // Silence is golden');
    }
    
    return $backup_dir;
}

add_action('wp_ajax_moesec_start_file_backup', 'moesec_ajax_start_file_backup');
function moesec_ajax_start_file_backup() {
    check_ajax_referer('moesec_backup_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => esc_html__('Permission denied.', 'moesec')));
    }
    
    // Schedule background backup
    wp_schedule_single_event(time(), 'moesec_background_file_backup');
    
    wp_send_json_success(array('message' => esc_html__('File backup started in background.', 'moesec')));
}

add_action('wp_ajax_moesec_start_db_backup', 'moesec_ajax_start_db_backup');
function moesec_ajax_start_db_backup() {
    check_ajax_referer('moesec_backup_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => esc_html__('Permission denied.', 'moesec')));
    }
    
    // Schedule background backup
    wp_schedule_single_event(time(), 'moesec_background_db_backup');
    
    wp_send_json_success(array('message' => esc_html__('Database backup started in background.', 'moesec')));
}

add_action('wp_ajax_moesec_backup_progress', 'moesec_ajax_backup_progress');
function moesec_ajax_backup_progress() {
    check_ajax_referer('moesec_backup_nonce', 'nonce');
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error(array('message' => esc_html__('Permission denied.', 'moesec')));
    }
    
    $file_progress = get_transient('moesec_file_backup_progress');
    $db_progress = get_transient('moesec_db_backup_progress');
    $file_status = get_transient('moesec_file_backup_status');
    $db_status = get_transient('moesec_db_backup_status');
    
    wp_send_json_success(array(
        'file_progress' => $file_progress !== false ? $file_progress : 0,
        'db_progress' => $db_progress !== false ? $db_progress : 0,
        'file_status' => $file_status ? $file_status : 'idle',
        'db_status' => $db_status ? $db_status : 'idle'
    ));
}

// Background file backup
add_action('moesec_background_file_backup', 'moesec_background_file_backup_handler');
function moesec_background_file_backup_handler() {
    set_transient('moesec_file_backup_status', 'running', 3600);
    set_transient('moesec_file_backup_progress', 0, 3600);
    
    $result = moesec_create_file_backup();
    
    if (is_wp_error($result)) {
        set_transient('moesec_file_backup_status', 'error: ' . $result->get_error_message(), 3600);
    } else {
        set_transient('moesec_file_backup_status', 'completed', 3600);
    }
    
    set_transient('moesec_file_backup_progress', 100, 3600);
}

// Background database backup
add_action('moesec_background_db_backup', 'moesec_background_db_backup_handler');
function moesec_background_db_backup_handler() {
    set_transient('moesec_db_backup_status', 'running', 3600);
    set_transient('moesec_db_backup_progress', 0, 3600);
    
    $result = moesec_create_database_backup();
    
    if (is_wp_error($result)) {
        set_transient('moesec_db_backup_status', 'error: ' . $result->get_error_message(), 3600);
    } else {
        set_transient('moesec_db_backup_status', 'completed', 3600);
    }
    
    set_transient('moesec_db_backup_progress', 100, 3600);
}

// Backups tab interface
function moesec_backups_tab() {
    if (!current_user_can('manage_options')) {
        wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'moesec'));
    }
    
    // Handle download action
    if (isset($_GET['moesec_download_backup']) && check_admin_referer('moesec_download_backup_' . $_GET['moesec_download_backup'])) {
        moesec_download_backup($_GET['moesec_download_backup']);
        exit;
    }
    
    // Handle delete action
    if (isset($_POST['moesec_delete_backup']) && check_admin_referer('moesec_delete_backup', 'moesec_delete_backup_nonce')) {
        $file = sanitize_file_name($_POST['backup_file']);
        $result = moesec_delete_backup($file);
        if ($result) {
            echo '<div class="updated"><p>' . esc_html__('Backup deleted successfully!', 'moesec') . '</p></div>';
        } else {
            echo '<div class="error"><p>' . esc_html__('Failed to delete backup.', 'moesec') . '</p></div>';
        }
    }
    
    // Handle restore action
    if (isset($_POST['moesec_restore_backup']) && check_admin_referer('moesec_restore_backup', 'moesec_restore_backup_nonce')) {
        $file = sanitize_file_name($_POST['backup_file']);
        $restore_type = sanitize_text_field($_POST['restore_type']);
        $result = moesec_restore_backup($file, $restore_type);
        if (is_wp_error($result)) {
            echo '<div class="error"><p>' . esc_html($result->get_error_message()) . '</p></div>';
        } else {
            echo '<div class="updated"><p>' . esc_html__('Backup restored successfully!', 'moesec') . '</p></div>';
        }
    }
    
    $backups = moesec_get_backups();
    ?>
    <h3><?php esc_html_e('Backup Management', 'moesec'); ?></h3>
    
    <div class="moesec-backup-actions" style="background: #fff; padding: 20px; border: 1px solid #ccc; margin: 20px 0;">
        <h4><?php esc_html_e('Create New Backup', 'moesec'); ?></h4>
        
        <div style="margin-bottom: 15px;">
            <button id="moesec-start-file-backup" class="button button-primary">
                <?php esc_html_e('Create File Backup', 'moesec'); ?>
            </button>
            <p class="description"><?php esc_html_e('Creates a complete backup of all website files (runs in background)', 'moesec'); ?></p>
            <div id="file-backup-progress" style="display: none; margin-top: 10px;">
                <div class="moesec-progress-bar">
                    <div class="moesec-progress" style="width: 0%;"></div>
                </div>
                <p id="file-backup-status"></p>
            </div>
        </div>
        
        <div>
            <button id="moesec-start-db-backup" class="button button-primary">
                <?php esc_html_e('Create Database Backup', 'moesec'); ?>
            </button>
            <p class="description"><?php esc_html_e('Creates a backup of the WordPress database (runs in background)', 'moesec'); ?></p>
            <div id="db-backup-progress" style="display: none; margin-top: 10px;">
                <div class="moesec-progress-bar">
                    <div class="moesec-progress" style="width: 0%;"></div>
                </div>
                <p id="db-backup-status"></p>
            </div>
        </div>
    </div>
    
    <h4><?php esc_html_e('Available Backups', 'moesec'); ?></h4>
    
    <?php if (empty($backups)): ?>
        <p><?php esc_html_e('No backups found. Create your first backup above.', 'moesec'); ?></p>
    <?php else: ?>
        <table class="widefat">
            <thead>
                <tr>
                    <th><?php esc_html_e('Filename', 'moesec'); ?></th>
                    <th><?php esc_html_e('Type', 'moesec'); ?></th>
                    <th><?php esc_html_e('Date Created', 'moesec'); ?></th>
                    <th><?php esc_html_e('Size', 'moesec'); ?></th>
                    <th><?php esc_html_e('Actions', 'moesec'); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($backups as $backup): ?>
                <tr>
                    <td><?php echo esc_html($backup['filename']); ?></td>
                    <td>
                        <?php 
                        if ($backup['type'] === 'files') {
                            echo '<span style="color: #0073aa;">📁 ' . esc_html__('Files', 'moesec') . '</span>';
                        } else {
                            echo '<span style="color: #d63638;">🗄️ ' . esc_html__('Database', 'moesec') . '</span>';
                        }
                        ?>
                    </td>
                    <td><?php echo esc_html($backup['date']); ?></td>
                    <td><?php echo esc_html($backup['size']); ?></td>
                    <td>
                        <a href="<?php echo esc_url(wp_nonce_url(admin_url('admin.php?page=moesec&tab=backups&moesec_download_backup=' . urlencode($backup['filename'])), 'moesec_download_backup_' . $backup['filename'])); ?>" class="button button-small"><?php esc_html_e('Download', 'moesec'); ?></a>
                        
                        <button type="button" class="button button-small" onclick="showRestoreModal('<?php echo esc_js($backup['filename']); ?>', '<?php echo esc_js($backup['type']); ?>')"><?php esc_html_e('Restore', 'moesec'); ?></button>
                        
                        <form method="post" action="" style="display: inline;">
                            <?php wp_nonce_field('moesec_delete_backup', 'moesec_delete_backup_nonce'); ?>
                            <input type="hidden" name="backup_file" value="<?php echo esc_attr($backup['filename']); ?>">
                            <input type="submit" name="moesec_delete_backup" class="button button-small" value="<?php esc_attr_e('Delete', 'moesec'); ?>" onclick="return confirm('<?php esc_attr_e('Are you sure you want to delete this backup?', 'moesec'); ?>');">
                        </form>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
    
    <div id="moesec-restore-modal" style="display: none; position: fixed; z-index: 999999; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.7);">
        <div style="background-color: #fff; margin: 10% auto; padding: 30px; width: 500px; border-radius: 5px;">
            <h3><?php esc_html_e('⚠️ Restore Backup', 'moesec'); ?></h3>
            <p style="color: #d63638; font-weight: bold;">
                <?php esc_html_e('WARNING: This action will overwrite existing data. Make sure you have a recent backup before proceeding.', 'moesec'); ?>
            </p>
            <form method="post" action="">
                <?php wp_nonce_field('moesec_restore_backup', 'moesec_restore_backup_nonce'); ?>
                <input type="hidden" name="backup_file" id="restore_backup_file">
                <input type="hidden" name="restore_type" id="restore_type">
                
                <p>
                    <label>
                        <input type="checkbox" id="confirm_restore" required>
                        <?php esc_html_e('I understand that this action cannot be undone', 'moesec'); ?>
                    </label>
                </p>
                
                <p>
                    <input type="submit" name="moesec_restore_backup" class="button button-primary" value="<?php esc_attr_e('Confirm Restore', 'moesec'); ?>" id="confirm_restore_btn" disabled>
                    <button type="button" class="button" onclick="hideRestoreModal()"><?php esc_html_e('Cancel', 'moesec'); ?></button>
                </p>
            </form>
        </div>
    </div>
    
    <script>
    jQuery(document).ready(function($) {
        var fileBackupInterval, dbBackupInterval;
        
        // Start file backup
        $('#moesec-start-file-backup').on('click', function() {
            $('#file-backup-progress').show();
            $('#file-backup-status').text('<?php esc_html_e('Starting backup...', 'moesec'); ?>');
            
            $.ajax({
                url: moesec_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'moesec_start_file_backup',
                    nonce: '<?php echo wp_create_nonce('moesec_backup_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        fileBackupInterval = setInterval(checkFileBackupProgress, 2000);
                    }
                }
            });
        });
        
        // Start database backup
        $('#moesec-start-db-backup').on('click', function() {
            $('#db-backup-progress').show();
            $('#db-backup-status').text('<?php esc_html_e('Starting backup...', 'moesec'); ?>');
            
            $.ajax({
                url: moesec_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'moesec_start_db_backup',
                    nonce: '<?php echo wp_create_nonce('moesec_backup_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        dbBackupInterval = setInterval(checkDbBackupProgress, 2000);
                    }
                }
            });
        });
        
        function checkFileBackupProgress() {
            $.ajax({
                url: moesec_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'moesec_backup_progress',
                    nonce: '<?php echo wp_create_nonce('moesec_backup_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        var progress = response.data.file_progress;
                        var status = response.data.file_status;
                        
                        $('#file-backup-progress .moesec-progress').css('width', progress + '%');
                        $('#file-backup-status').text(status + ' ' + progress + '%');
                        
                        if (status === 'completed' || status.indexOf('error') === 0) {
                            clearInterval(fileBackupInterval);
                            if (status === 'completed') {
                                setTimeout(function() {
                                    location.reload();
                                }, 2000);
                            }
                        }
                    }
                }
            });
        }
        
        function checkDbBackupProgress() {
            $.ajax({
                url: moesec_ajax.ajax_url,
                type: 'POST',
                data: {
                    action: 'moesec_backup_progress',
                    nonce: '<?php echo wp_create_nonce('moesec_backup_nonce'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        var progress = response.data.db_progress;
                        var status = response.data.db_status;
                        
                        $('#db-backup-progress .moesec-progress').css('width', progress + '%');
                        $('#db-backup-status').text(status + ' ' + progress + '%');
                        
                        if (status === 'completed' || status.indexOf('error') === 0) {
                            clearInterval(dbBackupInterval);
                            if (status === 'completed') {
                                setTimeout(function() {
                                    location.reload();
                                }, 2000);
                            }
                        }
                    }
                }
            });
        }
    });
    
    function showRestoreModal(filename, type) {
        document.getElementById('restore_backup_file').value = filename;
        document.getElementById('restore_type').value = type;
        document.getElementById('moesec-restore-modal').style.display = 'block';
    }
    
    function hideRestoreModal() {
        document.getElementById('moesec-restore-modal').style.display = 'none';
        document.getElementById('confirm_restore').checked = false;
        document.getElementById('confirm_restore_btn').disabled = true;
    }
    
    document.getElementById('confirm_restore').addEventListener('change', function() {
        document.getElementById('confirm_restore_btn').disabled = !this.checked;
    });
    </script>
    
    <div class="moesec-info-box" style="background: #e7f3ff; border-left: 4px solid #0073aa; padding: 15px; margin: 20px 0;">
        <h4><?php esc_html_e('Backup Information:', 'moesec'); ?></h4>
        <ul>
            <li><?php esc_html_e('Backups run in the background - you can close this page safely', 'moesec'); ?></li>
            <li><?php esc_html_e('Backups are stored in: wp-content/moesec-backups/', 'moesec'); ?></li>
            <li><?php esc_html_e('Backups are protected from direct access via .htaccess', 'moesec'); ?></li>
            <li><?php esc_html_e('Automatic cleanup keeps the last 10 backups', 'moesec'); ?></li>
            <li><?php esc_html_e('File backups use ZIP compression', 'moesec'); ?></li>
            <li><?php esc_html_e('Database backups are SQL dumps', 'moesec'); ?></li>
			<li><?php esc_html_e('Logs, Cache, Backup, Upgrade and such folders are excluded by default', 'moesec'); ?></li>

        </ul>
    </div>
    <?php
}

// Get list of backups
function moesec_get_backups() {
    $backup_dir = WP_CONTENT_DIR . '/moesec-backups';
    $backups = array();
    
    if (!is_dir($backup_dir)) {
        return $backups;
    }
    
    $files = @scandir($backup_dir);
    
    if ($files === false) {
        return $backups;
    }
    
    foreach ($files as $file) {
        if ($file === '.' || $file === '..' || $file === '.htaccess' || $file === 'index.php') {
            continue;
        }
        
        $filepath = $backup_dir . '/' . $file;
        
        if (is_file($filepath)) {
            $type = 'unknown';
            if (strpos($file, 'files-backup') !== false) {
                $type = 'files';
            } elseif (strpos($file, 'db-backup') !== false) {
                $type = 'database';
            }
            
            $backups[] = array(
                'filename' => $file,
                'type' => $type,
                'date' => date('Y-m-d H:i:s', filemtime($filepath)),
                'size' => size_format(filesize($filepath)),
                'path' => $filepath
            );
        }
    }
    
    // Sort by date, newest first
    usort($backups, function($a, $b) {
        return strcmp($b['date'], $a['date']);
    });
    
    return $backups;
}

// Create file backup with progress tracking
function moesec_create_file_backup() {
    set_time_limit(0);
	ini_set('memory_limit', '1024M'); 
    ignore_user_abort(true);
    
    $backup_dir = moesec_create_backup_directory();
    $timestamp = date('Y-m-d_H-i-s');
    $backup_file = $backup_dir . '/files-backup-' . $timestamp . '.zip';
    
    if (!class_exists('ZipArchive')) {
        return new WP_Error('zip_not_available', __('ZipArchive class is not available. Please enable ZIP extension in PHP.', 'moesec'));
    }
    
    $zip = new ZipArchive();
    
    if ($zip->open($backup_file, ZipArchive::CREATE) !== TRUE) {
        return new WP_Error('zip_creation_failed', __('Could not create ZIP file.', 'moesec'));
    }
    
    $root_path = realpath(ABSPATH);
    if ($root_path === false) {
        $zip->close();
        return new WP_Error('invalid_root', __('Could not resolve ABSPATH.', 'moesec'));
    }
    
    $files_added = 0;
    $files_skipped = 0;
    
    try {
        moesec_add_directory_to_zip($zip, $root_path, $root_path, $files_added, $files_skipped);
    } catch (Exception $e) {
        $zip->close();
        return new WP_Error('backup_failed', sprintf(__('Backup failed: %s', 'moesec'), $e->getMessage()));
    }
    
    $zip->close();
    
    moesec_cleanup_old_backups('files');
    moesec_log(sprintf(__('File backup created successfully. %d files added, %d skipped.', 'moesec'), $files_added, $files_skipped));
    
    return true;
}

function moesec_add_directory_to_zip($zip, $dir, $base_path, &$files_added, &$files_skipped) {
    $dir = rtrim($dir, '/\\');
    $base_path = rtrim($base_path, '/\\');
    
    if (!is_readable($dir) || !is_dir($dir)) {
        return;
    }
    
    $items = @scandir($dir);
    if ($items === false) {
        return;
    }
    
    $total_items = count($items);
    $processed = 0;
    
    foreach ($items as $item) {
        if ($item === '.' || $item === '..') {
            continue;
        }
        
        $processed++;
        
        // Update progress every 100 items
        if ($processed % 100 === 0) {
            $progress = min(99, round(($processed / $total_items) * 100));
            set_transient('moesec_file_backup_progress', $progress, 3600);
        }
        
        $path = $dir . '/' . $item;
        
        if (!is_readable($path)) {
            $files_skipped++;
            continue;
        }
        
        $real_path = @realpath($path);
        if ($real_path === false) {
            $files_skipped++;
            continue;
        }
        
        $skip_dirs = array('moesec-backups', 'cache', 'upgrade', 'backup', 'backups', 'tmp', 'temp', 'log', 'logs');
        $basename = basename($real_path);
        
        if (in_array($basename, $skip_dirs)) {
            continue;
        }
        
        try {
            if (is_dir($real_path)) {
                moesec_add_directory_to_zip($zip, $real_path, $base_path, $files_added, $files_skipped);
            } elseif (is_file($real_path)) {
                $relative_path = str_replace($base_path . '/', '', $real_path);
                $file_size = @filesize($real_path);
                
                if ($file_size === false || $file_size > 50 * 1024 * 1024) {
                    $files_skipped++;
                    continue;
                }
                
                if ($zip->addFile($real_path, $relative_path)) {
                    $files_added++;
                } else {
                    $files_skipped++;
                }
                
                if ($files_added % 100 === 0) {
                    @set_time_limit(30);
                }
            }
        } catch (Exception $e) {
            $files_skipped++;
            continue;
        }
    }
}

// Create database backup with progress tracking
function moesec_create_database_backup() {
    global $wpdb;
    
    $backup_dir = moesec_create_backup_directory();
    $timestamp = date('Y-m-d_H-i-s');
    $backup_file = $backup_dir . '/db-backup-' . $timestamp . '.sql';
    
    ob_start();
    
    $tables = $wpdb->get_results('SHOW TABLES', ARRAY_N);
    $total_tables = count($tables);
    $processed_tables = 0;
    
    $sql_dump = "-- MoeSec Database Backup\n";
    $sql_dump .= "-- Date: " . date('Y-m-d H:i:s') . "\n";
    $sql_dump .= "-- Database: " . DB_NAME . "\n";
    $sql_dump .= "-- WordPress Version: " . get_bloginfo('version') . "\n\n";
    $sql_dump .= "SET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\n";
    $sql_dump .= "SET time_zone = \"+00:00\";\n\n";
    
    foreach ($tables as $table) {
        $table_name = $table[0];
        $processed_tables++;
        
        $progress = round(($processed_tables / $total_tables) * 100);
        set_transient('moesec_db_backup_progress', $progress, 3600);
        
        $create_table = $wpdb->get_row("SHOW CREATE TABLE `{$table_name}`", ARRAY_N);
        $sql_dump .= "\n\n-- Table: {$table_name}\n";
        $sql_dump .= "DROP TABLE IF EXISTS `{$table_name}`;\n";
        $sql_dump .= $create_table[1] . ";\n\n";
        
        $rows = $wpdb->get_results("SELECT * FROM `{$table_name}`", ARRAY_A);
        
        if (!empty($rows)) {
            $sql_dump .= "-- Data for table `{$table_name}`\n\n";
            
            foreach ($rows as $row) {
                $values = array();
                foreach ($row as $value) {
                    if (is_null($value)) {
                        $values[] = 'NULL';
                    } else {
                        $values[] = "'" . $wpdb->_real_escape($value) . "'";
                    }
                }
                $sql_dump .= "INSERT INTO `{$table_name}` VALUES (" . implode(', ', $values) . ");\n";
            }
            
            $sql_dump .= "\n";
        }
    }
    
    $result = file_put_contents($backup_file, $sql_dump);
    ob_end_clean();
    
    if ($result === false) {
        return new WP_Error('write_failed', __('Failed to write database backup file.', 'moesec'));
    }
    
    moesec_cleanup_old_backups('database');
    moesec_log(__('Database backup created successfully', 'moesec'));
    
    return true;
}

// Download backup
function moesec_download_backup($filename) {
    while (ob_get_level()) {
        ob_end_clean();
    }
    
    $backup_dir = WP_CONTENT_DIR . '/moesec-backups';
    $filepath = $backup_dir . '/' . $filename;
    
    if (!file_exists($filepath)) {
        wp_die(esc_html__('Backup file not found.', 'moesec'));
    }
    
    @ini_set('display_errors', 0);
    
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
    header('Content-Length: ' . filesize($filepath));
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: public');
    header('Expires: 0');
    
    readfile($filepath);
    exit;
}

// Delete backup
function moesec_delete_backup($filename) {
    $backup_dir = WP_CONTENT_DIR . '/moesec-backups';
    $filepath = $backup_dir . '/' . $filename;
    
    if (file_exists($filepath)) {
        $result = unlink($filepath);
        if ($result) {
            moesec_log(sprintf(__('Backup deleted: %s', 'moesec'), $filename));
        }
        return $result;
    }
    
    return false;
}

// Restore backup
function moesec_restore_backup($filename, $type) {
    global $wpdb;
    
    $backup_dir = WP_CONTENT_DIR . '/moesec-backups';
    $filepath = $backup_dir . '/' . $filename;
    
    if (!file_exists($filepath)) {
        return new WP_Error('file_not_found', __('Backup file not found.', 'moesec'));
    }
    
    set_time_limit(0);
    
    if ($type === 'files') {
        if (!class_exists('ZipArchive')) {
            return new WP_Error('zip_not_available', __('ZipArchive class is not available.', 'moesec'));
        }
        
        $zip = new ZipArchive();
        if ($zip->open($filepath) !== TRUE) {
            return new WP_Error('zip_open_failed', __('Could not open ZIP file.', 'moesec'));
        }
        
        $zip->extractTo(ABSPATH);
        $zip->close();
        
        moesec_log(__('Files restored from backup', 'moesec'));
        
    } elseif ($type === 'database') {
        $sql = file_get_contents($filepath);
        
        if (empty($sql)) {
            return new WP_Error('empty_sql', __('SQL file is empty.', 'moesec'));
        }
        
        $queries = explode(";\n", $sql);
        
        foreach ($queries as $query) {
            $query = trim($query);
            if (!empty($query) && substr($query, 0, 2) !== '--') {
                $result = $wpdb->query($query);
                if ($result === false) {
                    return new WP_Error('query_failed', __('Database restore failed: You may download the backup files and try restoring manually or ask your hosting support for assistance. ', 'moesec') . $wpdb->last_error);
                }
            }
        }
        
        moesec_log(__('Database restored from backup', 'moesec'));
    }
    
    return true;
}

// Cleanup old backups
function moesec_cleanup_old_backups($type) {
    $backup_dir = WP_CONTENT_DIR . '/moesec-backups';
    $backups = array();
    
    $files = @scandir($backup_dir);
    if ($files === false) {
        return;
    }
    
    foreach ($files as $file) {
        if ($file === '.' || $file === '..' || $file === '.htaccess' || $file === 'index.php') {
            continue;
        }
        
        if ($type === 'files' && strpos($file, 'files-backup') !== false) {
            $backups[] = $backup_dir . '/' . $file;
        } elseif ($type === 'database' && strpos($file, 'db-backup') !== false) {
            $backups[] = $backup_dir . '/' . $file;
        }
    }
    
    usort($backups, function($a, $b) {
        return filemtime($b) - filemtime($a);
    });
    
    if (count($backups) > 10) {
        $backups_to_delete = array_slice($backups, 10);
        foreach ($backups_to_delete as $backup) {
            @unlink($backup);
        }
    }
}

function moesec_schedule_automatic_backups() {
    $enable_auto_backup = get_option('moesec_enable_auto_backup', false);
    $backup_frequency = get_option('moesec_backup_frequency', 'weekly');
    
    wp_clear_scheduled_hook('moesec_auto_backup');
    
    if ($enable_auto_backup) {
        $recurrence = 'daily';
        if ($backup_frequency === 'weekly') {
            $recurrence = 'weekly';
        } elseif ($backup_frequency === 'monthly') {
            $recurrence = 'monthly';
        }
        
        wp_schedule_event(time(), $recurrence, 'moesec_auto_backup');
        moesec_log('✓ Automatic backups ENABLED: ' . $recurrence . ' frequency - Cron job created');
    } else {
        moesec_log('✓ Automatic backups DISABLED - Cron job removed');
    }
}

// Perform automatic backup
add_action('moesec_auto_backup', 'moesec_perform_auto_backup');
function moesec_perform_auto_backup() {
    wp_schedule_single_event(time(), 'moesec_background_file_backup');
    wp_schedule_single_event(time() + 60, 'moesec_background_db_backup');
    moesec_log(__('Automatic backup scheduled', 'moesec'));
}

// Add custom cron schedules
add_filter('cron_schedules', 'moesec_add_cron_schedules');
function moesec_add_cron_schedules($schedules) {
    if (!isset($schedules['weekly'])) {
        $schedules['weekly'] = array(
            'interval' => 604800,
            'display' => __('Once Weekly', 'moesec')
        );
    }
    if (!isset($schedules['monthly'])) {
        $schedules['monthly'] = array(
            'interval' => 2592000,
            'display' => __('Once Monthly', 'moesec')
        );
    }
    return $schedules;
}

?>
