<?php

use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\Pjax;
use yii\web\View;
use common\widgets\GridView;
use yii\data\ArrayDataProvider;
/** 
 * @var View $this
 * @var array $tables
 * @var array $restorePoints
 * @var array $statistics
 */

$this->title = 'Database Backup & Restore';
$this->params['breadcrumbs'][] = $this->title;

$this->registerCss("
.backup-index {
    margin-bottom: 20px;
}
.backup-stats {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 4px;
    margin-bottom: 20px;
}
.backup-stats .stat-item {
    display: inline-block;
    margin-right: 30px;
}
.backup-stats .stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #007bff;
}
.backup-stats .stat-label {
    font-size: 12px;
    color: #6c757d;
}
.restore-points-expandable {
    margin-top: 10px;
    background: #f8f9fa;
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 10px;
    max-height: 300px;
    overflow-y: auto;
}
.restore-point-item {
    padding: 8px;
    border-bottom: 1px solid #dee2e6;
    font-size: 12px;
}
.restore-point-item:last-child {
    border-bottom: none;
}
.restore-point-item .restore-actions {
    margin-top: 5px;
}
.restore-actions .btn {
    padding: 2px 6px;
    font-size: 11px;
    margin-right: 3px;
}
.loading {
    display: none;
    text-align: center;
    padding: 20px;
    color: #6c757d;
}
.table-row-loading {
    opacity: 0.5;
}
.fixed-bottom-button {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 15px;
    background: #fff;
    border-top: 2px solid #007bff;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
    z-index: 1000;
    text-align: center;
}
.backup-index {
    padding-bottom: 80px;
}
");

?>

