<?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: Informacje o bazie PYXIS
 *
 * Wyświetla statystyki tabel PYXIS używanych przez iBOK.
 * Import nie jest potrzebny — tryb MySQL czyta bezpośrednio z tabel PYXIS.
 */

// Obsługa AJAX — odśwież statystyki
if (isset($_GET['action']) && $_GET['action'] === 'refresh_stats') {
    header('Content-Type: application/json; charset=utf-8');

    $pdo = db_get_pdo();
    if (!$pdo) {
        echo json_encode(['success' => false, 'error' => __('database.import_no_connection')]);
        exit;
    }

    try {
        // Tabele PYXIS z liczbą rekordów
        $tables = [
            'Userdb'              => 'Klienci',
            'Fv'                  => 'Faktury',
            'Fvk'                 => 'Korekty',
            'Oplaty'              => 'Płatności',
            'Mac'                 => 'Urządzenia klientów',
            'Infrastruktura'      => 'Infrastruktura sieciowa',
            'ZleceniaSerwisowe'   => 'Zlecenia serwisowe',
            'Operator'            => 'Operatorzy (admin)',
            'Podmioty'            => 'Podmioty (firma)',
            'Taryfy'              => 'Taryfy',
        ];

        $stats = [];
        foreach ($tables as $table => $label) {
            try {
                $row = $pdo->query("SELECT COUNT(*) AS cnt FROM `{$table}`")->fetch();
                $stats[] = [
                    'table' => $table,
                    'label' => $label,
                    'count' => (int)$row['cnt'],
                ];
            } catch (PDOException $e) {
                $stats[] = [
                    'table' => $table,
                    'label' => $label,
                    'count' => -1,
                    'error' => $e->getMessage(),
                ];
            }
        }

        // Widoki (views)
        $views = ['vUserdb', 'vFvLista', 'vFvkLista', 'vOplatyLista', 'vPzLista', 'vListaDokumentow', 'vListaNierozliczonychDokumentow', 'vNotyLista', 'vMac', 'vZleceniaLista', 'vInfrastruktura'];
        $available_views = [];
        foreach ($views as $view) {
            try {
                $pdo->query("SELECT 1 FROM `{$view}` LIMIT 0");
                $available_views[] = $view;
            } catch (PDOException $e) {
                // widok nie istnieje
            }
        }

        echo json_encode([
            'success' => true,
            'stats'   => $stats,
            'views'   => $available_views,
        ]);
    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}

// Renderowanie strony
$pdo = db_get_pdo();
$has_connection = ($pdo !== null);
?>

<div class="row">
    <div class="col-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="admin.php?page=database"><?= __('database.title') ?></a></li>
                <li class="breadcrumb-item active"><?= __('database.import_link') ?></li>
            </ol>
        </nav>

        <h4 class="mb-1"><i class="bi bi-database-check me-2"></i><?= __('database.import_title') ?></h4>
        <p class="text-muted mb-4"><?= __('database.import_subtitle_pyxis') ?? 'Statystyki tabel PYXIS używanych przez iBOK' ?></p>
        <?= ibok_help_section('admin_import', __('help.show_help'), __('help_admin.import_section_content')) ?>
    </div>
</div>

<?php if (!$has_connection): ?>
    <div class="alert alert-warning">
        <i class="bi bi-exclamation-triangle me-1"></i>
        <?= __('database.import_no_connection') ?>
        <a href="admin.php?page=database" class="alert-link ms-1"><?= __('database.title') ?></a>
    </div>
<?php else: ?>

    <div class="row">
        <div class="col-lg-8">
            <div class="alert alert-info">
                <i class="bi bi-info-circle me-1"></i>
                Tryb MySQL czyta dane bezpośrednio z tabel PYXIS — import nie jest potrzebny.
            </div>

            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-table me-1"></i> Tabele PYXIS</span>
                    <button type="button" class="btn btn-sm btn-outline-primary" id="btnRefresh">
                        <i class="bi bi-arrow-clockwise me-1"></i> Odśwież
                    </button>
                </div>
                <div class="card-body p-0" id="statsBody">
                    <div class="text-center text-muted py-4">
                        <div class="spinner-border spinner-border-sm" role="status"></div>
                        <?= __('common.loading') ?>
                    </div>
                </div>
            </div>

            <div class="card" id="viewsCard" style="display:none;">
                <div class="card-header">
                    <i class="bi bi-eye me-1"></i> Dostępne widoki (Views)
                </div>
                <div class="card-body" id="viewsBody"></div>
            </div>
        </div>
    </div>

    <script nonce="<?= csp_nonce() ?>">
    document.addEventListener('DOMContentLoaded', function() {
        loadStats();

        document.getElementById('btnRefresh').addEventListener('click', function() {
            loadStats();
        });

        function loadStats() {
            var statsBody = document.getElementById('statsBody');
            statsBody.innerHTML = '<div class="text-center text-muted py-4"><div class="spinner-border spinner-border-sm" role="status"></div> <?= __("common.loading") ?></div>';

            $.ajax({
                url: 'admin.php?page=db_import&action=refresh_stats',
                dataType: 'json',
                success: function(res) {
                    if (!res.success) {
                        statsBody.innerHTML = '<div class="alert alert-danger m-3">' + escHtml(res.error) + '</div>';
                        return;
                    }

                    var html = '<table class="table table-sm table-hover mb-0">';
                    html += '<thead><tr><th>Tabela</th><th>Opis</th><th class="text-end">Rekordów</th></tr></thead><tbody>';

                    var total = 0;
                    var stats = res.stats || [];
                    for (var i = 0; i < stats.length; i++) {
                        var s = stats[i];
                        var cnt = s.count;
                        var cls = cnt < 0 ? 'text-danger' : '';
                        var val = cnt < 0 ? '<i class="bi bi-x-circle text-danger"></i>' : cnt;
                        if (cnt > 0) total += cnt;
                        html += '<tr><td><code>' + escHtml(s.table) + '</code></td>';
                        html += '<td class="text-muted">' + escHtml(s.label) + '</td>';
                        html += '<td class="text-end ' + cls + '">' + val + '</td></tr>';
                    }
                    html += '<tr class="table-active fw-bold"><td colspan="2">Razem</td><td class="text-end">' + total + '</td></tr>';
                    html += '</tbody></table>';
                    statsBody.innerHTML = html;

                    // Views
                    var views = res.views || [];
                    if (views.length > 0) {
                        var vhtml = '';
                        for (var j = 0; j < views.length; j++) {
                            vhtml += '<span class="badge bg-success me-1 mb-1"><i class="bi bi-check me-1"></i>' + escHtml(views[j]) + '</span>';
                        }
                        document.getElementById('viewsBody').innerHTML = vhtml;
                        document.getElementById('viewsCard').style.display = '';
                    }
                },
                error: function(xhr) {
                    statsBody.innerHTML = '<div class="alert alert-danger m-3"><?= __("common.error") ?></div>';
                }
            });
        }

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

<?php endif; ?>
