<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Backup & Restore Management
 * Developer: JOACHIM'S INNOTECH
 */

// Initialize system
require_once dirname(__DIR__, 2) . '/config/config.php';
require_once dirname(__DIR__, 2) . '/config/constants.php';
require_once dirname(__DIR__, 2) . '/config/database.php';
require_once dirname(__DIR__, 2) . '/config/helpers.php';
require_once dirname(__DIR__, 2) . '/config/auth.php';
require_once dirname(__DIR__, 2) . '/config/csrf.php';

// Require authentication and permission
require_auth();
require_permission('settings.backup');

// Set page title
$page_title = 'Backup & Restore';

// Get current user
$current_user = current_user();

// Define backup directory
$backup_dir = BASE_PATH . '/backups/';
if (!file_exists($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// Handle backup creation
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST[CSRF_TOKEN_NAME] ?? '')) {
        $error = 'Invalid security token. Please try again.';
    } else {
        $action = $_POST['action'] ?? '';
        
        switch ($action) {
            case 'create_backup':
                try {
                    // Generate backup filename
                    $filename = 'backup_' . date('Y-m-d_H-i-s') . '.sql';
                    $filepath = $backup_dir . $filename;
                    
                    // Create database backup
                    $backup_sql = backup_database();
                    
                    if ($backup_sql === false) {
                        throw new Exception('Failed to generate backup');
                    }
                    
                    // Write to file
                    if (file_put_contents($filepath, $backup_sql) === false) {
                        throw new Exception('Failed to write backup file');
                    }
                    
                    // Compress if requested
                    if (isset($_POST['compress']) && $_POST['compress'] == '1') {
                        $gz_file = $filepath . '.gz';
                        $gz = gzopen($gz_file, 'w9');
                        gzwrite($gz, $backup_sql);
                        gzclose($gz);
                        unlink($filepath); // Remove uncompressed file
                        $filename .= '.gz';
                    }
                    
                    // Log the backup
                    audit_log($current_user['user_id'], AUDIT_BACKUP, 'system', null, null, [
                        'filename' => $filename,
                        'size' => filesize($filepath . (isset($_POST['compress']) ? '.gz' : ''))
                    ]);
                    
                    $message = 'Backup created successfully: ' . $filename;
                    
                } catch (Exception $e) {
                    $error = 'Failed to create backup: ' . $e->getMessage();
                    log_message("Backup failed: " . $e->getMessage(), 'ERROR');
                }
                break;
                
            case 'delete_backup':
                $filename = $_POST['filename'] ?? '';
                $filepath = $backup_dir . $filename;
                
                if (empty($filename)) {
                    $error = 'Invalid filename';
                } elseif (!file_exists($filepath)) {
                    $error = 'Backup file not found';
                } elseif (!unlink($filepath)) {
                    $error = 'Failed to delete backup file';
                } else {
                    audit_log($current_user['user_id'], 'backup_delete', 'system', null, null, ['filename' => $filename]);
                    $message = 'Backup deleted successfully';
                }
                break;
                
            case 'restore_backup':
                $filename = $_POST['filename'] ?? '';
                $filepath = $backup_dir . $filename;
                
                if (empty($filename)) {
                    $error = 'Invalid filename';
                } elseif (!file_exists($filepath)) {
                    $error = 'Backup file not found';
                } else {
                    try {
                        // Read backup file
                        if (pathinfo($filename, PATHINFO_EXTENSION) == 'gz') {
                            $gz = gzopen($filepath, 'r');
                            $sql = '';
                            while (!gzeof($gz)) {
                                $sql .= gzgets($gz, 4096);
                            }
                            gzclose($gz);
                        } else {
                            $sql = file_get_contents($filepath);
                        }
                        
                        // Split SQL into individual queries
                        $queries = explode(';', $sql);
                        
                        begin_transaction();
                        
                        // Disable foreign key checks temporarily
                        db_query("SET FOREIGN_KEY_CHECKS = 0");
                        
                        // Execute each query
                        foreach ($queries as $query) {
                            $query = trim($query);
                            if (!empty($query)) {
                                db_query($query);
                            }
                        }
                        
                        // Re-enable foreign key checks
                        db_query("SET FOREIGN_KEY_CHECKS = 1");
                        
                        commit_transaction();
                        
                        audit_log($current_user['user_id'], AUDIT_RESTORE, 'system', null, null, ['filename' => $filename]);
                        $message = 'Database restored successfully from: ' . $filename;
                        
                    } catch (Exception $e) {
                        rollback_transaction();
                        $error = 'Failed to restore backup: ' . $e->getMessage();
                        log_message("Restore failed: " . $e->getMessage(), 'ERROR');
                    }
                }
                break;
                
            case 'upload_backup':
                if (isset($_FILES['backup_file']) && $_FILES['backup_file']['error'] === UPLOAD_ERR_OK) {
                    $file = $_FILES['backup_file'];
                    $extension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
                    
                    if (!in_array($extension, ['sql', 'gz'])) {
                        $error = 'Only .sql and .gz files are allowed';
                    } elseif ($file['size'] > 100 * 1024 * 1024) { // 100MB max
                        $error = 'File size exceeds 100MB limit';
                    } else {
                        $filename = 'uploaded_' . date('Y-m-d_H-i-s') . '.' . $extension;
                        $destination = $backup_dir . $filename;
                        
                        if (move_uploaded_file($file['tmp_name'], $destination)) {
                            $message = 'Backup file uploaded successfully';
                            audit_log($current_user['user_id'], 'backup_upload', 'system', null, null, ['filename' => $filename]);
                        } else {
                            $error = 'Failed to upload file';
                        }
                    }
                } else {
                    $error = 'Please select a file to upload';
                }
                break;
                
            case 'download_backup':
                $filename = $_POST['filename'] ?? '';
                $filepath = $backup_dir . $filename;
                
                if (empty($filename)) {
                    $error = 'Invalid filename';
                } elseif (!file_exists($filepath)) {
                    $error = 'Backup file not found';
                } else {
                    header('Content-Type: application/octet-stream');
                    header('Content-Disposition: attachment; filename="' . $filename . '"');
                    header('Content-Length: ' . filesize($filepath));
                    readfile($filepath);
                    exit;
                }
                break;
                
            case 'cleanup_old':
                $days = (int)($_POST['days'] ?? 30);
                $count = 0;
                $size_freed = 0;
                
                $files = glob($backup_dir . '*');
                $cutoff = time() - ($days * 86400);
                
                foreach ($files as $file) {
                    if (is_file($file) && filemtime($file) < $cutoff) {
                        $size_freed += filesize($file);
                        if (unlink($file)) {
                            $count++;
                        }
                    }
                }
                
                $message = "Cleaned up $count old backup files, freed " . format_bytes($size_freed);
                audit_log($current_user['user_id'], 'backup_cleanup', 'system', null, null, [
                    'files_deleted' => $count,
                    'size_freed' => $size_freed,
                    'older_than_days' => $days
                ]);
                break;
        }
    }
}