<div class="backup-index">
    <div class="row">
        <div class="col-12 col-md-6">
            <div class="card">
                <div class="card-header bg-info text-white">
                    Backup Statistics
                </div>
                <div class="card-body backup-stats mb-0">
                    <div class="stat-item">
                        <div class="stat-value"><?= $statistics['total_backups'] ?></div>
                        <div class="stat-label">Total Backups</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?= $statistics['total_restores'] ?></div>
                        <div class="stat-label">Restores</div>
                    </div>
                    <div class="stat-item">
                        <div class="stat-value"><?= Yii::$app->formatter->asShortSize($statistics['total_size']) ?></div>
                        <div class="stat-label">Total Size</div>
                    </div>
                    <?php if ($statistics['latest_backup']): ?>
                        <div class="stat-item">
                            <div class="stat-value"><?= Yii::$app->formatter->asRelativeTime($statistics['latest_backup']->created_at) ?></div>
                            <div class="stat-label">Latest Backup</div>
                        </div>
                    <?php endif; ?>
                    
                </div>
            </div>
        </div>
        <div class="col-12 col-md-6">


    <!-- Backup Options & Actions -->
            <div style="margin-bottom: 20px; padding: 15px; background: #fff; border-radius: 4px; border: 1px solid #dee2e6;">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group mb-0">
                            <label>
                                <input type="checkbox" id="compress-backup" checked>
                                <strong>Compress backups (gzip)</strong>
                            </label>
                        </div>
                    </div>
                    <div class="col-md-8 text-right">
                        <a href="<?= Url::to(['/db-backup/setup/configure']) ?>" class="btn btn-outline-primary">
                            <i class="fa fa-cog"></i> Settings
                        </a>
                        <button type="button" id="btn-cleanup" class="btn btn-warning">
                            <i class="fa fa-trash-o"></i> Cleanup Old Backups
                        </button>
                        <a href="<?= Url::to(['history']) ?>" class="btn btn-secondary">
                            <i class="fa fa-history"></i> View History
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

            <?php
            // Prepare data for GridView
            $gridData = [];
            $grouped = [];
            foreach ($restorePoints as $point) {
                $grouped[$point['table']][] = $point;
            }
            
            foreach ($tables as $table) {
                $gridData[] = [
                    'table' => $table,
                    'restore_points' => isset($grouped[$table]) ? $grouped[$table] : [],
                    'restore_count' => isset($grouped[$table]) ? count($grouped[$table]) : 0,
                    'latest_backup' => isset($grouped[$table]) && !empty($grouped[$table]) ? $grouped[$table][0] : null,
                ];
            }
            
            $dataProvider = new ArrayDataProvider([
                'allModels' => $gridData,
                'pagination' => false,
            ]);
            ?>

            <?= GridView::widget([
                'dataProvider' => $dataProvider,
                'title' => '<i class="fa fa-database"></i> Select Tables & Create Backup',
                'options' => ['class' => 'table table-hover table-striped'],
                'tableOptions' => ['class' => 'table table-hover table-striped'],
                'columns' => [
                    [
                        'class' => 'yii\grid\CheckboxColumn',
                        'name' => 'backup-tables[]',
                        'checkboxOptions' => function($model) {
                            return ['value' => $model['table'], 'class' => 'backup-table-cb'];
                        },
                    ],
                    [
                        'attribute' => 'table',
                        'label' => 'Table Name',
                        'format' => 'html',
                        'value' => function($model) {
                            return '<i class="fa fa-table"></i> ' . Html::encode($model['table']);
                        },
                    ],
                    [
                        'attribute' => 'restore_count',
                        'label' => 'Backups',
                        'format' => 'html',
                        'value' => function($model) {
                            if ($model['restore_count'] == 0) {
                                return '<span class="badge badge-secondary">0</span>';
                            }
                            return '<span class="badge badge-primary">' . $model['restore_count'] . '</span>';
                        },
                    ],
                    [
                        'label' => 'Latest Backup',
                        'format' => 'html',
                        'value' => function($model) {
                            if ($model['latest_backup']) {
                                return '<small>' . $model['latest_backup']['created_formatted'] . '<br>' . $model['latest_backup']['size_formatted'] . '</small>';
                            }
                            return '<span class="text-muted">-</span>';
                        },
                    ],
                    [
                        'label' => 'Restore Points',
                        'format' => 'raw',
                        'value' => function($model) {
                            if (empty($model['restore_points'])) {
                                return '<span class="text-muted">No backups</span>';
                            }
                            $html = Html::tag('span', '<i class="fa fa-chevron-down"></i> Show (' . count($model['restore_points']) . ')', [
                                'style' => "cursor: pointer;",
                                'class' => "btn btn-sm btn-outline-info toggle-restore-points",
                                'data-table' => $model['table'],
                            ]);
                            // Debug: output the generated HTML as a comment
                            //$html .= "<!-- " . htmlspecialchars($html) . " -->";
                            return $html;
                        },
                    ],
                ],
                'rowOptions' => function($model, $key, $index, $grid) {
                    return ['data-key' => $key];
                },
                'afterRow' => function($model, $key, $index, $grid) {
                    if (empty($model['restore_points']) || count($model['restore_points']) == 0) {
                        return '';
                    }
                    
                    $html = '';
                    $restore_points = $model['restore_points'];
                    $cols_per_row = 3;
                    $point_count = count($restore_points);
                    $rows_needed = ceil($point_count / $cols_per_row);
                    $html .= '<tr id="expand-' . $model['table'] . '-row" class="restore-points-expandable d-none"><td colspan="5">';
                    Pjax::begin([
                        'id' => 'restore-points-' . $model['table'],
                        'timeout' => 5000
                    ]);
                    $html .= GridView::widget([
                        'dataProvider' => new ArrayDataProvider(['allModels' => $restore_points, 'pagination' => false]),
                        'columns' => [
                            [
                                'label' => 'Filename',
                                'format' => 'html',
                                'value' => function($model) {
                                    return '<code>' . Html::encode($model['filename']) . '</code>';
                                },
                            ],
                            [
                                'label' => 'Size',
                                'value' => function($model) {
                                    return $model['size_formatted'];
                                },
                            ],
                            [
                                'label' => 'Created At',
                                'value' => function($model) {
                                    return $model['created_formatted'];
                                },
                            ],
                            [
                                'class' => 'common\widgets\ActionColumn',
                                'template' => '{restore} {download} {delete}',
                                'buttons' => [
                                    'restore' => function($url, $dataModel, $key) use ($model) {
                                        return Html::button('<i class="fa fa-refresh"></i> Restore', [
                                            'class' => 'btn btn-sm btn-success btn-restore',
                                            'data-filename' => $dataModel['filename'],
                                            'data-table' => $model['table'],
                                        ]);
                                    },
                                    'download' => function($url, $dataModel, $key) {
                                        return Html::a('<i class="fa fa-download"></i> Download',            
                                            Url::to(['download', 'filename' => $dataModel['filename']]), 
                                            ['class' => 'btn btn-sm btn-info']);
                                    },
                                    'delete' => function($url, $dataModel, $key) {
                                        return Html::button('<i class="fa fa-trash"></i> Delete', [
                                            'class' => 'btn btn-sm btn-danger btn-delete',
                                            'data-filename' => $dataModel['filename'],
                                        ]);
                                    },
                                ],
                            ],
                        ],
                    ]);
                    Pjax::end();
                    $html .= '</td></tr>';
                    
                    return $html;
                },
                ]) ?>

            <div class="loading">
                <i class="fa fa-spinner fa-spin"></i> Creating backup...
            </div>
            
            <div id="backup-result" class="alert" style="display: none; margin-top: 15px;"></div>
        

