<?php
require_once 'config.php';
$adminId = requireAdminAuth();
$admin = getCurrentAdmin();

$pdo = getDBConnection();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $maintenanceMode = isset($_POST['maintenance_mode']) ? 1 : 0;
    $maintenanceTitle = trim($_POST['maintenance_title'] ?? 'Under Construction');
    $maintenanceMessage = trim($_POST['maintenance_message'] ?? '');
    $appVersion = trim($_POST['app_version'] ?? '1.0.0');
    $forceUpdate = isset($_POST['force_update']) ? 1 : 0;
    
    try {
        $pdo->beginTransaction();
        
        // Update settings
        $stmt = $pdo->prepare("UPDATE app_settings SET setting_value = ? WHERE setting_key = ?");
        $stmt->execute([$maintenanceMode, 'maintenance_mode']);
        $stmt->execute([$maintenanceTitle, 'maintenance_title']);
        $stmt->execute([$maintenanceMessage, 'maintenance_message']);
        $stmt->execute([$appVersion, 'app_version']);
        $stmt->execute([$forceUpdate, 'force_update']);
        
        $pdo->commit();
        $successMessage = "Settings updated successfully!";
    } catch (Exception $e) {
        $pdo->rollBack();
        $errorMessage = "Error updating settings: " . $e->getMessage();
    }
}