// Get list of backup files
$backup_files = [];
$files = glob($backup_dir . '*');

foreach ($files as $file) {
    if (is_file($file)) {
        $backup_files[] = [
            'name' => basename($file),
            'size' => filesize($file),
            'size_formatted' => format_bytes(filesize($file)),
            'modified' => filemtime($file),
            'modified_formatted' => date(DATETIME_FORMAT, filemtime($file)),
            'type' => pathinfo($file, PATHINFO_EXTENSION)
        ];
    }
}

// Sort by modified date (newest first)
usort($backup_files, function($a, $b) {
    return $b['modified'] - $a['modified'];
});

// Get database stats
$db_stats = get_db_size();
$table_count = db_fetch_value("SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = ?", [DB_NAME]);

// Include header
require_once dirname(__DIR__, 2) . '/views/partials/header.php';
?>

<!-- Content Header -->
<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0">Backup & Restore</h1>
            </div>
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="<?php echo base_url('dashboard.php'); ?>">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/dashboard.php'); ?>">Admin</a></li>
                    <li class="breadcrumb-item"><a href="<?php echo base_url('admin/settings/index.php'); ?>">Settings</a></li>
                    <li class="breadcrumb-item active">Backup & Restore</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Messages -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <i class="fas fa-check-circle mr-2"></i>
                <?php echo $message; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>
        
        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <i class="fas fa-exclamation-circle mr-2"></i>
                <?php echo $error; ?>
                <button type="button" class="close" data-dismiss="alert">&times;</button>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Database Stats -->
            <div class="col-lg-3 col-6">
                <div class="small-box bg-info">
                    <div class="inner">
                        <h3><?php echo $db_stats['size_mb'] ?? '0'; ?> MB</h3>
                        <p>Database Size</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-database"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-success">
                    <div class="inner">
                        <h3><?php echo $table_count; ?></h3>
                        <p>Tables</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-table"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-warning">
                    <div class="inner">
                        <h3><?php echo count($backup_files); ?></h3>
                        <p>Backup Files</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-copy"></i>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-6">
                <div class="small-box bg-danger">
                    <div class="inner">
                        <h3><?php echo $backup_files ? time_ago($backup_files[0]['modified']) : 'Never'; ?></h3>
                        <p>Last Backup</p>
                    </div>
                    <div class="icon">
                        <i class="fas fa-clock"></i>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <!-- Create Backup -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-download mr-1"></i>
                            Create Backup
                        </h3>
                    </div>
                    
                    <form method="POST">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="action" value="create_backup">
                        
                        <div class="card-body">
                            <p>Create a complete backup of the database including all tables and data.</p>
                            
                            <div class="form-group">
                                <div class="custom-control custom-checkbox">
                                    <input type="checkbox" class="custom-control-input" id="compress" name="compress" value="1">
                                    <label class="custom-control-label" for="compress">Compress backup (GZIP)</label>
                                </div>
                                <small class="text-muted">Recommended for large databases</small>
                            </div>
                            
                            <div class="alert alert-info">
                                <i class="fas fa-info-circle mr-2"></i>
                                <strong>Note:</strong> Backup files are stored in: <code><?php echo $backup_dir; ?></code>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-database mr-1"></i> Create Backup Now
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Upload Backup -->
                <div class="card mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-upload mr-1"></i>
                            Upload Backup File
                        </h3>
                    </div>
                    
                    <form method="POST" enctype="multipart/form-data">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="action" value="upload_backup">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="backup_file">Select Backup File</label>
                                <div class="custom-file">
                                    <input type="file" class="custom-file-input" id="backup_file" name="backup_file" 
                                           accept=".sql,.gz" required>
                                    <label class="custom-file-label" for="backup_file">Choose file</label>
                                </div>
                                <small class="text-muted">Allowed: .sql, .gz (Max: 100MB)</small>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-info">
                                <i class="fas fa-upload mr-1"></i> Upload Backup
                            </button>
                        </div>
                    </form>
                </div>

                <!-- Cleanup Old Backups -->
                <div class="card mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-trash-alt mr-1"></i>
                            Cleanup Old Backups
                        </h3>
                    </div>
                    
                    <form method="POST" onsubmit="return confirm('Are you sure you want to delete old backups? This cannot be undone.')">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="action" value="cleanup_old">
                        
                        <div class="card-body">
                            <div class="form-group">
                                <label for="days">Delete backups older than (days)</label>
                                <input type="number" class="form-control" id="days" name="days" value="30" min="1" required>
                            </div>
                        </div>
                        
                        <div class="card-footer">
                            <button type="submit" class="btn btn-warning">
                                <i class="fas fa-broom mr-1"></i> Cleanup Old Backups
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Backup Files List -->
            <div class="col-md-6">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list mr-1"></i>
                            Available Backups
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($backup_files)): ?>
                            <div class="text-center text-muted py-5">
                                <i class="fas fa-database fa-4x mb-3"></i>
                                <h5>No backup files found</h5>
                                <p>Create your first backup using the form on the left</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped table-hover">
                                    <thead>
                                        <tr>
                                            <th>Filename</th>
                                            <th>Size</th>
                                            <th>Modified</th>
                                            <th width="150">Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($backup_files as $backup): ?>
                                        <tr>
                                            <td>
                                                <i class="fas fa-<?php echo $backup['type'] == 'gz' ? 'file-archive' : 'file-code'; ?> mr-2"></i>
                                                <?php echo escape_html($backup['name']); ?>
                                            </td>
                                            <td><?php echo $backup['size_formatted']; ?></td>
                                            <td>
                                                <?php echo time_ago($backup['modified']); ?>
                                                <br>
                                                <small class="text-muted"><?php echo $backup['modified_formatted']; ?></small>
                                            </td>
                                            <td>
                                                <div class="btn-group">
                                                    <form method="POST" style="display: inline;">
                                                        <?php echo csrf_field(); ?>
                                                        <input type="hidden" name="action" value="download_backup">
                                                        <input type="hidden" name="filename" value="<?php echo $backup['name']; ?>">
                                                        <button type="submit" class="btn btn-sm btn-success" title="Download">
                                                            <i class="fas fa-download"></i>
                                                        </button>
                                                    </form>
                                                    
                                                    <button type="button" class="btn btn-sm btn-warning" 
                                                            onclick="restoreBackup('<?php echo $backup['name']; ?>')"
                                                            title="Restore">
                                                        <i class="fas fa-undo"></i>
                                                    </button>
                                                    
                                                    <button type="button" class="btn btn-sm btn-danger" 
                                                            onclick="deleteBackup('<?php echo $backup['name']; ?>')"
                                                            title="Delete">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </div>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <?php if (!empty($backup_files)): ?>
                    <div class="card-footer">
                        <div class="text-muted">
                            <i class="fas fa-info-circle mr-1"></i>
                            Total size: <?php echo format_bytes(array_sum(array_column($backup_files, 'size'))); ?>
                        </div>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Restore Warning -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle mr-2"></i>
                    <strong>Important:</strong> Restoring a backup will overwrite all current data. This action cannot be undone. 
                    Make sure you have a recent backup of the current state before restoring.
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Restore Confirmation Modal -->
<div class="modal fade" id="restoreModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">Confirm Restore</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to restore backup <strong id="restoreFilename"></strong>?</p>
                <p class="text-danger">
                    <i class="fas fa-exclamation-triangle mr-1"></i>
                    This will overwrite ALL current data and cannot be undone.
                </p>
                <p>Please confirm by typing <strong>RESTORE</strong> below:</p>
                <input type="text" class="form-control" id="confirmText" placeholder="Type RESTORE">
            </div>
            <div class="modal-footer">
                <form method="POST" id="restoreForm">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="restore_backup">
                    <input type="hidden" name="filename" id="restoreFilenameInput">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger" id="restoreBtn" disabled>Restore</button>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteBackupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger">
                <h5 class="modal-title">Delete Backup</h5>
                <button type="button" class="close" data-dismiss="modal">
                    <span>&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete backup <strong id="deleteFilename"></strong>?</p>
            </div>
            <div class="modal-footer">
                <form method="POST" id="deleteBackupForm">
                    <?php echo csrf_field(); ?>
                    <input type="hidden" name="action" value="delete_backup">
                    <input type="hidden" name="filename" id="deleteFilenameInput">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Custom file input
    $('.custom-file-input').on('change', function() {
        let fileName = $(this).val().split('\\').pop();
        $(this).next('.custom-file-label').addClass("selected").html(fileName);
    });
    
    // Restore confirmation
    $('#confirmText').on('input', function() {
        const text = $(this).val();
        $('#restoreBtn').prop('disabled', text !== 'RESTORE');
    });
});

function restoreBackup(filename) {
    $('#restoreFilename').text(filename);
    $('#restoreFilenameInput').val(filename);
    $('#confirmText').val('');
    $('#restoreBtn').prop('disabled', true);
    $('#restoreModal').modal('show');
}

function deleteBackup(filename) {
    $('#deleteFilename').text(filename);
    $('#deleteFilenameInput').val(filename);
    $('#deleteBackupModal').modal('show');
}
</script>

<?php
// Include footer
require_once dirname(__DIR__, 2) . '/views/partials/footer.php';
?>