<?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 bazy danych MySQL/MariaDB
 */

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

    if ($action === 'get_config') {
        $config = db_load_config();
        $real_password = $config['password'] ?? '';
        // Nie ujawniaj hasła w pełni
        if (!empty($config['password'])) {
            $config['password_set'] = true;
            $config['password'] = '';
        } else {
            $config['password_set'] = false;
        }
        // Dodaj status połączenia
        if (!empty($config['host']) && !empty($config['username'])) {
            $test_config = $config;
            $test_config['password'] = $real_password;
            $test = db_test_connection($test_config);
            $config['connection_ok'] = $test['success'];
            $config['server_version'] = $test['version'];
        } else {
            $config['connection_ok'] = false;
            $config['server_version'] = '';
        }
        // Statystyki tabel
        $config['table_stats'] = db_table_stats();
        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 = db_load_config();

        $config = [
            'enabled'  => !empty($_POST['enabled']),
            'host'     => trim($_POST['host'] ?? 'localhost'),
            'port'     => (int)($_POST['port'] ?? 3306),
            'database' => trim($_POST['database'] ?? ''),
            'username' => trim($_POST['username'] ?? ''),
            'password' => $_POST['password'] ?? '',
            'charset'  => 'utf8mb4',
        ];

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

        $save_result = db_save_config($config);
        if ($save_result) {
            ibok_log("Konfiguracja bazy danych zapisana przez admina", 'info');
            echo json_encode(['success' => true, 'message' => __('database.saved')]);
        } else {
            $dir = defined('IBOK_CFG_DIR') ? IBOK_CFG_DIR : IBOK_ROOT . '/cfg';
            $debug = '';
            if (!is_dir($dir)) {
                $debug = ' (katalog nie istnieje: ' . $dir . ')';
            } elseif (!is_writable($dir)) {
                $debug = ' (brak uprawnień zapisu do: ' . $dir . ')';
            }
            echo json_encode(['success' => false, 'error' => __('database.error_save') . $debug]);
        }
        exit;
    }

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

        $old_config = db_load_config();

        $config = [
            'host'     => trim($_POST['host'] ?? 'localhost'),
            'port'     => (int)($_POST['port'] ?? 3306),
            'database' => trim($_POST['database'] ?? ''),
            'username' => trim($_POST['username'] ?? ''),
            'password' => $_POST['password'] ?? '',
            'charset'  => 'utf8mb4',
        ];

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

        $result = db_test_connection($config);

        if ($result['success']) {
            echo json_encode([
                'success' => true,
                'message' => str_replace(':version', $result['version'], __('database.test_success')),
                'version' => $result['version'],
            ]);
        } else {
            echo json_encode([
                'success' => false,
                'error' => str_replace(':error', $result['message'], __('database.test_error')),
            ]);
        }
        exit;
    }

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

// Renderowanie strony
$config = db_load_config();
?>

<div class="row">
    <div class="col-12">
        <h4 class="mb-1"><i class="bi bi-database me-2"></i><?= __('database.title') ?></h4>
        <p class="text-muted mb-4"><?= __('database.subtitle') ?></p>
        <?= ibok_help_section('admin_database', __('help.show_help'), __('help_admin.database_section_content')) ?>
    </div>
</div>

<div class="row">
    <!-- Kolumna lewa: Formularz -->
    <div class="col-lg-8">
        <form id="dbConfigForm" autocomplete="off">
            <?= csrf_field() ?>

            <!-- Tryb danych - zawsze MySQL -->
            <input type="hidden" name="enabled" value="1">

            <!-- Konfiguracja połączenia -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-plug me-1"></i> MySQL / MariaDB
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <label for="dbHost" class="form-label"><?= __('database.host') ?></label>
                            <input type="text" class="form-control" id="dbHost" name="host"
                                   value="<?= e($config['host']) ?>" placeholder="<?= __('database.host_placeholder') ?>">
                        </div>
                        <div class="col-md-4">
                            <label for="dbPort" class="form-label"><?= __('database.port') ?></label>
                            <input type="number" class="form-control" id="dbPort" name="port"
                                   value="<?= e($config['port']) ?>" min="1" max="65535">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label for="dbName" class="form-label"><?= __('database.db_name') ?></label>
                        <input type="text" class="form-control" id="dbName" name="database"
                               value="<?= e($config['database']) ?>" placeholder="<?= __('database.db_name_placeholder') ?>">
                    </div>

                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="dbUser" class="form-label"><?= __('database.username') ?></label>
                            <input type="text" class="form-control" id="dbUser" name="username"
                                   value="<?= e($config['username']) ?>" placeholder="<?= __('database.username_placeholder') ?>">
                        </div>
                        <div class="col-md-6">
                            <label for="dbPass" class="form-label"><?= __('database.password') ?></label>
                            <input type="password" class="form-control" id="dbPass" name="password"
                                   placeholder="<?= !empty($config['password']) ? '********' : '' ?>">
                        </div>
                    </div>

                    <div class="d-flex gap-2">
                        <button type="button" class="btn btn-outline-primary" id="btnTest">
                            <i class="bi bi-lightning me-1"></i> <?= __('database.btn_test') ?>
                        </button>
                    </div>

                    <div id="testResult" class="mt-3" style="display:none;"></div>
                </div>
            </div>

            <!-- Przyciski -->
            <div class="d-flex gap-2 mb-4">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-check-lg me-1"></i> <?= __('database.btn_save') ?>
                </button>
                <a href="admin.php?page=db_import" class="btn btn-outline-secondary">
                    <i class="bi bi-box-arrow-in-down me-1"></i> <?= __('database.import_link') ?>
                </a>
            </div>

            <div id="saveResult" style="display:none;"></div>
        </form>
    </div>

    <!-- Kolumna prawa: Status -->
    <div class="col-lg-4">
        <div class="card mb-4" id="statusCard">
            <div class="card-header">
                <i class="bi bi-activity me-1"></i> <?= __('database.status') ?>
            </div>
            <div class="card-body" id="statusBody">
                <div class="text-center text-muted py-3">
                    <div class="spinner-border spinner-border-sm" role="status"></div>
                    <?= __('common.loading') ?>
                </div>
            </div>
        </div>

        <div class="card" id="tableStatsCard" style="display:none;">
            <div class="card-header">
                <i class="bi bi-table me-1"></i> <?= __('database.table_stats') ?>
            </div>
            <div class="card-body p-0">
                <table class="table table-sm table-hover mb-0">
                    <thead>
                        <tr>
                            <th><?= __('database.table_name') ?></th>
                            <th class="text-end"><?= __('database.table_rows') ?></th>
                        </tr>
                    </thead>
                    <tbody id="tableStatsBody"></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
