<?php
/**
 * MSPE Settings API
 */

require_once 'config.php';

$method = $_SERVER['REQUEST_METHOD'];

// Require authentication for all settings operations
requireAuth();

switch ($method) {
    case 'GET':
        getSettings();
        break;
        
    case 'POST':
        saveSettings();
        break;
        
    default:
        jsonResponse(['success' => false, 'message' => 'Method not allowed'], 405);
}

function getSettings() {
    global $db;
    
    // Check if settings file exists, if not return defaults
    $settings = $db->getAll('settings');
    $flatSettings = [];
    
    // Convert from array of objects to key-value pairs if needed
    // or just return as is if stored as key-value object
    if (empty($settings)) {
        // Defaults
        $flatSettings = [
            'site_name' => 'MSPE',
            'site_tagline' => 'Architects of Digital Resilience',
            'site_description' => 'MSPE transforms complexity into competitive advantage.',
            'contact_email' => 'info@mspe.pro',
            'contact_phone' => '+961 78 782 023',
            'contact_address' => '',
            'business_hours' => 'Mon - Fri: 9AM - 6PM',
            'support_hours' => 'Mon - Fri: 9AM - 6PM (On-call by arrangement)',
            'admin_email' => 'info@mspe.pro',
            'email_transport' => 'mail',
            'smtp_from_name' => 'MSPE',
            'smtp_from_email' => 'info@mspe.pro',
            'smtp_host' => '',
            'smtp_port' => '587',
            'smtp_encryption' => 'tls',
            'smtp_username' => '',
            'smtp_password' => '',
            'password_reset_url' => SITE_URL . '/admin/reset-password.html',
            'primary_color' => '#0ea5e9',
            'secondary_color' => '#0d9488'
        ];
    } else {
        // Assuming settings are stored as a single object in index 0 or key-value pairs
        // Let's assume key-value for simplicity in this file-based DB
        // But FileDB::getAll returns an indexed array of items.
        // So we'll store settings as: [ {key: 'site_name', value: 'MSPE'}, ... ]
        foreach ($settings as $setting) {
            if (isset($setting['key']) && isset($setting['value'])) {
                $flatSettings[$setting['key']] = $setting['value'];
            }
        }
    }
    
    jsonResponse(['success' => true, 'data' => $flatSettings]);
}

function saveSettings() {
    global $db;
    requireSameOriginRequest();
    $data = getRequestBody();
    
    if (empty($data)) {
        jsonResponse(['success' => false, 'message' => 'No data provided'], 400);
    }
    
    // Get existing settings to update or insert
    $existingSettings = $db->getAll('settings');
    $existingMap = [];
    
    foreach ($existingSettings as $index => $setting) {
        $existingMap[$setting['key']] = $setting['id'];
    }
    
    foreach ($data as $key => $value) {
        if (isset($existingMap[$key])) {
            // Update
            $db->update('settings', $existingMap[$key], ['value' => $value]);
        } else {
            // Insert
            $db->insert('settings', ['key' => $key, 'value' => $value]);
        }
    }
    
    jsonResponse(['success' => true, 'message' => 'Settings saved successfully']);
}
