<?php
/**
 * admin/maintenance-mode.php - System Maintenance Mode Control
 */

require_once __DIR__ . '/includes/base.php';

if (!hasAdminPermission('manage_maintenance')) {
    setFlashMessage('Access denied.', 'error');
    header('Location: ' . APP_URL . '/admin/index.php');
    exit();
}

$breadcrumbs = [['title' => 'Maintenance Mode', 'url' => '']];

// Get current maintenance status
try {
    $sql = "SELECT * FROM system_settings WHERE setting_key = 'maintenance_mode' LIMIT 1";
    $stmt = $db->query($sql);
    $setting = $stmt->fetch(PDO::FETCH_ASSOC);
    
    $isMaintenanceMode = $setting && json_decode($setting['setting_value'], true)['enabled'] ?? false;
    $maintenanceConfig = $setting ? json_decode($setting['setting_value'], true) : [
        'enabled' => false,
        'message' => 'System is currently under maintenance. Please check back later.',
        'allowed_ips' => [],
        'start_time' => null,
        'end_time' => null
    ];
} catch (PDOException $e) {
    $isMaintenanceMode = false;
    $maintenanceConfig = ['enabled' => false];
}

renderAdminHeader('Maintenance Mode', $breadcrumbs);
?>

<style>
.maintenance-status {
    padding: 3rem;
    text-align: center;
    border-radius: 12px;
    margin-bottom: 2rem;
}
.maintenance-status.active {
    background: linear-gradient(135deg, #fca5a5 0%, #ef4444 100%);
    color: white;
}
.maintenance-status.inactive {
    background: linear-gradient(135deg, #86efac 0%, #22c55e 100%);
    color: white;
}
</style>

<!-- Current Status -->
<div class="maintenance-status <?php echo $isMaintenanceMode ? 'active' : 'inactive'; ?>">
    <div class="mb-3">
        <i class="bi bi-<?php echo $isMaintenanceMode ? 'tools' : 'check-circle-fill'; ?>" style="font-size: 4rem;"></i>
    </div>
    <h2 class="fw-bold mb-2">Maintenance Mode is <?php echo $isMaintenanceMode ? 'ACTIVE' : 'INACTIVE'; ?></h2>
    <p class="mb-0">
        <?php if ($isMaintenanceMode): ?>
            System is currently in maintenance mode. Only admins and whitelisted IPs can access.
        <?php else: ?>
            System is operating normally. All users have full access.
        <?php endif; ?>
    </p>
    
    <?php if ($isMaintenanceMode && isset($maintenanceConfig['end_time'])): ?>
    <div class="mt-3">
        <small>Scheduled to end: <?php echo date('F j, Y g:i A', strtotime($maintenanceConfig['end_time'])); ?></small>
    </div>
    <?php endif; ?>
</div>

<!-- Control Panel -->
<div class="row">
    <div class="col-md-8">
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 fw-bold">Maintenance Configuration</h5>
            </div>
            <div class="card-body">
                <form id="maintenanceForm">
                    <!-- Enable/Disable -->
                    <div class="mb-4">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" id="enable_maintenance" 
                                   name="enabled" <?php echo $isMaintenanceMode ? 'checked' : ''; ?> 
                                   style="width: 3em; height: 1.5em;">
                            <label class="form-check-label fw-bold" for="enable_maintenance">
                                Enable Maintenance Mode
                            </label>
                        </div>
                        <small class="text-muted">When enabled, only administrators and whitelisted IPs can access the system</small>
                    </div>
                    
                    <!-- Maintenance Message -->
                    <div class="mb-3">
                        <label class="form-label fw-bold">Maintenance Message</label>
                        <textarea class="form-control" name="message" rows="4" required><?php echo htmlspecialchars($maintenanceConfig['message'] ?? ''); ?></textarea>
                        <small class="text-muted">This message will be displayed to users during maintenance</small>
                    </div>
                    
                    <!-- Schedule -->
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label class="form-label fw-bold">Start Time (Optional)</label>
                            <input type="datetime-local" class="form-control" name="start_time" 
                                   value="<?php echo isset($maintenanceConfig['start_time']) ? date('Y-m-d\TH:i', strtotime($maintenanceConfig['start_time'])) : ''; ?>">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label fw-bold">End Time (Optional)</label>
                            <input type="datetime-local" class="form-control" name="end_time"
                                   value="<?php echo isset($maintenanceConfig['end_time']) ? date('Y-m-d\TH:i', strtotime($maintenanceConfig['end_time'])) : ''; ?>">
                        </div>
                    </div>
                    
                    <!-- Allowed IPs -->
                    <div class="mb-4">
                        <label class="form-label fw-bold">Whitelisted IP Addresses</label>
                        <div id="ipList" class="mb-2">
                            <?php 
                            $allowedIPs = $maintenanceConfig['allowed_ips'] ?? [];
                            if (is_array($allowedIPs) && count($allowedIPs) > 0):
                                foreach ($allowedIPs as $ip): ?>
                                <div class="input-group mb-2 ip-entry">
                                    <input type="text" class="form-control" name="allowed_ips[]" value="<?php echo htmlspecialchars($ip); ?>">
                                    <button class="btn btn-outline-danger" type="button" onclick="removeIP(this)">
                                        <i class="bi bi-x"></i>
                                    </button>
                                </div>
                            <?php endforeach;
                            endif; ?>
                        </div>
                        <button type="button" class="btn btn-outline-primary btn-sm" onclick="addIP()">
                            <i class="bi bi-plus-circle me-1"></i>Add IP Address
                        </button>
                        <div class="mt-2">
                            <small class="text-muted">Your current IP: <code><?php echo $_SERVER['REMOTE_ADDR']; ?></code></small>
                            <button type="button" class="btn btn-link btn-sm p-0 ms-2" onclick="addCurrentIP()">Add</button>
                        </div>
                    </div>
                    
                    <!-- Actions -->
                    <div class="d-flex gap-2">
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-save me-2"></i>Save Configuration
                        </button>
                        
                        <?php if ($isMaintenanceMode): ?>
                        <button type="button" class="btn btn-success" onclick="disableMaintenanceNow()">
                            <i class="bi bi-play-circle me-2"></i>Disable Now
                        </button>
                        <?php else: ?>
                        <button type="button" class="btn btn-warning" onclick="enableMaintenanceNow()">
                            <i class="bi bi-pause-circle me-2"></i>Enable Now
                        </button>
                        <?php endif; ?>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <div class="col-md-4">
        <!-- Quick Actions -->
        <div class="card border-0 shadow-sm mb-3">
            <div class="card-header bg-white">
                <h6 class="mb-0 fw-bold">Quick Actions</h6>
            </div>
            <div class="card-body">
                <div class="d-grid gap-2">
                    <button class="btn btn-outline-warning" onclick="schedule15Min()">
                        <i class="bi bi-clock me-2"></i>Schedule 15 Min
                    </button>
                    <button class="btn btn-outline-warning" onclick="schedule1Hour()">
                        <i class="bi bi-clock me-2"></i>Schedule 1 Hour
                    </button>
                    <button class="btn btn-outline-warning" onclick="scheduleOvernight()">
                        <i class="bi bi-moon me-2"></i>Overnight (2AM-6AM)
                    </button>
                    <button class="btn btn-outline-info" onclick="notifyUsers()">
                        <i class="bi bi-bell me-2"></i>Notify All Users
                    </button>
                </div>
            </div>
        </div>
        
        <!-- Info Panel -->
        <div class="card border-0 shadow-sm">
            <div class="card-header bg-white">
                <h6 class="mb-0 fw-bold">Best Practices</h6>
            </div>
            <div class="card-body">
                <ul class="small mb-0">
                    <li class="mb-2">Schedule maintenance during off-peak hours</li>
                    <li class="mb-2">Notify users in advance via email</li>
                    <li class="mb-2">Whitelist your IP before enabling</li>
                    <li class="mb-2">Set a clear end time for automatic disable</li>
                    <li class="mb-2">Test maintenance page appearance first</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<script>
$('#maintenanceForm').submit(function(e) {
    e.preventDefault();
    
    const formData = {};
    formData.enabled = $('#enable_maintenance').is(':checked');
    formData.message = $('[name="message"]').val();
    formData.start_time = $('[name="start_time"]').val();
    formData.end_time = $('[name="end_time"]').val();
    formData.allowed_ips = [];
    $('[name="allowed_ips[]"]').each(function() {
        if ($(this).val()) formData.allowed_ips.push($(this).val());
    });
    
    showLoading();
    $.post(APP_URL + '/api/admin.php', {
        action: 'update_maintenance_mode',
        config: JSON.stringify(formData)
    }, function(response) {
        hideLoading();
        if (response.success) {
            showToast(response.message, 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast(response.message, 'error');
        }
    });
});

function addIP() {
    $('#ipList').append(`
        <div class="input-group mb-2 ip-entry">
            <input type="text" class="form-control" name="allowed_ips[]" placeholder="192.168.1.1">
            <button class="btn btn-outline-danger" type="button" onclick="removeIP(this)">
                <i class="bi bi-x"></i>
            </button>
        </div>
    `);
}

function removeIP(btn) {
    $(btn).closest('.ip-entry').remove();
}

function addCurrentIP() {
    $('#ipList').append(`
        <div class="input-group mb-2 ip-entry">
            <input type="text" class="form-control" name="allowed_ips[]" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>">
            <button class="btn btn-outline-danger" type="button" onclick="removeIP(this)">
                <i class="bi bi-x"></i>
            </button>
        </div>
    `);
}

function enableMaintenanceNow() {
    Swal.fire({
        title: 'Enable Maintenance Mode?',
        text: 'This will restrict access to admins and whitelisted IPs',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#f59e0b',
        confirmButtonText: 'Enable Now'
    }).then((result) => {
        if (result.isConfirmed) {
            $('#enable_maintenance').prop('checked', true);
            $('#maintenanceForm').submit();
        }
    });
}

function disableMaintenanceNow() {
    Swal.fire({
        title: 'Disable Maintenance Mode?',
        text: 'System will return to normal operation',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#22c55e',
        confirmButtonText: 'Disable Now'
    }).then((result) => {
        if (result.isConfirmed) {
            $('#enable_maintenance').prop('checked', false);
            $('#maintenanceForm').submit();
        }
    });
}

function schedule15Min() {
    const start = new Date();
    const end = new Date(start.getTime() + 15 * 60000);
    $('[name="start_time"]').val(start.toISOString().slice(0, 16));
    $('[name="end_time"]').val(end.toISOString().slice(0, 16));
}

function schedule1Hour() {
    const start = new Date();
    const end = new Date(start.getTime() + 60 * 60000);
    $('[name="start_time"]').val(start.toISOString().slice(0, 16));
    $('[name="end_time"]').val(end.toISOString().slice(0, 16));
}

function scheduleOvernight() {
    const start = new Date();
    start.setHours(2, 0, 0, 0);
    if (start <= new Date()) start.setDate(start.getDate() + 1);
    
    const end = new Date(start);
    end.setHours(6, 0, 0, 0);
    
    $('[name="start_time"]').val(start.toISOString().slice(0, 16));
    $('[name="end_time"]').val(end.toISOString().slice(0, 16));
}

function notifyUsers() {
    Swal.fire({
        title: 'Notify Users',
        html: `
            <textarea id="notification_message" class="form-control" rows="4" 
                      placeholder="Enter notification message..."></textarea>
        `,
        showCancelButton: true,
        confirmButtonText: 'Send Notification'
    }).then((result) => {
        if (result.isConfirmed) {
            const message = $('#notification_message').val();
            if (message) {
                $.post(APP_URL + '/api/admin.php', {
                    action: 'send_maintenance_notification',
                    message: message
                }, function(response) {
                    showToast(response.message, response.success ? 'success' : 'error');
                });
            }
        }
    });
}
</script>

<?php renderAdminFooter(); ?>