<?php
/**
 * (c) ININOUT & PYXIS. All Rights Reserved.
 * Wszelkie modyfikacje tego pliku wymagaja zgloszenia oraz zgody autorow.
 * Any modifications to this file require notification and consent of the authors.
 */
/**
 * i-BOK 5 - Panel admina: Konfiguracja SMTP
 */

require_once __DIR__ . '/../inc/smtp.php';

// Obsługa AJAX
if (isset($_GET['action'])) {
    header('Content-Type: application/json; charset=utf-8');
    $action = $_GET['action'];

    if ($action === 'get_config') {
        $config = smtp_load_config();
        // Nie ujawniaj hasła w pełni
        if (!empty($config['password'])) {
            $config['password_set'] = true;
            $config['password'] = '';
        } else {
            $config['password_set'] = false;
        }
        echo json_encode(['success' => true, 'config' => $config]);
        exit;
    }

    if ($action === 'save_config') {
        if (ibok_is_demo()) {
            echo json_encode(['success' => false, 'error' => __('demo.save_blocked')]);
            exit;
        }
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('login.error_csrf')]);
            exit;
        }

        $old_config = smtp_load_config();

        $config = [
            'enabled'    => !empty($_POST['enabled']),
            'host'       => trim($_POST['host'] ?? ''),
            'port'       => (int)($_POST['port'] ?? 587),
            'encryption' => $_POST['encryption'] ?? 'tls',
            'auth'       => !empty($_POST['auth']),
            'username'   => trim($_POST['username'] ?? ''),
            'password'   => $_POST['password'] ?? '',
            'from_email' => trim($_POST['from_email'] ?? ''),
            'from_name'  => trim($_POST['from_name'] ?? ''),
        ];

        // Jeśli hasło puste, zachowaj stare
        if (empty($config['password']) && !empty($old_config['password'])) {
            $config['password'] = $old_config['password'];
        }

        if (smtp_save_config($config)) {
            ibok_log("Konfiguracja SMTP zapisana przez admina", 'info');
            echo json_encode(['success' => true, 'message' => __('smtp.saved')]);
        } else {
            echo json_encode(['success' => false, 'error' => __('smtp.error_save')]);
        }
        exit;
    }

    if ($action === 'test_connection') {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('login.error_csrf')]);
            exit;
        }

        $old_config = smtp_load_config();

        $config = [
            'host'       => trim($_POST['host'] ?? ''),
            'port'       => (int)($_POST['port'] ?? 587),
            'encryption' => $_POST['encryption'] ?? 'tls',
            'auth'       => !empty($_POST['auth']),
            'username'   => trim($_POST['username'] ?? ''),
            'password'   => $_POST['password'] ?? '',
        ];

        // Jeśli hasło puste, użyj zapisanego
        if (empty($config['password']) && !empty($old_config['password'])) {
            $config['password'] = $old_config['password'];
        }

        $result = smtp_test_connection($config);
        echo json_encode($result);
        exit;
    }

    if ($action === 'test_send') {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('login.error_csrf')]);
            exit;
        }

        $testTo = trim($_POST['test_email'] ?? '');
        if (empty($testTo) || !filter_var($testTo, FILTER_VALIDATE_EMAIL)) {
            echo json_encode(['success' => false, 'error' => __('smtp.test_email_required')]);
            exit;
        }

        $old_config = smtp_load_config();

        $config = [
            'host'       => trim($_POST['host'] ?? ''),
            'port'       => (int)($_POST['port'] ?? 587),
            'encryption' => $_POST['encryption'] ?? 'tls',
            'auth'       => !empty($_POST['auth']),
            'username'   => trim($_POST['username'] ?? ''),
            'password'   => $_POST['password'] ?? '',
            'from_email' => trim($_POST['from_email'] ?? ''),
            'from_name'  => trim($_POST['from_name'] ?? ''),
        ];

        // Jeśli hasło puste, użyj zapisanego
        if (empty($config['password']) && !empty($old_config['password'])) {
            $config['password'] = $old_config['password'];
        }

        $result = smtp_test_send($config, $testTo);
        if ($result['success']) {
            ibok_log("Email testowy SMTP wysłany na: {$testTo}", 'info');
        }
        echo json_encode($result);
        exit;
    }

    if ($action === 'get_login_notify') {
        $cfg_file = IBOK_CFG_DIR . '/login_notify.cfg';
        $cfg = ['enabled' => false, 'email' => '', 'notify_client' => true, 'notify_admin' => true, 'min_interval' => 60];
        if (file_exists($cfg_file)) {
            $cfg = array_merge($cfg, @json_decode(file_get_contents($cfg_file), true) ?: []);
        }
        echo json_encode(['success' => true, 'config' => $cfg]);
        exit;
    }

    if ($action === 'save_login_notify') {
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'error' => __('login.error_csrf')]);
            exit;
        }
        $cfg = [
            'enabled'       => !empty($_POST['enabled']),
            'email'         => trim($_POST['email'] ?? ''),
            'notify_client' => !empty($_POST['notify_client']),
            'notify_admin'  => !empty($_POST['notify_admin']),
            'min_interval'  => max(10, (int)($_POST['min_interval'] ?? 60)),
        ];
        $cfg_file = IBOK_CFG_DIR . '/login_notify.cfg';
        if (file_put_contents($cfg_file, json_encode($cfg, JSON_PRETTY_PRINT))) {
            ibok_log("Konfiguracja powiadomień logowania zapisana", 'info');
            echo json_encode(['success' => true, 'message' => __('login_notify.saved')]);
        } else {
            echo json_encode(['success' => false, 'error' => __('smtp.error_save')]);
        }
        exit;
    }

    echo json_encode(['success' => false, 'error' => 'Unknown action']);
    exit;
}
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-envelope-at me-2"></i> <?= __('smtp.title') ?>
    </h4>

    <?= ibok_help_section('admin_smtp', __('help.show_help'), __('help_admin.smtp_section_content')) ?>

    <!-- Status -->
    <div id="smtpStatus" class="mb-4"></div>

    <!-- Alerts -->
    <div id="smtpAlert" class="d-none"></div>

    <div class="row g-4">
        <!-- Formularz konfiguracji -->
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-gear me-1"></i> <?= __('smtp.subtitle') ?>
                </div>
                <div class="card-body">
                    <form id="smtpForm">
                        <?= csrf_field() ?>

                        <!-- Włącz/wyłącz -->
                        <div class="mb-4">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="smtpEnabled" name="enabled">
                                <label class="form-check-label fw-bold" for="smtpEnabled"><?= __('smtp.enabled') ?></label>
                            </div>
                            <small class="text-muted"><?= __('smtp.enabled_desc') ?></small>
                        </div>

                        <div id="smtpFields">
                            <hr>

                            <!-- Serwer -->
                            <div class="row mb-3">
                                <div class="col-md-8">
                                    <label for="smtpHost" class="form-label"><?= __('smtp.host') ?><?= ibok_tooltip(__('help_admin.tooltip_smtp_host')) ?></label>
                                    <input type="text" class="form-control" id="smtpHost" name="host"
                                           placeholder="<?= __('smtp.host_placeholder') ?>">
                                </div>
                                <div class="col-md-4">
                                    <label for="smtpPort" class="form-label"><?= __('smtp.port') ?><?= ibok_tooltip(__('help_admin.tooltip_smtp_port')) ?></label>
                                    <input type="number" class="form-control" id="smtpPort" name="port"
                                           min="1" max="65535" value="587">
                                </div>
                            </div>

                            <!-- Szyfrowanie -->
                            <div class="mb-3">
                                <label for="smtpEncryption" class="form-label"><?= __('smtp.encryption') ?></label>
                                <select class="form-select" id="smtpEncryption" name="encryption">
                                    <option value="tls"><?= __('smtp.encryption_tls') ?></option>
                                    <option value="ssl"><?= __('smtp.encryption_ssl') ?></option>
                                    <option value="none"><?= __('smtp.encryption_none') ?></option>
                                </select>
                            </div>

                            <!-- Uwierzytelnianie -->
                            <div class="mb-3">
                                <div class="form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="smtpAuth" name="auth" checked>
                                    <label class="form-check-label" for="smtpAuth"><?= __('smtp.auth') ?></label>
                                </div>
                                <small class="text-muted"><?= __('smtp.auth_desc') ?></small>
                            </div>

                            <!-- Login / hasło -->
                            <div id="smtpAuthFields">
                                <div class="row mb-3">
                                    <div class="col-md-6">
                                        <label for="smtpUsername" class="form-label"><?= __('smtp.username') ?></label>
                                        <input type="text" class="form-control" id="smtpUsername" name="username"
                                               placeholder="<?= __('smtp.username_placeholder') ?>" autocomplete="off">
                                    </div>
                                    <div class="col-md-6">
                                        <label for="smtpPassword" class="form-label"><?= __('smtp.password') ?></label>
                                        <div class="input-group">
                                            <input type="password" class="form-control" id="smtpPassword" name="password"
                                                   placeholder="&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;&#8226;" autocomplete="new-password">
                                            <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                                <i class="bi bi-eye"></i>
                                            </button>
                                        </div>
                                        <small class="text-muted" id="passwordHint" style="display:none;"></small>
                                    </div>
                                </div>
                            </div>

                            <hr>

                            <!-- Nadawca -->
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="smtpFromEmail" class="form-label"><?= __('smtp.from_email') ?></label>
                                    <input type="email" class="form-control" id="smtpFromEmail" name="from_email"
                                           placeholder="<?= __('smtp.from_email_placeholder') ?>">
                                    <small class="text-muted"><?= __('smtp.from_email_desc') ?></small>
                                </div>
                                <div class="col-md-6">
                                    <label for="smtpFromName" class="form-label"><?= __('smtp.from_name') ?></label>
                                    <input type="text" class="form-control" id="smtpFromName" name="from_name"
                                           placeholder="<?= __('smtp.from_name_placeholder') ?>">
                                </div>
                            </div>
                        </div>

                        <!-- Przyciski -->
                        <div class="d-flex gap-2 mt-4">
                            <button type="submit" class="btn btn-primary" id="btnSave">
                                <i class="bi bi-check-lg me-1"></i> <?= __('smtp.btn_save') ?>
                            </button>
                            <button type="button" class="btn btn-outline-secondary" id="btnTestConn">
                                <i class="bi bi-plug me-1"></i> <?= __('smtp.btn_test_connection') ?>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Panel testowy -->
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-send-check me-1"></i> <?= __('smtp.btn_test') ?>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="testEmail" class="form-label"><?= __('smtp.test_email') ?></label>
                        <input type="email" class="form-control" id="testEmail"
                               placeholder="<?= __('smtp.test_email_placeholder') ?>">
                    </div>
                    <button type="button" class="btn btn-success w-100" id="btnTestSend">
                        <i class="bi bi-envelope-arrow-up me-1"></i> <?= __('smtp.btn_test') ?>
                    </button>
                    <div id="testResult" class="mt-3 d-none"></div>
                </div>
            </div>

            <!-- Popularne serwery SMTP -->
            <div class="card mt-3">
                <div class="card-header">
                    <i class="bi bi-lightbulb me-1"></i> SMTP
                </div>
                <div class="card-body p-0">
                    <table class="table table-sm table-hover mb-0 small">
                        <thead>
                            <tr><th>Serwer</th><th>Host</th><th>Port</th></tr>
                        </thead>
                        <tbody>
                            <tr class="smtp-preset" data-host="smtp.gmail.com" data-port="587" data-enc="tls">
                                <td>Gmail</td><td>smtp.gmail.com</td><td>587</td>
                            </tr>
                            <tr class="smtp-preset" data-host="smtp-mail.outlook.com" data-port="587" data-enc="tls">
                                <td>Outlook</td><td>smtp-mail.outlook.com</td><td>587</td>
                            </tr>
                            <tr class="smtp-preset" data-host="smtp.office365.com" data-port="587" data-enc="tls">
                                <td>Office 365</td><td>smtp.office365.com</td><td>587</td>
                            </tr>
                            <tr class="smtp-preset" data-host="smtp.wp.pl" data-port="465" data-enc="ssl">
                                <td>WP.pl</td><td>smtp.wp.pl</td><td>465</td>
                            </tr>
                            <tr class="smtp-preset" data-host="smtp.poczta.onet.pl" data-port="465" data-enc="ssl">
                                <td>Onet.pl</td><td>smtp.poczta.onet.pl</td><td>465</td>
                            </tr>
                            <tr class="smtp-preset" data-host="smtp.o2.pl" data-port="465" data-enc="ssl">
                                <td>O2.pl</td><td>smtp.o2.pl</td><td>465</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Powiadomienia o nieudanych logowaniach -->
    <div class="row g-4 mt-2">
        <div class="col-lg-8">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-shield-exclamation me-1"></i> <?= __('login_notify.settings_title') ?>
                </div>
                <div class="card-body">
                    <div id="loginNotifyAlert" class="d-none"></div>
                    <form id="loginNotifyForm">
                        <?= csrf_field() ?>

                        <div class="mb-3">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="lnEnabled" name="enabled">
                                <label class="form-check-label fw-bold" for="lnEnabled"><?= __('login_notify.enabled') ?></label>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="lnEmail" class="form-label"><?= __('login_notify.email_address') ?></label>
                            <input type="email" class="form-control" id="lnEmail" name="email" placeholder="admin@example.com">
                        </div>

                        <div class="mb-3">
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="lnClient" name="notify_client" checked>
                                <label class="form-check-label" for="lnClient"><?= __('login_notify.notify_client') ?></label>
                            </div>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" id="lnAdmin" name="notify_admin" checked>
                                <label class="form-check-label" for="lnAdmin"><?= __('login_notify.notify_admin') ?></label>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="lnInterval" class="form-label"><?= __('login_notify.min_interval') ?></label>
                            <input type="number" class="form-control" id="lnInterval" name="min_interval"
                                   value="60" min="10" max="3600" style="max-width: 150px;">
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-1"></i> <?= __('common.save') ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
const SMTP_LANG = {
    saved: '<?= __('smtp.saved') ?>',
    errorSave: '<?= __('smtp.error_save') ?>',
    testSuccess: '<?= __('smtp.test_success') ?>',
    testError: '<?= __('smtp.test_error') ?>',
    testConnSuccess: '<?= __('smtp.test_conn_success') ?>',
    testConnError: '<?= __('smtp.test_conn_error') ?>',
    testEmailRequired: '<?= __('smtp.test_email_required') ?>',
    statusActive: '<?= __('smtp.status_active') ?>',
    statusInactive: '<?= __('smtp.status_inactive') ?>'
};