// Get current settings
$stmt = $pdo->query("SELECT setting_key, setting_value FROM app_settings");
$settings = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>App Settings - Admin Panel</title>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif; background: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; padding: 20px; }
        .header { background: #6366f1; color: white; padding: 20px; border-radius: 12px; margin-bottom: 30px; }
        .card { background: white; padding: 30px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); margin-bottom: 20px; }
        h1 { font-size: 28px; margin-bottom: 8px; }
        h2 { font-size: 20px; margin-bottom: 20px; color: #333; }
        .subtitle { opacity: 0.9; font-size: 14px; }
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .alert-success { background: #d1fae5; color: #065f46; border: 1px solid #10b981; }
        .alert-error { background: #fee2e2; color: #991b1b; border: 1px solid #ef4444; }
        .form-group { margin-bottom: 25px; }
        label { display: block; font-weight: 600; margin-bottom: 8px; color: #374151; }
        input[type="text"], textarea { width: 100%; padding: 12px; border: 2px solid #e5e7eb; border-radius: 8px; font-size: 14px; font-family: inherit; }
        input[type="text"]:focus, textarea:focus { outline: none; border-color: #6366f1; }
        textarea { min-height: 100px; resize: vertical; }
        .switch-container { display: flex; align-items: center; gap: 15px; padding: 15px; background: #f9fafb; border-radius: 8px; }
        .switch { position: relative; display: inline-block; width: 60px; height: 34px; }
        .switch input { opacity: 0; width: 0; height: 0; }
        .slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #ccc; transition: .4s; border-radius: 34px; }
        .slider:before { position: absolute; content: ""; height: 26px; width: 26px; left: 4px; bottom: 4px; background-color: white; transition: .4s; border-radius: 50%; }
        input:checked + .slider { background-color: #6366f1; }
        input:checked + .slider:before { transform: translateX(26px); }
        .status-badge { display: inline-block; padding: 6px 12px; border-radius: 20px; font-size: 12px; font-weight: 600; }
        .status-active { background: #fee2e2; color: #991b1b; }
        .status-inactive { background: #d1fae5; color: #065f46; }
        .btn { padding: 12px 24px; border: none; border-radius: 8px; font-size: 15px; font-weight: 600; cursor: pointer; transition: all 0.3s; }
        .btn-primary { background: #6366f1; color: white; }
        .btn-primary:hover { background: #4f46e5; transform: translateY(-2px); box-shadow: 0 4px 12px rgba(99,102,241,0.3); }
        .btn-secondary { background: #e5e7eb; color: #374151; margin-left: 10px; }
        .btn-secondary:hover { background: #d1d5db; }
        .info-box { background: #eff6ff; border-left: 4px solid #3b82f6; padding: 15px; border-radius: 8px; margin-bottom: 20px; }
        .nav { background: white; padding: 15px 20px; border-radius: 8px; margin-bottom: 20px; }
        .nav a { color: #6366f1; text-decoration: none; margin-right: 20px; font-weight: 500; }
        .nav a:hover { text-decoration: underline; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🛠️ App Settings & Maintenance</h1>
            <p class="subtitle">Control app behavior and maintenance mode</p>
        </div>

        <div class="nav">
            <a href="dashboard.php">← Back to Dashboard</a>
            <a href="users.php">Users</a>
            <a href="sessions.php">Sessions</a>
            <a href="logout.php">Logout</a>
        </div>

        <?php if (isset($successMessage)): ?>
            <div class="alert alert-success">✅ <?= htmlspecialchars($successMessage) ?></div>
        <?php endif; ?>

        <?php if (isset($errorMessage)): ?>
            <div class="alert alert-error">❌ <?= htmlspecialchars($errorMessage) ?></div>
        <?php endif; ?>

        <div class="card">
            <h2>🚧 Maintenance Mode</h2>
            
            <div class="info-box">
                <strong>ℹ️ How it works:</strong><br>
                When enabled, all users will see the maintenance screen instead of the app. Use this during updates, bug fixes, or emergencies.
            </div>

            <form method="POST">
                <div class="form-group">
                    <div class="switch-container">
                        <label class="switch">
                            <input type="checkbox" name="maintenance_mode" id="maintenance_mode" 
                                   <?= ($settings['maintenance_mode'] ?? 0) == 1 ? 'checked' : '' ?>>
                            <span class="slider"></span>
                        </label>
                        <div>
                            <strong>Maintenance Mode</strong>
                            <div style="font-size: 13px; color: #6b7280;">
                                Current Status: 
                                <span id="status-badge" class="status-badge <?= ($settings['maintenance_mode'] ?? 0) == 1 ? 'status-active' : 'status-inactive' ?>">
                                    <?= ($settings['maintenance_mode'] ?? 0) == 1 ? '🔴 ACTIVE' : '🟢 INACTIVE' ?>
                                </span>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="maintenance_title">Maintenance Screen Title</label>
                    <input type="text" id="maintenance_title" name="maintenance_title" 
                           value="<?= htmlspecialchars($settings['maintenance_title'] ?? 'Under Construction') ?>">
                </div>

                <div class="form-group">
                    <label for="maintenance_message">Maintenance Message</label>
                    <textarea id="maintenance_message" name="maintenance_message" 
                              placeholder="Tell users why the app is under maintenance..."><?= htmlspecialchars($settings['maintenance_message'] ?? '') ?></textarea>
                    <small style="color: #6b7280;">This message will be shown to users during maintenance.</small>
                </div>

                <hr style="margin: 30px 0; border: none; border-top: 1px solid #e5e7eb;">

                <h2>📱 App Version Control</h2>

                <div class="form-group">
                    <label for="app_version">Current App Version</label>
                    <input type="text" id="app_version" name="app_version" 
                           value="<?= htmlspecialchars($settings['app_version'] ?? '1.0.0') ?>" 
                           placeholder="1.0.0">
                    <small style="color: #6b7280;">For tracking and future update enforcement.</small>
                </div>

                <div class="form-group">
                    <div class="switch-container">
                        <label class="switch">
                            <input type="checkbox" name="force_update" id="force_update" 
                                   <?= ($settings['force_update'] ?? 0) == 1 ? 'checked' : '' ?>>
                            <span class="slider"></span>
                        </label>
                        <div>
                            <strong>Force Update</strong>
                            <div style="font-size: 13px; color: #6b7280;">
                                Require users to update to the latest version
                            </div>
                        </div>
                    </div>
                </div>

                <div style="margin-top: 30px;">
                    <button type="submit" class="btn btn-primary">💾 Save Settings</button>
                    <button type="button" class="btn btn-secondary" onclick="location.reload()">↻ Reset</button>
                </div>
            </form>
        </div>
    </div>

    <script>
        // Update status badge when toggle changes
        document.getElementById('maintenance_mode').addEventListener('change', function() {
            const badge = document.getElementById('status-badge');
            if (this.checked) {
                badge.className = 'status-badge status-active';
                badge.textContent = '🔴 ACTIVE';
            } else {
                badge.className = 'status-badge status-inactive';
                badge.textContent = '🟢 INACTIVE';
            }
        });
    </script>
</body>
</html>
