<?php
session_start();

// Check if user is logged in and is admin
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    header('Location: login.php');
    exit();
}

include 'layouts/dbconn.php';
include 'includes/AuditLogger.php';

// Initialize the audit logger
$logger = new AuditLogger($conn, $_SESSION['user_id']);

// Backup directory
$backup_dir = 'backups/';
if (!file_exists($backup_dir)) {
    mkdir($backup_dir, 0755, true);
}

// Get backup settings
$settings = array();
$sql = "SELECT setting_key, setting_value FROM backup_settings";
$result = $conn->query($sql);
while ($row = $result->fetch_assoc()) {
    $settings[$row['setting_key']] = $row['setting_value'];
}

// Get list of backup files
$backups = array();
if ($handle = opendir($backup_dir)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != ".." && pathinfo($entry, PATHINFO_EXTENSION) == 'sql') {
            $backup_path = $backup_dir . $entry;
            $backups[] = array(
                'filename' => $entry,
                'size' => filesize($backup_path),
                'created' => filemtime($backup_path)
            );
        }
    }
    closedir($handle);
}

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

// Calculate statistics
$total_backups = count($backups);
$total_size = array_sum(array_column($backups, 'size'));
$latest_backup = $backups[0] ?? null;
$days_retained = isset($settings['retention_days']) ? intval($settings['retention_days']) : 30;