</div>

<!-- Fixed Bottom Create Backup Button -->
<div class="fixed-bottom-button">
    <button type="button" id="btn-create-backup" class="btn btn-primary btn-lg">
        <i class="fa fa-database"></i> Create Selected Backups
    </button>
</div>

<?php
$createBackupUrl = Url::to(['create-backup']);
$restoreUrl = Url::to(['restore']);
$deleteUrl = Url::to(['delete']);
$cleanupUrl = Url::to(['cleanup']);
?>
<script>
// Toggle restore points expandable rows (AfterRow)
$(document).on('click', '.toggle-restore-points', function(e) {
    e.preventDefault();
    console.log('Toggle restore points clicked');
    var table = $(this).data('table');
    var expandRows = $('#expand-' + table + '-row');
    console.log('Data attributes:', $(this).data());
    var icon = $(this).find('i');
    
    if (expandRows.hasClass('d-none')) {
        expandRows.removeClass('d-none');
        //expandRows.slideDown(300);
        icon.removeClass('fa-chevron-down').addClass('fa-chevron-up');
        $(this).html(icon).append(' Hide (' + expandRows.find('.restore-point-item').length + ')');
    } else {
        expandRows.addClass('d-none');
        //expandRows.slideUp(300);
        icon.removeClass('fa-chevron-up').addClass('fa-chevron-down');
        $(this).html(icon).append(' Show (' + expandRows.find('.restore-point-item').length + ')');
    }
});

// Create backup
$('#btn-create-backup').click(function() {
    var tables = [];
    $('input[name=\"backup-tables[]\"]:checked').each(function() {
        tables.push($(this).val());
    });
    
    if (tables.length === 0) {
        $('#LGmodal .modal-title').html('No Selection');
        $('#LGmodal .modal-body').html(
            '<div class="alert alert-warning">' +
            '<i class="fa fa-exclamation-triangle"></i> ' +
            'Please select at least one table to backup.' +
            '</div>'
        );
        $('#LGmodal .modal-footer').html(
            '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>'
        );
        $('#LGmodal').modal('show');
        return;
    }
    
    var compress = $('#compress-backup').prop('checked');
    
    $('#btn-create-backup').prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> Creating Backups...');
    $('.loading').show();
    $('#backup-result').hide();
    
    $.ajax({
        url: "<?=$createBackupUrl?>",
        type: 'POST',
        data: {
            tables: tables,
            compress: compress,
            _csrf: yii.getCsrfToken()
        },
        success: function(response) {
            console.log('Backup creation completed:', response);
            
            var title = response.success ? 'Backup Completed' : 'Backup Failed';
            var headerColor = response.success ? 'bg-success' : 'bg-danger';
            var bodyHtml = '<i class="fa ' + (response.success ? 'fa-check-circle' : 'fa-times-circle') + '"></i> ';
            bodyHtml += response.message + '</div>';
            
            if (response.results && response.results.length > 0) {
                bodyHtml += '<div class="table-responsive"><table class="table table-sm table-bordered">';
                bodyHtml += '<thead><tr><th>Table</th><th>Status</th><th>Actions</th></tr></thead><tbody>';
                
                response.results.forEach(function(result) {
                    bodyHtml += '<tr>';
                    bodyHtml += '<td>' + result.table + '</td>';
                    if (result.success) {
                        bodyHtml += '<td><span class="badge badge-success">Success</span><br><small>' + 
                                    (result.size ? (result.size / 1024).toFixed(2) + ' KB' : '') + '</small></td>';
                        bodyHtml += '<td><a href="<?= Url::to(['download']) ?>?filename=' + encodeURIComponent(result.filename) + 
                                    '" class="btn btn-sm btn-info"><i class="fa fa-download"></i> Download</a></td>';
                    } else {
                        bodyHtml += '<td><span class="badge badge-danger">Failed</span><br><small>' + 
                                    (result.error || '') + '</small></td>';
                        bodyHtml += '<td>-</td>';
                    }
                    bodyHtml += '</tr>';
                });
                
                bodyHtml += '</tbody></table></div>';
            }
            
            $('#LGmodal .modal-header').addClass(headerColor + ' text-white');
            $('#LGmodal .modal-title').html(title);
            $('#LGmodal .modal-body').html(bodyHtml);
            $('#LGmodal .modal-footer').html(
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>' +
                '<button type="button" class="btn btn-primary" onclick="location.reload()">Refresh Page</button>'
            );
            $('#LGmodal').modal('show');
        },
        error: function(xhr, status, error) {
            var errorMsg = 'An error occurred while creating backup.';
            console.error('Backup creation failed:', error, xhr.responseText);
            var headerColor = 'bg-danger';
            $('#LGmodal .modal-header').addClass(headerColor + ' text-white');
            $('#LGmodal .modal-title').html('Backup Error');
            $('#LGmodal .modal-body').html(
                '<div class="alert alert-danger">' +
                '<i class="fa fa-times-circle"></i> ' + errorMsg +
                '</div>'
            );
            $('#LGmodal .modal-footer').html(
                '<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>'
            );
            $('#LGmodal').modal('show');
        },
        complete: function() {
            $('#btn-create-backup').prop('disabled', false).html('<i class="fa fa-database"></i> Create Selected Backups');
            $('.loading').hide();
        }
    });
});