document.addEventListener('DOMContentLoaded', function() {
    // Załaduj status
    loadStatus();

    // Test połączenia
    document.getElementById('btnTest').addEventListener('click', function() {
        var btn = this;
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm"></span> ...';

        $.ajax({
            url: 'admin.php?page=database&action=test_connection',
            method: 'POST',
            data: $('#dbConfigForm').serialize(),
            dataType: 'json',
            success: function(res) {
                var cls = res.success ? 'alert-success' : 'alert-danger';
                var icon = res.success ? 'bi-check-circle' : 'bi-x-circle';
                var msg = res.success ? res.message : res.error;
                var el = document.getElementById('testResult');
                el.innerHTML = '<div class="alert ' + cls + '"><i class="bi ' + icon + ' me-1"></i> ' + escHtml(msg) + '</div>';
                el.style.display = '';
            },
            error: function(xhr) {
                var detail = xhr.responseText ? ' (' + xhr.status + ': ' + xhr.responseText.substring(0, 200) + ')' : '';
                var el = document.getElementById('testResult');
                el.innerHTML = '<div class="alert alert-danger"><i class="bi bi-x-circle me-1"></i> <?= __("common.error") ?>' + escHtml(detail) + '</div>';
                el.style.display = '';
            },
            complete: function() {
                btn.disabled = false;
                btn.innerHTML = '<i class="bi bi-lightning me-1"></i> <?= __("database.btn_test") ?>';
            }
        });
    });

    // Zapisz konfigurację
    document.getElementById('dbConfigForm').addEventListener('submit', function(e) {
        e.preventDefault();
        var data = $(this).serialize();

        $.ajax({
            url: 'admin.php?page=database&action=save_config',
            method: 'POST',
            data: data,
            dataType: 'json',
            success: function(res) {
                var cls = res.success ? 'alert-success' : 'alert-danger';
                var msg = res.success ? res.message : res.error;
                var icon = res.success ? 'bi-check-circle' : 'bi-x-circle';
                var el = document.getElementById('saveResult');
                el.innerHTML = '<div class="alert ' + cls + '"><i class="bi ' + icon + ' me-1"></i> ' + escHtml(msg) + '</div>';
                el.style.display = '';
                if (res.success) {
                    loadStatus();
                    setTimeout(function() { el.style.display = 'none'; }, 3000);
                }
            },
            error: function(xhr) {
                var detail = xhr.responseText ? ' (' + xhr.status + ': ' + xhr.responseText.substring(0, 200) + ')' : '';
                var el = document.getElementById('saveResult');
                el.innerHTML = '<div class="alert alert-danger"><i class="bi bi-x-circle me-1"></i> <?= __("common.error") ?>' + escHtml(detail) + '</div>';
                el.style.display = '';
            }
        });
    });

    function loadStatus() {
        $.ajax({
            url: 'admin.php?page=database&action=get_config',
            dataType: 'json',
            success: function(res) {
                if (!res.success) return;
                var c = res.config;

                var html = '';
                if (c.connection_ok) {
                    html += '<div class="mb-2"><span class="badge bg-success"><i class="bi bi-check-circle me-1"></i><?= __("database.status_ok") ?></span></div>';
                    html += '<div class="mb-2"><small class="text-muted"><?= __("database.server_version") ?>:</small><br><strong>' + escHtml(c.server_version) + '</strong></div>';
                } else {
                    html += '<div class="mb-2"><span class="badge bg-secondary"><i class="bi bi-x-circle me-1"></i><?= __("database.status_error") ?></span></div>';
                }
                html += '<div class="mb-0"><small class="text-muted"><?= __("database.mode") ?>:</small><br><strong>MySQL / MariaDB</strong></div>';

                document.getElementById('statusBody').innerHTML = html;

                // Statystyki tabel
                var stats = c.table_stats || {};
                var keys = Object.keys(stats);
                if (keys.length > 0) {
                    var tbody = '';
                    keys.sort();
                    for (var i = 0; i < keys.length; i++) {
                        tbody += '<tr><td><code>' + escHtml(keys[i]) + '</code></td><td class="text-end">' + stats[keys[i]] + '</td></tr>';
                    }
                    document.getElementById('tableStatsBody').innerHTML = tbody;
                    document.getElementById('tableStatsCard').style.display = '';
                } else {
                    document.getElementById('tableStatsCard').style.display = 'none';
                }
            }
        });
    }

    function escHtml(s) {
        if (!s) return '';
        var div = document.createElement('span');
        div.textContent = s;
        return div.innerHTML;
    }
});
</script>