document.addEventListener('DOMContentLoaded', function() {
    // Wczytaj konfigurację
    loadConfig();

    // Pokaż/ukryj pola SMTP w zależności od checkbox
    $('#smtpEnabled').on('change', function() {
        $('#smtpFields').toggle(this.checked);
    });

    // Pokaż/ukryj pola auth
    $('#smtpAuth').on('change', function() {
        $('#smtpAuthFields').toggle(this.checked);
    });

    // Toggle hasła
    $('#togglePassword').on('click', function() {
        var inp = $('#smtpPassword');
        var icon = $(this).find('i');
        if (inp.attr('type') === 'password') {
            inp.attr('type', 'text');
            icon.removeClass('bi-eye').addClass('bi-eye-slash');
        } else {
            inp.attr('type', 'password');
            icon.removeClass('bi-eye-slash').addClass('bi-eye');
        }
    });

    // Zmiana szyfrowania -> zmiana portu
    $('#smtpEncryption').on('change', function() {
        var val = $(this).val();
        if (val === 'tls') $('#smtpPort').val(587);
        else if (val === 'ssl') $('#smtpPort').val(465);
        else $('#smtpPort').val(25);
    });

    // Presety SMTP
    $('.smtp-preset').on('click', function() {
        $('#smtpHost').val($(this).data('host'));
        $('#smtpPort').val($(this).data('port'));
        $('#smtpEncryption').val($(this).data('enc'));
    });

    // Zapisz
    $('#smtpForm').on('submit', function(e) {
        e.preventDefault();
        saveConfig();
    });

    // Test połączenia
    $('#btnTestConn').on('click', function() {
        testConnection();
    });

    // Test wysyłki
    $('#btnTestSend').on('click', function() {
        testSend();
    });
});