// Restore backup
$(document).on('click', '.btn-restore', function() {
    var filename = $(this).data('filename');
    var table = $(this).data('table');
    var btn = $(this);
    
    // Show confirmation modal
    $('#LGmodal .modal-title').html('Confirm Restore');
    $('#LGmodal .modal-header').addClass('bg-warning text-white');
    $('#LGmodal .modal-body').html(
        '<div class="">' +
        '<i class="fa fa-exclamation-triangle"></i> ' +
        '<strong>WARNING:</strong> This will overwrite the current data in table "' + table + '".<br><br>' +
        'Are you sure you want to restore from <strong>' + filename + '</strong>?' +
        '</div>'
    );
    $('#LGmodal .modal-footer').html(
        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>' +
        '<button type="button" class="btn btn-danger" id="confirm-restore">OK - Restore</button>'
    );
    $('#LGmodal').modal('show');
    
    // Handle confirmation
    $('#confirm-restore').off('click').on('click', function() {
        $('#LGmodal').modal('hide');
        performRestore(btn, filename);
    });
});

function performRestore(btn, filename) {
    btn.prop('disabled', true).html('<i class=\"fa fa-spinner fa-spin\"></i> Restoring...');
    
    $.ajax({
        url: "<?=$restoreUrl?>",
        type: 'POST',
        data: {
            filename: filename,
            _csrf: yii.getCsrfToken()
        },
        success: function(response) {
            if (response.success) {
                
                $('#LGmodal .modal-header').addClass('bg-success text-white');
                $('#LGmodal .modal-title').html('Restore Successful');
                
                $('#LGmodal .modal-body').html('<div class=""><i class="fa fa-check-circle"></i> ' + response.message + '</div>');
                $('#LGmodal .modal-footer').html('<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>');
                $('#LGmodal').modal('show');
                setTimeout(function() {
                    location.reload();
                }, 2000);
            } else {
                $('#LGmodal .modal-header').addClass('bg-danger text-white');
                $('#LGmodal .modal-title').html('Restore Failed');
                $('#LGmodal .modal-body').html('<div class="alert alert-danger"><i class="fa fa-times-circle"></i> ' + response.message + '</div>');
                $('#LGmodal .modal-footer').html('<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>');
                $('#LGmodal').modal('show');
            }
        },
        error: function(xhr, status, error) {
            $('#LGmodal .modal-header').addClass('bg-danger text-white');
            $('#LGmodal .modal-title').html('Restore Error');
            $('#LGmodal .modal-body').html('<div class="alert alert-danger"><i class="fa fa-times-circle"></i> An error occurred while restoring backup.</div>');
            $('#LGmodal .modal-footer').html('<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>');
            $('#LGmodal').modal('show');
        },
        complete: function() {
            btn.prop('disabled', false).html('<i class=\"fa fa-refresh\"></i> Restore');
        }
    });
}

// Delete backup
$(document).on('click', '.btn-delete', function() {
    var filename = $(this).data('filename');
    var btn = $(this);
    var pjaxContainer = btn.closest('[data-pjax-container]');
    
    // Show confirmation modal
    
    $('#LGmodal .modal-header').addClass('bg-danger text-white');
    $('#LGmodal .modal-title').html('Confirm Delete');
    $('#LGmodal .modal-body').html(
        '<div class="">' +
        '<i class="fa fa-exclamation-triangle"></i> ' +
        'Are you sure you want to delete <strong>' + filename + '</strong>?' +
        '</div>'
    );
    $('#LGmodal .modal-footer').html(
        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>' +
        '<button type="button" class="btn btn-danger" id="confirm-delete">OK - Delete</button>'
    );
    $('#LGmodal').modal('show');
    
    // Handle confirmation
    $('#confirm-delete').off('click').on('click', function() {
        $('#LGmodal').modal('hide');
        performDelete(btn, filename, pjaxContainer);
    });
});

