<?php
/**
 * Admin - System Settings
 */
require_once __DIR__ . '/../config.php';
require_admin_login();

$page_title = 'System Settings';
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token($_POST['csrf_token'] ?? '')) {
        $errors[] = 'Invalid security token';
    } else {
        // Update all system settings
        $settings = [
            'maintenance_mode' => ['value' => isset($_POST['maintenance_mode']) ? 1 : 0, 'type' => 'boolean'],
            'maintenance_message' => ['value' => sanitize($_POST['maintenance_message'] ?? ''), 'type' => 'string'],
            'registration_enabled' => ['value' => isset($_POST['registration_enabled']) ? 1 : 0, 'type' => 'boolean'],
            'social_login_enabled' => ['value' => isset($_POST['social_login_enabled']) ? 1 : 0, 'type' => 'boolean'],
            'email_verification_required' => ['value' => isset($_POST['email_verification_required']) ? 1 : 0, 'type' => 'boolean'],
            'otp_enabled' => ['value' => isset($_POST['otp_enabled']) ? 1 : 0, 'type' => 'boolean'],
            'max_login_attempts' => ['value' => intval($_POST['max_login_attempts'] ?? 5), 'type' => 'integer'],
            'lockout_duration_minutes' => ['value' => intval($_POST['lockout_duration_minutes'] ?? 30), 'type' => 'integer'],
            'session_timeout_minutes' => ['value' => intval($_POST['session_timeout_minutes'] ?? 120), 'type' => 'integer'],
            'password_min_length' => ['value' => intval($_POST['password_min_length'] ?? 8), 'type' => 'integer'],
            'require_strong_password' => ['value' => isset($_POST['require_strong_password']) ? 1 : 0, 'type' => 'boolean'],
            'newsletter_popup_enabled' => ['value' => isset($_POST['newsletter_popup_enabled']) ? 1 : 0, 'type' => 'boolean'],
            'newsletter_popup_delay_seconds' => ['value' => intval($_POST['newsletter_popup_delay_seconds'] ?? 10), 'type' => 'integer'],
            'announcement_bar_enabled' => ['value' => isset($_POST['announcement_bar_enabled']) ? 1 : 0, 'type' => 'boolean'],
            'announcement_bar_message' => ['value' => sanitize($_POST['announcement_bar_message'] ?? ''), 'type' => 'string'],
            'announcement_bar_link' => ['value' => sanitize($_POST['announcement_bar_link'] ?? ''), 'type' => 'string'],
            'popup_banner_enabled' => ['value' => isset($_POST['popup_banner_enabled']) ? 1 : 0, 'type' => 'boolean'],
            'live_chat_enabled' => ['value' => isset($_POST['live_chat_enabled']) ? 1 : 0, 'type' => 'boolean'],
        ];
        
        $updated = 0;
        try {
            db()->beginTransaction();
            
            foreach ($settings as $key => $data) {
                // Check if setting exists
                $check = db()->prepare("SELECT id FROM system_settings WHERE setting_key = ?");
                $check->execute([$key]);
                
                if ($check->fetch()) {
                    // Update existing
                    $stmt = db()->prepare("UPDATE system_settings SET setting_value = ?, data_type = ?, updated_at = NOW() WHERE setting_key = ?");
                    $stmt->execute([$data['value'], $data['type'], $key]);
                } else {
                    // Insert new
                    $stmt = db()->prepare("INSERT INTO system_settings (setting_key, setting_value, data_type, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())");
                    $stmt->execute([$key, $data['value'], $data['type']]);
                }
                $updated++;
            }
            
            db()->commit();
            
            // Log activity
            log_activity('system_settings_updated', "Updated $updated system settings", $_SESSION['admin_id'], 'admin');
            
        } catch (PDOException $e) {
            db()->rollBack();
            error_log("System settings update error: " . $e->getMessage());
            $errors[] = 'Failed to save system settings. Please try again.';
        }
        
        if (empty($errors)) {
            $success = 'System settings updated successfully (' . $updated . ' settings saved)';
        }
    }
}

// Get current settings
$settings = [];
$keys = [
    'maintenance_mode', 'maintenance_message', 'registration_enabled', 'social_login_enabled',
    'email_verification_required', 'otp_enabled', 'max_login_attempts', 'lockout_duration_minutes',
    'session_timeout_minutes', 'password_min_length', 'require_strong_password',
    'newsletter_popup_enabled', 'newsletter_popup_delay_seconds', 'announcement_bar_enabled',
    'announcement_bar_message', 'announcement_bar_link', 'popup_banner_enabled', 'live_chat_enabled'
];

foreach ($keys as $key) {
    $settings[$key] = get_system_setting($key);
}