function loadConfig() {
    $.get('admin.php?page=smtp&action=get_config', function(data) {
        if (data.success) {
            var c = data.config;
            $('#smtpEnabled').prop('checked', c.enabled).trigger('change');
            $('#smtpHost').val(c.host);
            $('#smtpPort').val(c.port);
            $('#smtpEncryption').val(c.encryption);
            $('#smtpAuth').prop('checked', c.auth).trigger('change');
            $('#smtpUsername').val(c.username);
            $('#smtpFromEmail').val(c.from_email);
            $('#smtpFromName').val(c.from_name);

            if (c.password_set) {
                $('#smtpPassword').attr('placeholder', '\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022');
                $('#passwordHint').text('(hasło zapisane)').show();
            }

            updateStatus(c.enabled);
        }
    });
}

function saveConfig() {
    var btn = $('#btnSave');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>...');

    $.post('admin.php?page=smtp&action=save_config', $('#smtpForm').serialize(), function(data) {
        if (data.success) {
            showAlert('success', data.message || SMTP_LANG.saved);
            updateStatus($('#smtpEnabled').is(':checked'));
            if ($('#smtpPassword').val()) {
                $('#smtpPassword').val('');
                $('#passwordHint').text('(hasło zapisane)').show();
            }
        } else {
            showAlert('danger', data.error || SMTP_LANG.errorSave);
        }
    }).fail(function() {
        showAlert('danger', SMTP_LANG.errorSave);
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-check-lg me-1"></i> ' + '<?= __('smtp.btn_save') ?>');
    });
}

