<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;

/**
 * @var yii\web\View $this
 */
$this->title = 'Configure Database Backup Module';
$this->params['breadcrumbs'][] = ['label' => 'Setup', 'url' => ['setup/index']];
$this->params['breadcrumbs'][] = $this->title;

// Generate URLs before the heredoc
$generateKeyUrl = Url::to(['setup/generate-key']);
$getSystemIdUrl = Url::to(['setup/get-system-id']);
$testEncryptionUrl = Url::to(['setup/test-encryption']);
$saveConfigUrl = Url::to(['setup/save-config']);

$this->registerJs(<<<JS
\$(document).ready(function() {
    // Generate Key button
    \$('#btn-generate-key').on('click', function() {
        \$.ajax({
            type: 'POST',
            url: '{$generateKeyUrl}',
            dataType: 'json',
            beforeSend: function() {
                \$('#btn-generate-key').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Generating...');
                \$('#key-error').hide();
            },
            success: function(response) {
                if (response.success) {
                    \$('#encryptionKey').val(response.key);
                    \$('#key-display').val(response.base64).select();
                    \$('#key-success').show().delay(5000).fadeOut();
                } else {
                    \$('#key-error').text('Error: ' + response.error).show();
                }
            },
            error: function() {
                \$('#key-error').text('Error generating key. Please try again.').show();
            },
            complete: function() {
                \$('#btn-generate-key').prop('disabled', false).html('<i class="fa fa-key"></i> Generate New Key');
            }
        });
    });

    // Get System ID button
    \$('#btn-get-systemid').on('click', function() {
        \$.ajax({
            type: 'POST',
            url: '{$getSystemIdUrl}',
            dataType: 'json',
            beforeSend: function() {
                \$('#btn-get-systemid').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Retrieving...');
                \$('#systemid-error').hide();
            },
            success: function(response) {
                if (response.success) {
                    \$('#systemId').val(response.systemId);
                    \$('#systemid-success').show().delay(5000).fadeOut();
                } else {
                    \$('#systemid-error').text('Error: ' + response.error).show();
                }
            },
            error: function() {
                \$('#systemid-error').text('Error retrieving system ID. Please try again.').show();
            },
            complete: function() {
                \$('#btn-get-systemid').prop('disabled', false).html('<i class="fa fa-server"></i> Get System ID');
            }
        });
    });

    // Test Encryption button
    \$('#btn-test-encryption').on('click', function() {
        if (!validateSettings()) {
            return;
        }
        
        \$.ajax({
            type: 'POST',
            url: '{$testEncryptionUrl}',
            data: {
                encryptionKey: \$('#encryptionKey').val(),
                systemId: \$('#systemId').val()
            },
            dataType: 'json',
            beforeSend: function() {
                \$('#btn-test-encryption').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Testing...');
                \$('#test-result').html('').hide();
            },
            success: function(response) {
                if (response.success) {
                    \$('#test-result')
                        .html('<div class="alert alert-success"><i class="fa fa-check-circle"></i> <strong>Encryption test passed!</strong><br>Overhead: ' + response.overheadBytes + ' bytes</div>')
                        .show();
                } else {
                    \$('#test-result')
                        .html('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <strong>Encryption test failed:</strong> ' + response.error + '</div>')
                        .show();
                }
            },
            error: function() {
                \$('#test-result')
                    .html('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> Error testing encryption. Please try again.</div>')
                    .show();
            },
            complete: function() {
                \$('#btn-test-encryption').prop('disabled', false).html('<i class="fa fa-flask"></i> Test Encryption');
            }
        });
    });

    // Save Configuration button
    \$('#btn-save-config').on('click', function() {
        if (!validateSettings()) {
            return;
        }
        
        \$.ajax({
            type: 'POST',
            url: '{$saveConfigUrl}',
            data: {
                encryptionEnabled: \$('#encryptionEnabled').is(':checked') ? 1 : 0,
                encryptionKey: \$('#encryptionKey').val(),
                systemId: \$('#systemId').val(),
                authorizedSystems: \$('#authorizedSystems').val()
            },
            dataType: 'json',
            beforeSend: function() {
                \$('#btn-save-config').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Saving...');
                \$('#config-result').html('').hide();
            },
            success: function(response) {
                if (response.success) {
                    var resultHtml = '<div class="alert alert-success">';
                    resultHtml += '<i class="fa fa-check-circle"></i> <strong>Configuration Saved!</strong><br>';
                    resultHtml += '<small>';
                    if (response.envWritten) {
                        resultHtml += '✓ Encryption key saved to <code>.env.local</code><br>';
                        resultHtml += '✓ Configuration saved to <code>' + response.filePath + '</code><br>';
                        resultHtml += 'Setup is complete! Your backup module is ready to use.';
                    } else {
                        resultHtml += '✓ Configuration saved to <code>' + response.filePath + '</code><br>';
                        resultHtml += '<strong style="color: #856404;">Manual Step Required:</strong> Add this to your server environment or .env file:<br>';
                        resultHtml += '<code style="display: block; background: #fff3cd; padding: 8px; margin: 8px 0; border-radius: 3px;">DB_BACKUP_ENCRYPTION_KEY=' + escapeHtml(response.encryptionKey) + '</code>';
                    }
                    resultHtml += '</small></div>';
                    
                    \$('#config-output').val(response.config).select();
                    \$('#config-result').html(resultHtml).show();
                } else {
                    \$('#config-result')
                        .html('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> <strong>Error:</strong> ' + response.error + '</div>')
                        .show();
                }
            },
            error: function() {
                \$('#config-result')
                    .html('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> Error saving configuration. Please try again.</div>')
                    .show();
            },
            complete: function() {
                \$('#btn-save-config').prop('disabled', false).html('<i class="fa fa-save"></i> Save Configuration');
            }
        });
    });
    
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return text.replace(/[&<>"']/g, function(m) { return map[m]; });
    }

    // Add System ID to Authorized Systems
    \$('#btn-add-systemid').on('click', function() {
        var systemId = \$('#systemId').val().trim();
        
        if (!systemId) {
            alert('Please retrieve the system ID first.');
            return;
        }
        
        var textarea = \$('#authorizedSystems');
        var currentValue = textarea.val().trim();
        
        // Check if system ID already exists
        if (currentValue.includes(systemId)) {
            \$('#add-systemid-error').text('System ID is already in the authorized list.').show().delay(3000).fadeOut();
            return;
        }
        
        // Add system ID to the list
        var newValue = currentValue ? currentValue + (currentValue.endsWith(String.fromCharCode(10)) ? '' : String.fromCharCode(10)) + systemId : systemId;
        textarea.val(newValue);
        
        \$('#add-systemid-success').show().delay(3000).fadeOut();
    });

    // Encryption toggle

    \$('#encryptionEnabled').on('change', function() {
        var enabled = \$(this).is(':checked');
        \$('.encryption-settings').toggleClass('disabled', !enabled).find('input, textarea, button').prop('disabled', !enabled);
    });

    // Initial state
    var encryptionEnabled = \$('#encryptionEnabled').is(':checked');
    \$('.encryption-settings').toggleClass('disabled', !encryptionEnabled).find('input, textarea, button').prop('disabled', !encryptionEnabled);
    
    function validateSettings() {
        if (!document.getElementById('encryptionEnabled').checked) {
            alert('Encryption must be enabled for setup.');
            return false;
        }
        
        if (\$('#encryptionKey').val().trim() === '') {
            alert('Please generate an encryption key first.');
            return false;
        }
        
        if (\$('#systemId').val().trim() === '') {
            alert('Please retrieve the system ID first.');
            return false;
        }
        
        return true;
    }
});

function validateSettings() {
    if (!document.getElementById('encryptionEnabled').checked) {
        alert('Encryption must be enabled for setup.');
        return false;
    }
    
    if (\$('#encryptionKey').val().trim() === '') {
        alert('Please generate an encryption key first.');
        return false;
    }
    
    if (\$('#systemId').val().trim() === '') {
        alert('Please retrieve the system ID first.');
        return false;
    }
    
    return true;
}
JS
);

?>

<div class="setup-configure">
    <div class="row">
        <div class="col-lg-12">
            
            <!-- Next Steps Card -->
            <div class="card mb-4">
                <div class="card-header bg-info text-white">
                    <h5 class="card-title mb-0">
                        <i class="fa fa-info-circle"></i> Setup Steps
                    </h5>
                </div>
                <div class="card-body">
                    <ol class="mb-0">
                        <li>Click <strong>Generate Key</strong> to create an encryption key</li>
                        <li>Click <strong>Get System ID</strong> to retrieve your system identifier</li>
                        <li>(Optional) Add authorized system IDs if needed</li>
                        <li>Click <strong>Test Encryption</strong> to verify everything works</li>
                        <li>Click <strong>Save Configuration</strong> - it will be automatically saved to <code>/common/config/backup.php</code></li>
                        <li>That's it! Your backup module is now configured and ready to use</li>
                    </ol>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h3 class="card-title mb-0">
                        <i class="fa fa-cogs"></i> Module Configuration
                    </h3>
                </div>
                <div class="card-body">

                    <!-- Encryption Enable/Disable -->
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" class="custom-control-input" id="encryptionEnabled" checked>
                            <label class="custom-control-label" for="encryptionEnabled">
                                <strong>Enable Encryption</strong>
                                <small class="text-muted d-block">Encrypt backups with AES-256-GCM encryption</small>
                            </label>
                        </div>
                    </div>

                    <hr>

                    <!-- Encryption Settings Section -->
                    <div class="encryption-settings">

                        <!-- Generate Key Section -->
                        <div class="form-group">
                            <label for="encryptionKey" class="font-weight-bold">
                                <i class="fa fa-key"></i> Encryption Key
                            </label>
                            <div class="input-group mb-2">
                                <input type="hidden" id="encryptionKey" value="">
                                <input type="text" id="key-display" class="form-control" placeholder="Generated key will appear here" readonly>
                                <div class="input-group-append">
                                    <button type="button" id="btn-generate-key" class="btn btn-outline-secondary">
                                        <i class="fa fa-key"></i> Generate New Key
                                    </button>
                                </div>
                            </div>
                            <small class="form-text text-muted">
                                Click to generate a secure 256-bit encryption key. Keep this key safe!
                            </small>
                            <div id="key-error" class="alert alert-danger mt-2" style="display: none;"></div>
                            <div id="key-success" class="alert alert-success mt-2" style="display: none;">
                                <i class="fa fa-check-circle"></i> Key generated successfully!
                            </div>
                        </div>

                        <!-- System ID Section -->
                        <div class="form-group">
                            <label for="systemId" class="font-weight-bold">
                                <i class="fa fa-server"></i> System ID
                            </label>
                            <div class="input-group mb-2">
                                <input type="text" id="systemId" class="form-control" placeholder="System ID will appear here" readonly>
                                <div class="input-group-append">
                                    <button type="button" id="btn-get-systemid" class="btn btn-outline-secondary">
                                        <i class="fa fa-server"></i> Get System ID
                                    </button>
                                    <button type="button" id="btn-add-systemid" class="btn btn-outline-success" title="Add this system ID to authorized systems">
                                        <i class="fa fa-plus"></i> Add to List
                                    </button>
                                </div>
                            </div>
                            <small class="form-text text-muted">
                                This uniquely identifies your system. Backups encrypted on this system can only be restored on authorized systems.
                            </small>
                            <div id="systemid-error" class="alert alert-danger mt-2" style="display: none;"></div>
                            <div id="add-systemid-success" class="alert alert-success mt-2" style="display: none;">
                                <i class="fa fa-check-circle"></i> System ID added to authorized systems!
                            </div>
                            <div id="add-systemid-error" class="alert alert-warning mt-2" style="display: none;"></div>
                            <div id="systemid-success" class="alert alert-success mt-2" style="display: none;">
                                <i class="fa fa-check-circle"></i> System ID retrieved successfully!
                            </div>
                        </div>

                        <!-- Authorized Systems Section -->
                        <div class="form-group">
                            <label for="authorizedSystems" class="font-weight-bold">
                                <i class="fa fa-shield-alt"></i> Authorized Systems (Optional)
                            </label>
                            <textarea id="authorizedSystems" class="form-control" rows="4" placeholder="Enter one system ID per line&#10;Leave empty to allow restoration only on this system"></textarea>
                            <small class="form-text text-muted">
                                List additional system IDs that should be able to restore backups encrypted on this system.
                                Leave empty if only this system will restore backups.
                            </small>
                        </div>

                        <!-- Test Encryption Section -->
                        <div class="form-group">
                            <label class="font-weight-bold">
                                <i class="fa fa-flask"></i> Test Encryption
                            </label>
                            <button type="button" id="btn-test-encryption" class="btn btn-warning btn-block">
                                <i class="fa fa-flask"></i> Test Encryption
                            </button>
                            <small class="form-text text-muted d-block mt-2">
                                Tests that encryption and decryption work correctly with your settings.
                            </small>
                            <div id="test-result" style="display: none;"></div>
                        </div>

                    </div>

                    <hr>

                    <!-- Configuration Output Section -->
                    <div class="form-group">
                        <label for="config-output" class="font-weight-bold">
                            <i class="fa fa-code"></i> Configuration Code
                        </label>
                        <button type="button" id="btn-save-config" class="btn btn-primary btn-block mb-2">
                            <i class="fa fa-save"></i> Save Configuration
                        </button>
                        <textarea id="config-output" class="form-control font-monospace" rows="12" placeholder="Configuration will appear here after saving" readonly style="font-size: 12px;"></textarea>
                        <small class="form-text text-muted d-block mt-2">
                            Configuration is automatically saved to <code>/common/config/backup.php</code> or your app's config directory. The code is shown here for your reference.
                        </small>
                        <div id="config-result" style="display: none;"></div>
                    </div>

                </div>
            </div>

            <!-- Security Notes Card -->
            <div class="card mt-4">
                <div class="card-header bg-warning">
                    <h5 class="card-title mb-0">
                        <i class="fa fa-exclamation-triangle"></i> Security Notes
                    </h5>
                </div>
                <div class="card-body small">
                    <ul class="mb-0">
                        <li><strong>Key Protection:</strong> Store your encryption key in a secure location (environment variables recommended).</li>
                        <li><strong>Key Loss:</strong> Without the encryption key, encrypted backups cannot be decrypted.</li>
                        <li><strong>Multi-System:</strong> Each system must have the same encryption key to restore each other's backups.</li>
                        <li><strong>Authorized Systems:</strong> System IDs must be added to <code>authorizedSystems</code> array for cross-system restoration.</li>
                        <li><strong>Backup Key:</strong> Backup your encryption key separately from your database backups.</li>
                    </ul>
                </div>
            </div>

        </div>
    </div>
</div>

<style>
.encryption-settings.disabled {
    opacity: 0.6;
    pointer-events: none;
}

.font-monospace {
    font-family: 'Courier New', monospace;
}

.custom-control-label {
    cursor: pointer;
}
</style>
