<?php
/**
 * ComptaFlow UK - Backup & Restore Screen
 * Version 1.0.0
 */

namespace ComptaFlowUK\Admin\Screens;

use ComptaFlowUK\Services\BackupService;

defined('ABSPATH') || exit;

class BackupScreen {
    
    public static function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('Insufficient permissions.', 'comptaflow-uk-by-meetempo'));
        }
        
        // Process actions
        self::handleActions();
        
        // Get info
        $tables = BackupService::getTables();
        $stats = BackupService::getTablesStats();
        $estimated_size = BackupService::getEstimatedSize();
        
        echo '<div class="wrap">';
        echo '<h1>💾 ' . esc_html__('Backup & Restore', 'comptaflow-uk-by-meetempo') . '</h1>';
        
        // Messages
        self::showMessages();
        
        // Section Export
        self::renderExportSection($tables, $stats, $estimated_size);
        
        // Section Import
        self::renderImportSection();
        
        // Instructions phpMyAdmin (collapsible)
        self::renderPhpMyAdminInstructions($tables);
        
        // Factory Reset
        self::renderFactoryReset();
        
        echo '</div>';
    }
    
    /**
     * Export section (1-click)
     */
    private static function renderExportSection(array $tables, array $stats, int $estimated_size): void {
        $total_rows = array_sum($stats);
        
        echo '<div style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4; border-left: 4px solid #00a32a;">';
        echo '<h2 style="margin-top: 0;">📥 ' . esc_html__('Create a backup', 'comptaflow-uk-by-meetempo') . '</h2>';
        
        echo '<div style="display: flex; gap: 20px; flex-wrap: wrap; margin-bottom: 20px;">';
        
        // Stats
        echo '<div style="background: #f0f7ff; padding: 15px; border-radius: 5px; flex: 1; min-width: 200px;">';
        echo '<div style="font-size: 24px; font-weight: bold; color: #0073aa;">' . count($tables) . '</div>';
        echo '<div style="color: #666;">' . esc_html__('Tables', 'comptaflow-uk-by-meetempo') . '</div>';
        echo '</div>';
        
        echo '<div style="background: #f0f7ff; padding: 15px; border-radius: 5px; flex: 1; min-width: 200px;">';
        echo '<div style="font-size: 24px; font-weight: bold; color: #0073aa;">' . esc_html(number_format($total_rows, 0, '.', ',')) . '</div>';
        echo '<div style="color: #666;">' . esc_html__('Records', 'comptaflow-uk-by-meetempo') . '</div>';
        echo '</div>';
        
        echo '<div style="background: #f0f7ff; padding: 15px; border-radius: 5px; flex: 1; min-width: 200px;">';
        echo '<div style="font-size: 24px; font-weight: bold; color: #0073aa;">' . esc_html(BackupService::formatSize($estimated_size)) . '</div>';
        echo '<div style="color: #666;">' . esc_html__('Estimated size', 'comptaflow-uk-by-meetempo') . '</div>';
        echo '</div>';
        
        echo '</div>';
        
        // Table details
        echo '<details style="margin-bottom: 20px;">';
        echo '<summary style="cursor: pointer; color: #0073aa; font-weight: 600;">📋 ' . esc_html__('View table details', 'comptaflow-uk-by-meetempo') . ' (' . count($tables) . ')</summary>';
        echo '<div style="background: #f9f9f9; padding: 15px; margin-top: 10px; border-radius: 5px;">';
        echo '<table style="width: 100%; border-collapse: collapse;">';
        echo '<thead><tr><th style="text-align: left; padding: 5px; border-bottom: 1px solid #ddd;">' . esc_html__('Table', 'comptaflow-uk-by-meetempo') . '</th><th style="text-align: right; padding: 5px; border-bottom: 1px solid #ddd;">' . esc_html__('Rows', 'comptaflow-uk-by-meetempo') . '</th></tr></thead>';
        echo '<tbody>';
        foreach ($stats as $table => $count) {
            echo '<tr>';
            echo '<td style="padding: 5px; font-family: monospace; font-size: 12px;">' . esc_html($table) . '</td>';
            echo '<td style="padding: 5px; text-align: right;">' . esc_html(number_format($count, 0, '.', ',')) . '</td>';
            echo '</tr>';
        }
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        echo '</details>';
        
        // Export button
        echo '<div style="margin-top: 20px;">';
        echo '<a href="' . esc_url(BackupService::getDownloadUrl()) . '" class="button button-primary button-hero" style="background: #00a32a; border-color: #00a32a;">';
        echo '💾 ' . esc_html__('Download backup (.sql)', 'comptaflow-uk-by-meetempo');
        echo '</a>';
        echo '</div>';
        
        echo '<div style="background: #fff3cd; padding: 15px; border-left: 4px solid #856404; margin-top: 20px;">';
        echo '<p style="margin: 0;"><strong>💡 ' . esc_html__('Recommendations:', 'comptaflow-uk-by-meetempo') . '</strong></p>';
        echo '<ul style="margin: 10px 0 0 20px;">';
        echo '<li>' . esc_html__('Back up before each plugin update', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Back up at the end of each month (minimum)', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Keep backups on multiple media (Cloud, hard drive, USB drive)', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '</ul>';
        echo '</div>';
        
        echo '</div>';
    }
    
    /**
     * Import/Restore section
     */
    private static function renderImportSection(): void {
        echo '<div style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4; border-left: 4px solid #d63638;">';
        echo '<h2 style="margin-top: 0;">📤 ' . esc_html__('Restore a backup', 'comptaflow-uk-by-meetempo') . '</h2>';
        
        // Warning
        echo '<div style="background: #f8d7da; padding: 15px; border-radius: 5px; margin-bottom: 20px;">';
        echo '<h3 style="margin-top: 0; color: #721c24;">⚠️ ' . esc_html__('WARNING - Irreversible operation', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<ul style="color: #721c24; margin-bottom: 0;">';
        echo '<li>' . esc_html__('The restore will overwrite ALL your current data', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('This action cannot be undone', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Create a backup of the current state BEFORE restoring', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '</ul>';
        echo '</div>';
        
        // Upload form
        echo '<form method="post" enctype="multipart/form-data" id="restore-form">';
        wp_nonce_field('comptaflow_uk_restore', 'restore_nonce');
        echo '<input type="hidden" name="action" value="restore_backup">';
        
        echo '<div style="display: flex; gap: 15px; align-items: flex-end; flex-wrap: wrap;">';
        
        echo '<div>';
        echo '<label style="display: block; margin-bottom: 5px; font-weight: 600;">' . esc_html__('Backup file (.sql)', 'comptaflow-uk-by-meetempo') . '</label>';
        echo '<input type="file" name="backup_file" accept=".sql" required style="padding: 10px; border: 2px dashed #ccc; border-radius: 5px;">';
        echo '</div>';
        
        echo '<div>';
        echo '<label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">';
        echo '<input type="checkbox" name="confirm_restore" value="1" required>';
        echo '<span style="color: #d63638; font-weight: 600;">' . esc_html__('I confirm I want to overwrite my current data', 'comptaflow-uk-by-meetempo') . '</span>';
        echo '</label>';
        echo '</div>';
        
        echo '</div>';
        
        echo '<div style="margin-top: 20px;">';
        echo '<button type="submit" class="button button-secondary button-hero" style="background: #d63638; color: #fff; border-color: #d63638;" onclick="return confirm(\'' . esc_js(__('Are you ABSOLUTELY SURE you want to restore? This action is IRREVERSIBLE!', 'comptaflow-uk-by-meetempo')) . '\');">';
        echo '📤 ' . esc_html__('Restore backup', 'comptaflow-uk-by-meetempo');
        echo '</button>';
        echo '</div>';
        
        echo '</form>';
        
        echo '</div>';
    }
    
    /**
     * phpMyAdmin instructions (collapsible)
     */
    private static function renderPhpMyAdminInstructions(array $tables): void {
        echo '<details style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4;">';
        echo '<summary style="cursor: pointer; font-size: 16px; font-weight: 600;">📖 ' . esc_html__('Manual instructions (phpMyAdmin)', 'comptaflow-uk-by-meetempo') . '</summary>';
        
        echo '<div style="margin-top: 20px;">';
        
        // Manual export
        echo '<h3>' . esc_html__('Export manually:', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<ol style="line-height: 1.8;">';
        echo '<li>' . esc_html__('Log in to phpMyAdmin', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Select your WordPress database', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Click the "Export" tab', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Choose "Custom" method', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Select the tables', 'comptaflow-uk-by-meetempo') . ' <code>wp_cfuk_*</code></li>';
        echo '<li>' . esc_html__('Format: SQL', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Click "Go"', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '</ol>';
        
        // Manual import
        echo '<h3>' . esc_html__('Import manually:', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<ol style="line-height: 1.8;">';
        echo '<li>' . esc_html__('Log in to phpMyAdmin', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Select your WordPress database', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Click the "Import" tab', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Choose your .sql file', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Click "Go"', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '</ol>';
        
        // Table list
        echo '<h3>' . esc_html__('ComptaFlow UK Tables:', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<div style="background: #f9f9f9; padding: 10px; font-family: monospace; font-size: 12px; max-height: 200px; overflow-y: auto;">';
        foreach ($tables as $table) {
            echo esc_html($table) . '<br>';
        }
        echo '</div>';
        
        echo '</div>';
        echo '</details>';
    }
    
    /**
     * Factory reset section
     */
    private static function renderFactoryReset(): void {
        echo '<details style="background: #fff; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4;">';
        echo '<summary style="cursor: pointer; font-size: 16px; font-weight: 600; color: #d63638;">🔄 ' . esc_html__('Factory Reset', 'comptaflow-uk-by-meetempo') . '</summary>';
        
        echo '<div style="margin-top: 20px;">';
        
        echo '<div style="background: #dc3545; color: white; padding: 20px; border-radius: 5px;">';
        echo '<h3 style="color: white; margin-top: 0;">⚠️ ' . esc_html__('DANGER - Total and irreversible data loss', 'comptaflow-uk-by-meetempo') . '</h3>';
        echo '<p>' . esc_html__('To return to a fresh installation:', 'comptaflow-uk-by-meetempo') . '</p>';
        echo '<ol style="color: white;">';
        echo '<li>' . esc_html__('Go to Plugins → Installed Plugins', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Find ComptaFlow UK', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Click Deactivate', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '<li>' . esc_html__('Then click Delete', 'comptaflow-uk-by-meetempo') . '</li>';
        echo '</ol>';
        echo '<p><strong>⚠️ ' . esc_html__('This action will PERMANENTLY delete all your accounting data.', 'comptaflow-uk-by-meetempo') . '</strong></p>';
        echo '</div>';
        
        echo '</div>';
        echo '</details>';
    }
    
    /**
     * Handle POST actions
     */
    private static function handleActions(): void {
        $post_action = isset($_POST['action']) ? sanitize_text_field(wp_unslash($_POST['action'])) : '';
        if ($post_action === 'restore_backup') {
            // Verify nonce
            $restore_nonce = isset($_POST['restore_nonce']) ? sanitize_text_field(wp_unslash($_POST['restore_nonce'])) : '';
            if (!wp_verify_nonce($restore_nonce, 'comptaflow_uk_restore')) {
                add_settings_error('comptaflow_uk_backup', 'nonce_error', __('Security error. Please try again.', 'comptaflow-uk-by-meetempo'), 'error');
                return;
            }
            
            // Verify confirmation
            if (empty($_POST['confirm_restore'])) {
                add_settings_error('comptaflow_uk_backup', 'confirm_error', __('You must tick the confirmation checkbox.', 'comptaflow-uk-by-meetempo'), 'error');
                return;
            }
            
            // Verify file
            if (empty($_FILES['backup_file']) || $_FILES['backup_file']['error'] !== UPLOAD_ERR_OK) {
                add_settings_error('comptaflow_uk_backup', 'file_error', __('Error uploading the file.', 'comptaflow-uk-by-meetempo'), 'error');
                return;
            }
            
            // Verify extension
            $file_name = $_FILES['backup_file']['name'];
            if (pathinfo($file_name, PATHINFO_EXTENSION) !== 'sql') {
                add_settings_error('comptaflow_uk_backup', 'ext_error', __('The file must be in .sql format', 'comptaflow-uk-by-meetempo'), 'error');
                return;
            }
            
            // Restore
            $result = BackupService::restore($_FILES['backup_file']['tmp_name']);
            
            if ($result['success']) {
                add_settings_error('comptaflow_uk_backup', 'success', $result['message'] . ' (' . $result['queries'] . ' ' . __('queries executed', 'comptaflow-uk-by-meetempo') . ')', 'updated');
            } else {
                add_settings_error('comptaflow_uk_backup', 'restore_error', $result['message'], 'error');
            }
        }
    }
    
    /**
     * Display messages
     */
    private static function showMessages(): void {
        settings_errors('comptaflow_uk_backup');
    }
}
