<?php
require_once '../config/cors.php';
require_once '../config/database.php';
require_once '../utils/helpers.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

// Extract authorization token
$token = getAuthToken();

// Validate token
$user = getUserFromToken($token);
if (!$user) {
    errorResponse('User not authenticated', 401);
}

// Check if user is admin
if (!isAdmin($user['id'])) {
    errorResponse('Unauthorized: Admin access required', 403);
}

// Validate action
if (!isset($input['action'])) {
    errorResponse('Action is required', 400);
}

$action = $input['action'];

try {
    switch ($action) {
        case 'get':
            // Get active SMTP settings
            $stmt = $pdo->prepare("SELECT * FROM smtp_settings WHERE is_active = TRUE LIMIT 1");
            $stmt->execute();
            $settings = $stmt->fetch();
            
            jsonResponse(['settings' => $settings], 200);
            break;
            
        case 'save':
            $settingsData = isset($input['settings']) ? $input['settings'] : null;
            
            if (!$settingsData) {
                errorResponse('Settings data is required', 400);
            }
            
            // Start transaction
            $pdo->beginTransaction();
            
            try {
                // Deactivate all existing configs
                $stmt = $pdo->prepare("UPDATE smtp_settings SET is_active = FALSE");
                $stmt->execute();
                
                // Check if settings already exist for this provider
                $stmt = $pdo->prepare("SELECT id FROM smtp_settings WHERE provider = ? LIMIT 1");
                $stmt->execute([$settingsData['provider']]);
                $existing = $stmt->fetch();
                
                if ($existing) {
                    // Update existing settings with all fields
                    $updateFields = [
                        'host' => isset($settingsData['host']) ? $settingsData['host'] : '',
                        'port' => isset($settingsData['port']) ? $settingsData['port'] : 587,
                        'username' => isset($settingsData['username']) ? $settingsData['username'] : '',
                        'password' => isset($settingsData['password']) ? $settingsData['password'] : '',
                        'from_email' => $settingsData['from_email'],
                        'from_name' => $settingsData['from_name'],
                        'api_key' => isset($settingsData['api_key']) ? $settingsData['api_key'] : '',
                        'service_id' => isset($settingsData['service_id']) ? $settingsData['service_id'] : '',
                        'template_id' => isset($settingsData['template_id']) ? $settingsData['template_id'] : '',
                        'user_id' => isset($settingsData['user_id']) ? $settingsData['user_id'] : ''
                    ];
                    
                    $stmt = $pdo->prepare("
                        UPDATE smtp_settings 
                        SET host = ?, port = ?, username = ?, password = ?, 
                            from_email = ?, from_name = ?, api_key = ?, 
                            service_id = ?, template_id = ?, user_id = ?,
                            is_active = TRUE, updated_at = datetime('now') 
                        WHERE id = ?
                    ");
                    $stmt->execute([
                        $updateFields['host'],
                        $updateFields['port'],
                        $updateFields['username'],
                        $updateFields['password'],
                        $updateFields['from_email'],
                        $updateFields['from_name'],
                        $updateFields['api_key'],
                        $updateFields['service_id'],
                        $updateFields['template_id'],
                        $updateFields['user_id'],
                        $existing['id']
                    ]);
                    $settingsId = $existing['id'];
                } else {
                    // Insert new settings
                    $settingsId = generateUUID();
                    $stmt = $pdo->prepare("
                        INSERT INTO smtp_settings 
                        (id, provider, host, port, username, password, from_email, from_name, 
                        api_key, service_id, template_id, user_id, is_active) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, TRUE)
                    ");
                    $stmt->execute([
                        $settingsId,
                        $settingsData['provider'],
                        isset($settingsData['host']) ? $settingsData['host'] : '',
                        isset($settingsData['port']) ? $settingsData['port'] : 587,
                        isset($settingsData['username']) ? $settingsData['username'] : '',
                        isset($settingsData['password']) ? $settingsData['password'] : '',
                        $settingsData['from_email'],
                        $settingsData['from_name'],
                        isset($settingsData['api_key']) ? $settingsData['api_key'] : '',
                        isset($settingsData['service_id']) ? $settingsData['service_id'] : '',
                        isset($settingsData['template_id']) ? $settingsData['template_id'] : '',
                        isset($settingsData['user_id']) ? $settingsData['user_id'] : ''
                    ]);
                }
                
                // Commit transaction
                $pdo->commit();
                
                // Fetch the saved settings
                $stmt = $pdo->prepare("SELECT * FROM smtp_settings WHERE id = ?");
                $stmt->execute([$settingsId]);
                $savedSettings = $stmt->fetch();
                
                jsonResponse(['settings' => $savedSettings], 200);
            } catch (Exception $e) {
                // Rollback transaction
                $pdo->rollback();
                throw $e;
            }
            break;
            
        default:
            errorResponse('Invalid action', 400);
    }
} catch (Exception $e) {
    errorResponse('Error managing email settings: ' . $e->getMessage(), 500);
}
?>