function performDelete(btn, filename, pjaxContainer) {
    
    $.ajax({
        url: "<?=$deleteUrl?>",
        type: 'POST',
        data: {
            filename: filename,
            _csrf: yii.getCsrfToken()
        },
        success: function(response) {
            if (response.success) {
                // Refresh the Pjax container
                if (pjaxContainer.length) {
                    $.pjax.reload({container: '#' + pjaxContainer.attr('id'), timeout: 5000});
                } else {
                    location.reload();
                }
            } else {                
                $('#LGmodal .modal-header').addClass('bg-danger text-white');
                $('#LGmodal .modal-title').html('Delete Failed');
                $('#LGmodal .modal-body').html('<div class="alert alert-danger"><i class="fa fa-times-circle"></i> ' + response.message + '</div>');
                $('#LGmodal .modal-footer').html('<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>');
                $('#LGmodal').modal('show');
            }
        },
        error: function(xhr, status, error) {
            $('#LGmodal .modal-header').addClass('bg-danger text-white');
            $('#LGmodal .modal-title').html('Delete Error');
            $('#LGmodal .modal-body').html('<div class="alert alert-danger"><i class="fa fa-times-circle"></i> An error occurred while deleting backup.</div>');
            $('#LGmodal .modal-footer').html('<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>');
            $('#LGmodal').modal('show');
        }
    });
}

// Cleanup old backups
$('#btn-cleanup').click(function() {
    var btn = $(this);
    
    // Show confirmation modal
    $('#LGmodal .modal-header').addClass('bg-warning text-white');
    $('#LGmodal .modal-title').html('Confirm Cleanup');
    $('#LGmodal .modal-body').html(
        '<div class="">' +
        '<i class="fa fa-exclamation-triangle"></i> ' +
        'This will delete backups older than the configured retention period.<br><br>' +
        'Continue?' +
        '</div>'
    );
    $('#LGmodal .modal-footer').html(
        '<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>' +
        '<button type="button" class="btn btn-warning" id="confirm-cleanup">OK - Cleanup</button>'
    );
    $('#LGmodal').modal('show');
    
    // Handle confirmation
    $('#confirm-cleanup').off('click').on('click', function() {
        $('#LGmodal').modal('hide');
        performCleanup(btn);
    });
});

function performCleanup(btn) {
    btn.prop('disabled', true).html('<i class=\"fa fa-spinner fa-spin\"></i> Cleaning...');
    
    $.ajax({
        url: '{$cleanupUrl}',
        type: 'POST',
        data: {
            _csrf: yii.getCsrfToken()
        },
        success: function(response) {
            var alertClass = response.success ? 'bg-success' : 'bg-danger';
            var icon = response.success ? 'fa-check-circle' : 'fa-times-circle';
            var title = response.success ? 'Cleanup Completed' : 'Cleanup Failed';
            if (response.success) {
                console.log('Cleanup completed:', response.message);
            } else {
                console.error('Cleanup failed:', response.message);
            }
            $('#LGmodal .modal-header').addClass(alertClass + ' text-white');
            $('#LGmodal .modal-title').html(title);
            $('#LGmodal .modal-body').html('<i class="fa ' + icon + '"></i> ' + response.message );
            $('#LGmodal .modal-footer').html('<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>');
            $('#LGmodal').modal('show');
            if (response.deleted > 0) {
                setTimeout(function() {
                    location.reload();
                }, 2000);
            }
        },
        error: function(xhr, status, error) {
            console.error('Cleanup AJAX error:', error, xhr.responseText);
            $('#LGmodal .modal-header').addClass('bg-danger text-white');
            $('#LGmodal .modal-title').html('Cleanup Error');
            $('#LGmodal .modal-body').html('<i class="fa fa-times-circle"></i> An error occurred during cleanup.');
            $('#LGmodal .modal-footer').html('<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>');
            $('#LGmodal').modal('show');
        },
        complete: function() {
            btn.prop('disabled', false).html('<i class=\"fa fa-trash-o\"></i> Cleanup Old Backups');
        }
    });
}
</script>