$csrf_token = generate_csrf_token();
include __DIR__ . '/includes/header.php';
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <h2 class="fw-bold mb-0">System Settings</h2>
</div>

<?php if (!empty($errors)): ?>
    <div class="alert alert-danger alert-dismissible fade show">
        <?php foreach ($errors as $error): ?><p class="mb-0"><?php echo $error; ?></p><?php endforeach; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>
<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show">
        <i class="bi bi-check-circle-fill me-2"></i><?php echo $success; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
<?php endif; ?>

<div class="card border-0 shadow-sm">
    <div class="card-body p-4">
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
            
            <h5 class="mb-3">Maintenance Mode</h5>
            <div class="row g-3 mb-4">
                <div class="col-md-6">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="maintenance_mode" class="form-check-input" id="maintenance_mode" <?php echo $settings['maintenance_mode'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="maintenance_mode">Enable Maintenance Mode</label>
                    </div>
                    <small class="text-muted">When enabled, only admins can access the site.</small>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Maintenance Message</label>
                    <textarea name="maintenance_message" class="form-control" rows="2"><?php echo $settings['maintenance_message']; ?></textarea>
                </div>
            </div>
            
            <h5 class="mb-3">User Registration</h5>
            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="registration_enabled" class="form-check-input" id="registration_enabled" <?php echo $settings['registration_enabled'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="registration_enabled">Allow New Registrations</label>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="email_verification_required" class="form-check-input" id="email_verification_required" <?php echo $settings['email_verification_required'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="email_verification_required">Require Email Verification</label>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="social_login_enabled" class="form-check-input" id="social_login_enabled" <?php echo $settings['social_login_enabled'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="social_login_enabled">Enable Social Login</label>
                    </div>
                </div>
            </div>
            
            <h5 class="mb-3">Security Settings</h5>
            <div class="row g-3 mb-4">
                <div class="col-md-3">
                    <label class="form-label">Max Login Attempts</label>
                    <input type="number" name="max_login_attempts" class="form-control" value="<?php echo $settings['max_login_attempts']; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Lockout Duration (minutes)</label>
                    <input type="number" name="lockout_duration_minutes" class="form-control" value="<?php echo $settings['lockout_duration_minutes']; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Session Timeout (minutes)</label>
                    <input type="number" name="session_timeout_minutes" class="form-control" value="<?php echo $settings['session_timeout_minutes']; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Password Min Length</label>
                    <input type="number" name="password_min_length" class="form-control" value="<?php echo $settings['password_min_length']; ?>">
                </div>
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="require_strong_password" class="form-check-input" id="require_strong_password" <?php echo $settings['require_strong_password'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="require_strong_password">Require Strong Passwords</label>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="otp_enabled" class="form-check-input" id="otp_enabled" <?php echo $settings['otp_enabled'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="otp_enabled">Enable OTP Verification</label>
                    </div>
                </div>
            </div>
            
            <h5 class="mb-3">Marketing Features</h5>
            <div class="row g-3 mb-4">
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="newsletter_popup_enabled" class="form-check-input" id="newsletter_popup_enabled" <?php echo $settings['newsletter_popup_enabled'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="newsletter_popup_enabled">Newsletter Popup</label>
                    </div>
                </div>
                <div class="col-md-4">
                    <label class="form-label">Popup Delay (seconds)</label>
                    <input type="number" name="newsletter_popup_delay_seconds" class="form-control" value="<?php echo $settings['newsletter_popup_delay_seconds']; ?>">
                </div>
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="announcement_bar_enabled" class="form-check-input" id="announcement_bar_enabled" <?php echo $settings['announcement_bar_enabled'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="announcement_bar_enabled">Announcement Bar</label>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label">Announcement Message</label>
                    <input type="text" name="announcement_bar_message" class="form-control" value="<?php echo $settings['announcement_bar_message']; ?>">
                </div>
                <div class="col-md-6">
                    <label class="form-label">Announcement Link</label>
                    <input type="text" name="announcement_bar_link" class="form-control" value="<?php echo $settings['announcement_bar_link']; ?>">
                </div>
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="popup_banner_enabled" class="form-check-input" id="popup_banner_enabled" <?php echo $settings['popup_banner_enabled'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="popup_banner_enabled">Popup Banner/Modal</label>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-check form-switch">
                        <input type="checkbox" name="live_chat_enabled" class="form-check-input" id="live_chat_enabled" <?php echo $settings['live_chat_enabled'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="live_chat_enabled">Live Chat Widget</label>
                    </div>
                </div>
            </div>
            
            <div class="mt-4">
                <button type="submit" class="btn btn-primary"><i class="bi bi-save me-2"></i>Save Settings</button>
            </div>
        </form>
    </div>
</div>

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