<?php

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

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

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

require_once __DIR__ . '/../../classes/BackupManager.php';
require_once __DIR__ . '/../../classes/EmailService.php';

$backupManager = new BackupManager($conn);
$emailService = new EmailService($conn);

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

echo "\n";

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

    echo "\n";
    echo "\n";
    echo "\n";

    if (isset($_POST['update_settings'])) {
        error_log("Updating settings");
        echo "\n";
        echo "\n";
        $message = updateBackupSettings($conn);
        $messageType = strpos($message, 'Error') === false ? 'success' : 'danger';
        echo "\n";
    } elseif (isset($_POST['test_email'])) {
        error_log("Testing email");

        $emailService = new EmailService($conn);

        try {
            $result = $emailService->sendTestEmail();
            $message = $result ? "Test email sent successfully!" : "Test email failed to send.";
            $messageType = $result ? 'success' : 'danger';
        } catch (Exception $e) {
            $message = "Error sending test email: " . $e->getMessage();
            $messageType = 'danger';
            error_log("Email test error: " . $e->getMessage());
        }
    } elseif (isset($_POST['run_backup'])) {
        $message = runManualBackup($backupManager);
        $messageType = strpos($message, 'Error') === false ? 'success' : 'danger';
    } elseif (isset($_POST['cleanup_backups'])) {
        $message = cleanupOldBackups($backupManager);
        $messageType = strpos($message, 'Error') === false ? 'success' : 'danger';
    } elseif (isset($_POST['debug_test'])) {
        $message = "Debug test successful - form submission works!";
        $messageType = 'success';
    }
}

