<?php

include '../../includes/header.php';


$auth = new Auth($conn);
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


$database = new Database();
$conn = $database->getConnection();


require_once __DIR__ . '/../../classes/LocalBackupManager.php';
$localBackupManager = new LocalBackupManager($conn);


$message = '';
$messageType = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    error_log("POST request received: " . print_r($_POST, true));

    if (isset($_POST['create_backup'])) {
        error_log("Create backup requested by user: " . $_SESSION['user_id']);
        try {
            $result = $localBackupManager->createLocalBackup($_SESSION['user_id']);
            error_log("Backup creation result: " . print_r($result, true));
            $message = "Local backup created successfully! Backup ID: {$result['backup_id']}";
            $messageType = 'success';
        } catch (Exception $e) {
            error_log("Backup creation error: " . $e->getMessage());
            error_log("Stack trace: " . $e->getTraceAsString());
            $message = "Error creating backup: " . $e->getMessage();
            $messageType = 'danger';
        }
    } elseif (isset($_POST['delete_backup']) && isset($_POST['backup_id'])) {
        $backupId = (int)$_POST['backup_id'];
        error_log("Delete backup requested for ID: " . $backupId);
        if ($localBackupManager->deleteLocalBackup($backupId)) {
            $message = "Backup deleted successfully!";
            $messageType = 'success';
        } else {
            $message = "Error deleting backup.";
            $messageType = 'danger';
        }
    }
}


$backupHistory = $localBackupManager->getLocalBackupHistory(20);
?>

<style>
    .backup-card {
        border: none;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        margin-bottom: 20px;
    }

    .backup-header {
        background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        color: white;
        padding: 15px 20px;
        border-radius: 5px 5px 0 0;
    }

    .status-indicator {
        width: 12px;
        height: 12px;
        border-radius: 50%;
        display: inline-block;
        margin-right: 8px;
    }

    .status-success { background-color: #28a745; }
    .status-failed { background-color: #dc3545; }
    .status-in_progress { background-color: #17a2b8; }

    .download-link {
        color: #007bff;
        text-decoration: none;
    }

    .download-link:hover {
        text-decoration: underline;
    }

    .table-responsive {
        border-radius: 0 0 5px 5px;
        overflow: hidden;
    }
</style>

<div class="container-fluid mt-4">
    <div class="row">
        <div class="col-12">
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="../dashboard/admin.php">Dashboard</a></li>
                    <li class="breadcrumb-item active">Local Backup Management</li>
                </ol>
            </nav>

            <h2><i class="fas fa-download"></i> Local Backup Management</h2>
            <p class="text-muted">Create and download database backups to your local computer</p>
        </div>
    </div>

    <?php if (!empty($message)): ?>
    <div class="row">
        <div class="col-12">
            <div class="alert alert-<?php echo $messageType; ?> alert-dismissible fade show">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        </div>
    </div>
    <?php endif; ?>


    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card backup-card">
                <div class="card-body text-center">
                    <i class="fas fa-plus-circle fa-2x text-success mb-2"></i>
                    <h6>Create New Backup</h6>
                    <p class="text-muted small">Generate a fresh backup of all system data</p>
                    <form method="POST" style="display: inline;">
                        <button type="submit" name="create_backup" class="btn btn-success btn-sm"
                                onclick="return confirm('Are you sure you want to create a new backup? This may take a few minutes.')">
                            <i class="fas fa-play"></i> Create Backup
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card backup-card">
                <div class="card-body text-center">
                    <i class="fas fa-info-circle fa-2x text-info mb-2"></i>
                    <h6>Backup Information</h6>
                    <p class="text-muted small">Backups include all business data, transactions, and system logs</p>
                    <span class="badge bg-info"><?php echo count($backupHistory); ?> backups available</span>
                </div>
            </div>
        </div>

        <div class="col-md-4">
            <div class="card backup-card">
                <div class="card-body text-center">
                    <i class="fas fa-shield-alt fa-2x text-warning mb-2"></i>
                    <h6>Security Note</h6>
                    <p class="text-muted small">Backups are stored securely and only accessible to administrators</p>
                    <span class="badge bg-warning">Admin Only</span>
                </div>
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-12">
            <div class="card backup-card">
                <div class="backup-header">
                    <h5><i class="fas fa-history"></i> Local Backup History</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($backupHistory)): ?>
                        <div class="text-center text-muted py-4">
                            <i class="fas fa-inbox fa-3x mb-3"></i>
                            <p>No local backups found.</p>
                            <p>Create your first backup to see it listed here.</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th><i class="fas fa-hashtag"></i> ID</th>
                                        <th><i class="fas fa-calendar"></i> Created</th>
                                        <th><i class="fas fa-info-circle"></i> Status</th>
                                        <th><i class="fas fa-file"></i> File Size</th>
                                        <th><i class="fas fa-clock"></i> Duration</th>
                                        <th><i class="fas fa-user"></i> Created By</th>
                                        <th><i class="fas fa-download"></i> Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($backupHistory as $backup): ?>
                                        <tr>
                                            <td>
                                                <strong>#<?php echo $backup['backup_id']; ?></strong>
                                            </td>
                                            <td>
                                                <?php echo date('M d, Y', strtotime($backup['backup_date'])); ?>
                                                <br>
                                                <small class="text-muted"><?php echo date('H:i:s', strtotime($backup['backup_date'])); ?></small>
                                            </td>
                                            <td>
                                                <span class="status-indicator status-<?php echo $backup['status']; ?>"></span>
                                                <?php echo ucfirst(str_replace('_', ' ', $backup['status'])); ?>
                                            </td>
                                            <td>
                                                <?php if ($backup['file_size']): ?>
                                                    <?php echo formatFileSize($backup['file_size']); ?>
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php if ($backup['execution_time']): ?>
                                                    <?php echo $backup['execution_time']; ?>s
                                                <?php else: ?>
                                                    <span class="text-muted">-</span>
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($backup['created_by_name'] ?? 'System'); ?>
                                            </td>
                                            <td>
                                                <?php if ($backup['status'] === 'success' && $backup['file_path']): ?>
                                                    <a href="../../api/download_local_backup.php?id=<?php echo $backup['backup_id']; ?>"
                                                       class="download-link btn btn-sm btn-outline-primary">
                                                        <i class="fas fa-download"></i> Download
                                                    </a>
                                                    <form method="POST" style="display: inline; margin-left: 5px;">
                                                        <input type="hidden" name="backup_id" value="<?php echo $backup['backup_id']; ?>">
                                                        <button type="submit" name="delete_backup" class="btn btn-sm btn-outline-danger"
                                                                onclick="return confirm('Are you sure you want to delete this backup?')">
                                                            <i class="fas fa-trash"></i> Delete
                                                        </button>
                                                    </form>
                                                <?php elseif ($backup['status'] === 'in_progress'): ?>
                                                    <span class="badge bg-warning">In Progress...</span>
                                                <?php elseif ($backup['status'] === 'failed'): ?>
                                                    <span class="badge bg-danger">Failed</span>
                                                    <?php if ($backup['error_message']): ?>
                                                        <br><small class="text-danger"><?php echo htmlspecialchars($backup['error_message']); ?></small>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>




































</div>

<?php

function formatFileSize($bytes) {
    if (!$bytes) return '-';

    $units = ['B', 'KB', 'MB', 'GB'];
    $bytes = max($bytes, 0);
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
    $pow = min($pow, count($units) - 1);
    $bytes /= pow(1024, $pow);

    return round($bytes, 2) . ' ' . $units[$pow];
}
?>

<?php
include '../../includes/footer.php';
?>