include 'layouts/main.php';
?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Backup & Restore')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Sweet Alert -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'System', 'title' => 'Backup & Restore')); ?>

                    <!-- Success/Error Messages -->
                    <?php if (isset($_SESSION['success'])): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <?php 
                            echo $_SESSION['success']; 
                            unset($_SESSION['success']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php 
                            echo $_SESSION['error']; 
                            unset($_SESSION['error']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <!-- Statistics Cards -->
                    <div class="row">
                        <div class="col-xl-3 col-sm-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h4 class="mb-0"><?php echo $total_backups; ?></h4>
                                            <p class="text-muted mb-0">Total Backups</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-primary-subtle text-primary rounded">
                                                    <i class="ri-database-2-line fs-3"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-sm-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h4 class="mb-0"><?php echo number_format($total_size / (1024 * 1024), 2); ?> MB</h4>
                                            <p class="text-muted mb-0">Total Size</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-success-subtle text-success rounded">
                                                    <i class="ri-hard-drive-line fs-3"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-sm-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h4 class="mb-0"><?php echo $latest_backup ? date('Y-m-d H:i', $latest_backup['created']) : 'Never'; ?></h4>
                                            <p class="text-muted mb-0">Latest Backup</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-info-subtle text-info rounded">
                                                    <i class="ri-time-line fs-3"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="col-xl-3 col-sm-6">
                            <div class="card">
                                <div class="card-body">
                                    <div class="d-flex align-items-center">
                                        <div class="flex-grow-1">
                                            <h4 class="mb-0"><?php echo $days_retained; ?> Days</h4>
                                            <p class="text-muted mb-0">Retention Period</p>
                                        </div>
                                        <div class="flex-shrink-0">
                                            <div class="avatar-sm">
                                                <span class="avatar-title bg-warning-subtle text-warning rounded">
                                                    <i class="ri-calendar-line fs-3"></i>
                                                </span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Backup Actions -->
                    <div class="row">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Backup Management</h4>
                                    <div class="flex-shrink-0">
                                        <button type="button" class="btn btn-primary" id="createBackupBtn">
                                            <i class="ri-add-line align-middle me-1"></i> Create Backup
                                        </button>
                                        <button type="button" class="btn btn-soft-primary" data-bs-toggle="modal" data-bs-target="#scheduleModal">
                                            <i class="ri-settings-3-line align-middle me-1"></i> Schedule Settings
                                        </button>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table table-nowrap align-middle mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th scope="col">Filename</th>
                                                    <th scope="col">Size</th>
                                                    <th scope="col">Created At</th>
                                                    <th scope="col">Type</th>
                                                    <th scope="col" class="text-center">Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php if (empty($backups)): ?>
                                                    <tr>
                                                        <td colspan="5" class="text-center">No backups found</td>
                                                    </tr>
                                                <?php else: ?>
                                                    <?php foreach ($backups as $backup): ?>
                                                        <tr>
                                                            <td>
                                                                <div class="d-flex align-items-center">
                                                                    <i class="ri-file-text-line text-primary fs-16 me-2"></i>
                                                                    <?php echo htmlspecialchars($backup['filename']); ?>
                                                                </div>
                                                            </td>
                                                            <td><?php echo number_format($backup['size'] / 1024, 2); ?> KB</td>
                                                            <td><?php echo date('Y-m-d H:i:s', $backup['created']); ?></td>
                                                            <td>
                                                                <?php
                                                                $is_automated = strpos($backup['filename'], 'automated_') === 0;
                                                                $badge_class = $is_automated ? 'bg-info-subtle text-info' : 'bg-success-subtle text-success';
                                                                ?>
                                                                <span class="badge <?php echo $badge_class; ?>">
                                                                    <?php echo $is_automated ? 'Automated' : 'Manual'; ?>
                                                                </span>
                                                            </td>
                                                            <td>
                                                                <div class="text-center">
                                                                    <a href="download_backup.php?file=<?php echo urlencode($backup['filename']); ?>" 
                                                                       class="btn btn-soft-primary btn-sm">
                                                                        <i class="ri-download-2-line"></i>
                                                                    </a>
                                                                    <button type="button" class="btn btn-soft-warning btn-sm restore-backup" 
                                                                            data-filename="<?php echo htmlspecialchars($backup['filename']); ?>">
                                                                        <i class="ri-restart-line"></i>
                                                                    </button>
                                                                    <button type="button" class="btn btn-soft-danger btn-sm delete-backup"
                                                                            data-filename="<?php echo htmlspecialchars($backup['filename']); ?>">
                                                                        <i class="ri-delete-bin-line"></i>
                                                                    </button>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    <?php endforeach; ?>
                                                <?php endif; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Schedule Settings Modal -->
            <div class="modal fade" id="scheduleModal" tabindex="-1" aria-labelledby="scheduleModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="scheduleModalLabel">Backup Schedule Settings</h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <form id="scheduleForm">
                            <div class="modal-body">
                                <div class="mb-3">
                                    <label class="form-label">Backup Frequency</label>
                                    <select class="form-select" name="frequency" required>
                                        <option value="daily" <?php echo ($settings['backup_frequency'] ?? '') === 'daily' ? 'selected' : ''; ?>>Daily</option>
                                        <option value="weekly" <?php echo ($settings['backup_frequency'] ?? '') === 'weekly' ? 'selected' : ''; ?>>Weekly</option>
                                        <option value="monthly" <?php echo ($settings['backup_frequency'] ?? '') === 'monthly' ? 'selected' : ''; ?>>Monthly</option>
                                    </select>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Retention Period (Days)</label>
                                    <input type="number" class="form-control" name="retention_days" 
                                           min="1" max="365" 
                                           value="<?php echo $settings['retention_days'] ?? '30'; ?>" required>
                                </div>
                                <div class="mb-3">
                                    <label class="form-label">Notification Email</label>
                                    <input type="email" class="form-control" name="notify_email"
                                           value="<?php echo $settings['notify_email'] ?? ''; ?>"
                                           placeholder="admin@example.com">
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-primary">Save Changes</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- Sweet Alert -->
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Create backup button handler
            document.getElementById('createBackupBtn').addEventListener('click', function() {
                Swal.fire({
                    title: 'Create New Backup',
                    text: 'Are you sure you want to create a new backup?',
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Yes, create it!',
                    cancelButtonText: 'No, cancel',
                    confirmButtonClass: 'btn btn-primary w-xs me-2 mt-2',
                    cancelButtonClass: 'btn btn-light w-xs mt-2',
                    buttonsStyling: false,
                    showLoaderOnConfirm: true
                }).then((result) => {
                    if (result.isConfirmed) {
                        const form = document.createElement('form');
                        form.method = 'POST';
                        form.action = 'backup_actions.php';
            
                        const actionInput = document.createElement('input');
                        actionInput.type = 'hidden';
                        actionInput.name = 'action';
                        actionInput.value = 'create_backup';
            
                        form.appendChild(actionInput);
                        document.body.appendChild(form);
                        form.submit();
                    }
                });
            });

            // Restore backup handler
            document.querySelectorAll('.restore-backup').forEach(button => {
                button.addEventListener('click', function() {
                    const filename = this.dataset.filename;
                    Swal.fire({
                        title: 'Restore Backup',
                        text: `Are you sure you want to restore ${filename}? This will overwrite the current database!`,
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, restore it!',
                        cancelButtonText: 'No, cancel',
                        confirmButtonClass: 'btn btn-warning w-xs me-2 mt-2',
                        cancelButtonClass: 'btn btn-light w-xs mt-2',
                        buttonsStyling: false,
                        showLoaderOnConfirm: true
                    }).then((result) => {
                        if (result.isConfirmed) {
                            const form = document.createElement('form');
                            form.method = 'POST';
                            form.action = 'backup_actions.php';
            
                            // Add action input
                            const actionInput = document.createElement('input');
                            actionInput.type = 'hidden';
                            actionInput.name = 'action';
                            actionInput.value = 'restore_backup';
                            
                            // Add filename input
                            const filenameInput = document.createElement('input');
                            filenameInput.type = 'hidden';
                            filenameInput.name = 'filename';
                            filenameInput.value = filename;
            
                            form.appendChild(actionInput);
                            form.appendChild(filenameInput);
                            document.body.appendChild(form);
                            form.submit();
                        }
                    });
                });
            });

            // Delete backup handler
            document.querySelectorAll('.delete-backup').forEach(button => {
                button.addEventListener('click', function() {
                    const filename = this.dataset.filename;
                    Swal.fire({
                        title: 'Delete Backup',
                        text: `Are you sure you want to delete ${filename}?`,
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonText: 'Yes, delete it!',
                        cancelButtonText: 'No, cancel',
                        confirmButtonClass: 'btn btn-danger w-xs me-2 mt-2',
                        cancelButtonClass: 'btn btn-light w-xs mt-2',
                        buttonsStyling: false,
                        showLoaderOnConfirm: true
                    }).then((result) => {
                        if (result.isConfirmed) {
                            const form = document.createElement('form');
                            form.method = 'POST';
                            form.action = 'backup_actions.php';
            
                            // Add action input
                            const actionInput = document.createElement('input');
                            actionInput.type = 'hidden';
                            actionInput.name = 'action';
                            actionInput.value = 'delete_backup';
                            
                            // Add filename input
                            const filenameInput = document.createElement('input');
                            filenameInput.type = 'hidden';
                            filenameInput.name = 'filename';
                            filenameInput.value = filename;
            
                            form.appendChild(actionInput);
                            form.appendChild(filenameInput);
                            document.body.appendChild(form);
                            form.submit();
                        }
                    });
                });
            });

            // Schedule form handler
            document.getElementById('scheduleForm').addEventListener('submit', function(e) {
                e.preventDefault();
                const formData = new FormData(this);
                formData.append('action', 'update_schedule');
            
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = 'backup_actions.php';
            
                for (let pair of formData.entries()) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = pair[0];
                    input.value = pair[1];
                    form.appendChild(input);
                }
            
                document.body.appendChild(form);
                form.submit();
            });

            // Show success/error messages from session if they exist
            <?php if (isset($_SESSION['success'])): ?>
                Swal.fire({
                    title: 'Success!',
                    text: '<?php echo addslashes($_SESSION['success']); ?>',
                    icon: 'success',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false
                });
            <?php unset($_SESSION['success']); endif; ?>

            <?php if (isset($_SESSION['error'])): ?>
                Swal.fire({
                    title: 'Error!',
                    text: '<?php echo addslashes($_SESSION['error']); ?>',
                    icon: 'error',
                    confirmButtonClass: 'btn btn-primary w-xs mt-2',
                    buttonsStyling: false
                });
            <?php unset($_SESSION['error']); endif; ?>
        });
    </script>
</body>
</html>