function testConnection() {
    var btn = $('#btnTestConn');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>...');

    $.post('admin.php?page=smtp&action=test_connection', $('#smtpForm').serialize(), function(data) {
        if (data.success) {
            showAlert('success', SMTP_LANG.testConnSuccess);
        } else {
            var msg = SMTP_LANG.testConnError.replace(':error', escHtml(data.error || 'Unknown error'));
            if (data.debug) {
                msg += '<br><details class="mt-2"><summary>Debug SMTP</summary><pre class="mb-0 mt-1 small" style="max-height:200px;overflow:auto;white-space:pre-wrap;">' + escHtml(data.debug) + '</pre></details>';
            }
            showAlert('danger', msg);
        }
    }).fail(function() {
        showAlert('danger', SMTP_LANG.testConnError.replace(':error', 'Network error'));
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-plug me-1"></i> ' + '<?= __('smtp.btn_test_connection') ?>');
    });
}

function testSend() {
    var email = $('#testEmail').val().trim();
    if (!email) {
        $('#testResult').removeClass('d-none alert-success alert-danger').addClass('alert alert-warning').text(SMTP_LANG.testEmailRequired);
        return;
    }

    var btn = $('#btnTestSend');
    btn.prop('disabled', true).html('<span class="spinner-border spinner-border-sm me-1"></span>...');

    var formData = $('#smtpForm').serialize() + '&test_email=' + encodeURIComponent(email);

    $.post('admin.php?page=smtp&action=test_send', formData, function(data) {
        if (data.success) {
            $('#testResult').removeClass('d-none alert-danger alert-warning').addClass('alert alert-success').html(SMTP_LANG.testSuccess);
        } else {
            var msg = SMTP_LANG.testError.replace(':error', escHtml(data.error || 'Unknown error'));
            if (data.debug) {
                msg += '<br><details class="mt-2"><summary>Debug SMTP</summary><pre class="mb-0 mt-1 small" style="max-height:200px;overflow:auto;white-space:pre-wrap;">' + escHtml(data.debug) + '</pre></details>';
            }
            $('#testResult').removeClass('d-none alert-success alert-warning').addClass('alert alert-danger').html(msg);
        }
    }).fail(function() {
        $('#testResult').removeClass('d-none alert-success alert-warning').addClass('alert alert-danger').text('Network error');
    }).always(function() {
        btn.prop('disabled', false).html('<i class="bi bi-envelope-arrow-up me-1"></i> ' + '<?= __('smtp.btn_test') ?>');
    });
}