echo "\n";
$settings = getAllBackupSettings($conn);
echo "\n";
$backupHistory = $backupManager->getBackupHistory(20);
$smtpConfig = $emailService->getSmtpConfig();
?>

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

    .settings-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 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-pending { background-color: #ffc107; }
    .status-in_progress { background-color: #17a2b8; }

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

    .backup-file-link:hover {
        text-decoration: underline;
    }

    .config-table th {
        background-color: #f8f9fa;
        border-top: none;
        font-weight: 600;
    }

    .test-result {
        padding: 10px;
        border-radius: 5px;
        margin-top: 10px;
    }

    .test-success {
        background-color: #d4edda;
        border: 1px solid #c3e6cb;
        color: #155724;
    }

    .test-error {
        background-color: #f8d7da;
        border: 1px solid #f5c6cb;
        color: #721c24;
    }
</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">Backup Management</li>
                </ol>
            </nav>

            <h2><i class="fas fa-shield-alt"></i> Backup Management System</h2>
            <p class="text-muted">Configure automated backups and monitor backup status</p>


            <div class="alert alert-warning">
                <strong>Debug Test:</strong>
                <form method="POST" style="display: inline;">
                    <input type="hidden" name="debug_test" value="1">
                    <button type="submit" class="btn btn-warning btn-sm">Test Form Submission</button>
                </form>
                <?php
                if (isset($_POST['debug_test'])) {
                    echo "<br><strong>✅ Form submission works!</strong> POST data received.";
                }
                ?>

                <br><strong>Current Email Settings from Database:</strong>
                <ul>
                    <li>SMTP Host: <?php echo htmlspecialchars($settings['smtp_host']['value'] ?? 'NOT SET'); ?></li>
                    <li>SMTP Username: <?php echo htmlspecialchars($settings['smtp_username']['value'] ?? 'NOT SET'); ?></li>
                    <li>Admin Email: <?php echo htmlspecialchars($settings['admin_email']['value'] ?? 'NOT SET'); ?></li>
                </ul>
            </div>
        </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 else: ?>
    <div class="row">
        <div class="col-12">
            <div class="alert alert-info">
                <strong>Debug:</strong> No message set. Check if form is submitting properly.
            </div>
        </div>
    </div>
    <?php endif; ?>


    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card settings-card">
                <div class="card-body text-center">
                    <i class="fas fa-play-circle fa-2x text-success mb-2"></i>
                    <h6>Run Backup Now</h6>
                    <form method="POST" style="display: inline;">
                        <button type="submit" name="run_backup" class="btn btn-success btn-sm"
                                onclick="return confirm('Are you sure you want to run a backup now?')">
                            Start Backup
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card settings-card">
                <div class="card-body text-center">
                    <i class="fas fa-envelope fa-2x text-primary mb-2"></i>
                    <h6>Test Email</h6>
                    <form method="POST" style="display: inline;" id="testEmailForm">
                        <button type="submit" name="test_email" class="btn btn-primary btn-sm" id="testEmailBtn">
                            Send Test Email
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card settings-card">
                <div class="card-body text-center">
                    <i class="fas fa-trash-alt fa-2x text-warning mb-2"></i>
                    <h6>Cleanup Old Files</h6>
                    <form method="POST" style="display: inline;">
                        <button type="submit" name="cleanup_backups" class="btn btn-warning btn-sm"
                                onclick="return confirm('Are you sure you want to delete old backup files?')">
                            Cleanup
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="card settings-card">
                <div class="card-body text-center">
                    <i class="fas fa-chart-line fa-2x text-info mb-2"></i>
                    <h6>System Status</h6>
                    <span class="badge bg-<?php echo ($settings['backup_enabled']['value'] ?? 'false') === 'true' ? 'success' : 'danger'; ?>">
                        <?php echo ($settings['backup_enabled']['value'] ?? 'false') === 'true' ? 'Enabled' : 'Disabled'; ?>
                    </span>
                </div>
            </div>
        </div>
    </div>


    <div class="row">
        <div class="col-md-6">
            <div class="card settings-card">
                <div class="settings-header">
                    <h5><i class="fas fa-cog"></i> Backup Settings</h5>
                </div>
                <div class="card-body">
                    <form method="POST" id="backupSettingsForm">
                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="backup_enabled"
                                       name="backup_enabled" value="true"
                                       <?php echo ($settings['backup_enabled']['value'] ?? 'false') === 'true' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="backup_enabled">
                                    Enable Automatic Backups
                                </label>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="backup_frequency" class="form-label">Backup Frequency</label>
                                    <select class="form-select" id="backup_frequency" name="backup_frequency">
                                        <option value="daily" <?php echo ($settings['backup_frequency']['value'] ?? 'daily') === 'daily' ? 'selected' : ''; ?>>Daily</option>
                                        <option value="weekly" <?php echo ($settings['backup_frequency']['value'] ?? '') === 'weekly' ? 'selected' : ''; ?>>Weekly</option>
                                        <option value="monthly" <?php echo ($settings['backup_frequency']['value'] ?? '') === 'monthly' ? 'selected' : ''; ?>>Monthly</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="backup_time" class="form-label">Backup Time</label>
                                    <input type="time" class="form-control" id="backup_time" name="backup_time"
                                           value="<?php echo $settings['backup_time']['value'] ?? '02:00'; ?>">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="retention_days" class="form-label">Retention (Days)</label>
                                    <input type="number" class="form-control" id="retention_days" name="retention_days"
                                           value="<?php echo $settings['retention_days']['value'] ?? '30'; ?>" min="1" max="365">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="max_file_size" class="form-label">Max File Size (MB)</label>
                                    <input type="number" class="form-control" id="max_file_size" name="max_file_size"
                                           value="<?php echo $settings['max_file_size']['value'] ?? '25'; ?>" min="1" max="100">
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="compression_enabled"
                                       name="compression_enabled" value="true"
                                       <?php echo ($settings['compression_enabled']['value'] ?? 'true') === 'true' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="compression_enabled">
                                    Enable File Compression
                                </label>
                            </div>
                        </div>

                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="notification_enabled"
                                       name="notification_enabled" value="true"
                                       <?php echo ($settings['notification_enabled']['value'] ?? 'true') === 'true' ? 'checked' : ''; ?>>
                                <label class="form-check-label" for="notification_enabled">
                                    Send Email Notifications
                                </label>
                            </div>
                        </div>

                        <button type="submit" name="update_settings" class="btn btn-primary">
                            <i class="fas fa-save"></i> Save Settings
                        </button>
                    </form>
                </div>
            </div>
        </div>


        <div class="col-md-6">
            <div class="card settings-card">
                <div class="settings-header">
                    <h5><i class="fas fa-envelope"></i> Email Configuration</h5>
                </div>
                <div class="card-body">
                    <form method="POST" id="emailSettingsForm">
                        <div class="mb-3">
                            <label for="admin_email" class="form-label">Admin Email Address</label>
                            <input type="email" class="form-control" id="admin_email" name="admin_email"
                                   value="<?php echo $settings['admin_email']['value'] ?? ''; ?>"
                                   placeholder="admin@company.com" required>
                        </div>

                        <div class="row">
                            <div class="col-md-8">
                                <div class="mb-3">
                                    <label for="smtp_host" class="form-label">SMTP Host</label>
                                    <input type="text" class="form-control" id="smtp_host" name="smtp_host"
                                           value="<?php echo $settings['smtp_host']['value'] ?? ''; ?>"
                                           placeholder="smtp.gmail.com" required>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="mb-3">
                                    <label for="smtp_port" class="form-label">Port</label>
                                    <input type="number" class="form-control" id="smtp_port" name="smtp_port"
                                           value="<?php echo $settings['smtp_port']['value'] ?? '587'; ?>" required>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="smtp_username" class="form-label">SMTP Username</label>
                            <input type="text" class="form-control" id="smtp_username" name="smtp_username"
                                   value="<?php echo $settings['smtp_username']['value'] ?? ''; ?>"
                                   placeholder="your-email@gmail.com" required>
                        </div>

                        <div class="mb-3">
                            <label for="smtp_password" class="form-label">SMTP Password</label>
                            <input type="password" class="form-control" id="smtp_password" name="smtp_password"
                                   value="<?php echo $settings['smtp_password']['value'] ?? ''; ?>"
                                   placeholder="App password or SMTP password" required>
                        </div>

                        <div class="mb-3">
                            <label for="smtp_encryption" class="form-label">Encryption</label>
                            <select class="form-select" id="smtp_encryption" name="smtp_encryption" required>
                                <option value="tls" <?php echo ($settings['smtp_encryption']['value'] ?? 'tls') === 'tls' ? 'selected' : ''; ?>>TLS</option>
                                <option value="ssl" <?php echo ($settings['smtp_encryption']['value'] ?? '') === 'ssl' ? 'selected' : ''; ?>>SSL</option>
                                <option value="none" <?php echo ($settings['smtp_encryption']['value'] ?? '') === 'none' ? 'selected' : ''; ?>>None</option>
                            </select>
                        </div>

                        <button type="submit" name="update_settings" class="btn btn-primary" id="saveEmailBtn">
                            <i class="fas fa-save"></i> Save Email Settings
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>


    <div class="row mt-4">
        <div class="col-12">
            <div class="card settings-card">
                <div class="settings-header">
                    <h5><i class="fas fa-history"></i> 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 backup history found.</p>
                            <p>Run your first backup to see history 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> Date</th>
                                        <th><i class="fas fa-tag"></i> Type</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-envelope"></i> Email</th>
                                        <th><i class="fas fa-user"></i> Created By</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="badge bg-secondary"><?php echo ucfirst($backup['backup_type']); ?></span>
                                            </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 if ($backup['email_sent']): ?>
                                                    <i class="fas fa-check text-success"></i> Sent
                                                <?php else: ?>
                                                    <i class="fas fa-times text-danger"></i> Failed
                                                <?php endif; ?>
                                            </td>
                                            <td>
                                                <?php echo htmlspecialchars($backup['created_by_name'] ?? 'System'); ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<?php

function updateBackupSettings($conn) {
    echo "\n";

    $settings = [
        'backup_enabled' => $_POST['backup_enabled'] ?? 'false',
        'backup_frequency' => $_POST['backup_frequency'] ?? 'daily',
        'backup_time' => $_POST['backup_time'] ?? '02:00',
        'retention_days' => $_POST['retention_days'] ?? '30',
        'max_file_size' => $_POST['max_file_size'] ?? '25',
        'compression_enabled' => $_POST['compression_enabled'] ?? 'false',
        'notification_enabled' => $_POST['notification_enabled'] ?? 'false',
        'admin_email' => trim($_POST['admin_email'] ?? ''),
        'smtp_host' => trim($_POST['smtp_host'] ?? ''),
        'smtp_port' => $_POST['smtp_port'] ?? '587',
        'smtp_username' => trim($_POST['smtp_username'] ?? ''),
        'smtp_password' => $_POST['smtp_password'] ?? '',
        'smtp_encryption' => $_POST['smtp_encryption'] ?? 'tls'
    ];

    echo "\n";

    try {
        $conn->beginTransaction();
        echo "\n";

        $successCount = 0;
        foreach ($settings as $key => $value) {
            $isEncrypted = in_array($key, ['smtp_password']);

            $sql = "INSERT INTO backup_settings (setting_key, setting_value, is_encrypted, updated_by)
                    VALUES (:key, :value, :encrypted, :user_id)
                    ON DUPLICATE KEY UPDATE
                    setting_value = VALUES(setting_value),
                    is_encrypted = VALUES(is_encrypted),
                    updated_at = NOW(),
                    updated_by = VALUES(updated_by)";

            echo "\n";

            $stmt = $conn->prepare($sql);
            $stmt->bindValue(':key', $key, PDO::PARAM_STR);
            $stmt->bindValue(':value', $value, PDO::PARAM_STR);
            $stmt->bindValue(':encrypted', $isEncrypted, PDO::PARAM_BOOL);
            $stmt->bindValue(':user_id', $_SESSION['user_id'] ?? 1, PDO::PARAM_INT);

            if ($stmt->execute()) {
                $successCount++;
                echo "\n";
            } else {
                $errorInfo = $stmt->errorInfo();
                echo "\n";
            }
        }

        $conn->commit();
        echo "\n";

        return "Settings updated successfully! ($successCount settings saved)";

    } catch (Exception $e) {
        $conn->rollback();
        echo "\n";
        return "Error updating settings: " . $e->getMessage();
    }
}

function runManualBackup($backupManager) {
    try {
        $result = $backupManager->createFullBackup($_SESSION['user_id']);
        return "Backup completed successfully! ID: {$result['backup_id']}";
    } catch (Exception $e) {
        return "Error running backup: " . $e->getMessage();
    }
}

function cleanupOldBackups($backupManager) {
    try {
        $deletedCount = $backupManager->cleanupOldBackups();
        return "Cleanup completed! Deleted $deletedCount old backup files.";
    } catch (Exception $e) {
        return "Error during cleanup: " . $e->getMessage();
    }
}

function getAllBackupSettings($conn) {
    try {
        $stmt = $conn->prepare("SHOW TABLES LIKE 'backup_settings'");
        $stmt->execute();
        $tableExists = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$tableExists) {
            echo "\n";
            return [];
        }

        echo "\n";

        $stmt = $conn->prepare("SELECT COUNT(*) as count FROM backup_settings");
        $stmt->execute();
        $countResult = $stmt->fetch(PDO::FETCH_ASSOC);
        echo "\n";

        $stmt = $conn->prepare("SELECT * FROM backup_settings ORDER BY setting_key");
        $stmt->execute();
        $results = $stmt->fetchAll(PDO::FETCH_ASSOC);

        echo "\n";

        $settings = [];
        foreach ($results as $result) {
            $settings[$result['setting_key']] = $result;
            echo "\n";
        }

        return $settings;
    } catch (Exception $e) {
        echo "\n";
        return [];
    }
}

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];
}
?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const emailForm = document.getElementById('emailSettingsForm');
    const saveEmailBtn = document.getElementById('saveEmailBtn');

    if (emailForm && saveEmailBtn) {
        emailForm.addEventListener('submit', function(e) {
            const originalText = saveEmailBtn.innerHTML;
            saveEmailBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Saving...';

            setTimeout(() => {
                saveEmailBtn.innerHTML = originalText;
            }, 3000);
        });
    }

    const testEmailForm = document.getElementById('testEmailForm');
    const testEmailBtn = document.getElementById('testEmailBtn');

    if (testEmailForm && testEmailBtn) {
        testEmailForm.addEventListener('submit', function(e) {
            const smtpHost = document.getElementById('smtp_host');
            const smtpUsername = document.getElementById('smtp_username');
            const adminEmail = document.getElementById('admin_email');

            console.log('Test Email Validation:');
            console.log('SMTP Host value:', smtpHost?.value);
            console.log('SMTP Username value:', smtpUsername?.value);
            console.log('Admin Email value:', adminEmail?.value);

            if (!smtpHost?.value || !smtpUsername?.value || !adminEmail?.value) {
                e.preventDefault();
                alert('Please save your email settings first before testing!\n\nDebug info:\nSMTP Host: ' + (smtpHost?.value || 'empty') + '\nSMTP Username: ' + (smtpUsername?.value || 'empty') + '\nAdmin Email: ' + (adminEmail?.value || 'empty'));
                return false;
            }

            const originalText = testEmailBtn.innerHTML;
            testEmailBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
            testEmailBtn.disabled = true;

            setTimeout(() => {
                testEmailBtn.innerHTML = originalText;
                testEmailBtn.disabled = false;
            }, 10000);
        });
    }
});
</script>

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