<?php
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../config/constants.php';
require_once __DIR__ . '/../../includes/functions.php';
require_once __DIR__ . '/../../includes/auth_admin.php';
require_once __DIR__ . '/../../includes/audit.php';

apply_cors();
$admin = require_super_admin(); // SMTP credentials are sensitive
$pdo = getDbConnection();
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    $stmt = $pdo->query('SELECT * FROM smtp_settings WHERE id = 1');
    $row = $stmt->fetch();
    if ($row && !empty($row['smtp_password'])) {
        $row['smtp_password'] = str_repeat('*', 8);
    }
    send_success(['smtp' => $row]);
}

if ($method === 'POST' || $method === 'PUT') {
    $input = get_json_input();
    require_fields($input, ['smtp_host', 'smtp_port', 'smtp_username', 'sender_name', 'sender_email']);

    $fields = [
        'smtp_host = :host', 'smtp_port = :port', 'smtp_encryption = :encryption',
        'smtp_username = :username', 'sender_name = :sender_name', 'sender_email = :sender_email',
    ];
    $params = [
        ':host' => clean_str($input['smtp_host']),
        ':port' => (int) $input['smtp_port'],
        ':encryption' => in_array($input['smtp_encryption'] ?? 'SSL', ['SSL', 'TLS', 'NONE'], true) ? $input['smtp_encryption'] : 'SSL',
        ':username' => clean_str($input['smtp_username']),
        ':sender_name' => clean_str($input['sender_name']),
        ':sender_email' => clean_str($input['sender_email']),
    ];

    // Only update password if a new, non-masked value was actually provided
    if (!empty($input['smtp_password']) && strpos($input['smtp_password'], '*') === false) {
        $fields[] = 'smtp_password = :password';
        $params[':password'] = $input['smtp_password'];
    }

    $stmt = $pdo->prepare('UPDATE smtp_settings SET ' . implode(', ', $fields) . ' WHERE id = 1');
    $stmt->execute($params);

    log_admin_action($admin['email'], 'UPDATE_SMTP_SETTINGS', '', 'host=' . $input['smtp_host']);
    send_success(null, 'SMTP settings updated.');
}

send_error('Invalid request.', 400);