function showAlert(type, msg) {
    $('#smtpAlert').removeClass('d-none alert-success alert-danger alert-warning alert-info')
        .addClass('alert alert-' + type + ' alert-dismissible fade show')
        .html(msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>');
}

function updateStatus(enabled) {
    if (enabled) {
        $('#smtpStatus').html('<div class="alert alert-success mb-0"><i class="bi bi-check-circle me-1"></i> <strong>' + SMTP_LANG.statusActive + '</strong></div>');
    } else {
        $('#smtpStatus').html('<div class="alert alert-secondary mb-0"><i class="bi bi-info-circle me-1"></i> ' + SMTP_LANG.statusInactive + '</div>');
    }
}

function escHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}

// Login notify form
document.addEventListener('DOMContentLoaded', function() {
    // Load config
    $.get('admin.php?page=smtp&action=get_login_notify', function(data) {
        if (data.success) {
            var c = data.config;
            $('#lnEnabled').prop('checked', c.enabled);
            $('#lnEmail').val(c.email);
            $('#lnClient').prop('checked', c.notify_client);
            $('#lnAdmin').prop('checked', c.notify_admin);
            $('#lnInterval').val(c.min_interval);
        }
    });

    // Save
    $('#loginNotifyForm').on('submit', function(e) {
        e.preventDefault();
        $.post('admin.php?page=smtp&action=save_login_notify', $(this).serialize(), function(data) {
            var el = $('#loginNotifyAlert');
            if (data.success) {
                el.removeClass('d-none alert-danger').addClass('alert alert-success alert-dismissible fade show')
                  .html((data.message || 'OK') + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>');
            } else {
                el.removeClass('d-none alert-success').addClass('alert alert-danger alert-dismissible fade show')
                  .html((data.error || 'Error') + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>');
            }
        });
    });
});
</script>
