<?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 - Analityka superadmina (ukryta strona z tokenem)
 *
 * URL: admin.php?page=analytics&token=HASH
 * Nie widoczna w menu nawigacji. 5 zakładek: Przegląd, Finanse, Klienci, Operacyjne, Ryzyko.
 */

// --- Kontrola dostępu --- ukryte dla serwisantów (dane finansowe firmy)
if (is_service_user()) {
    echo '<div class="container py-5"><div class="alert alert-danger text-center">';
    echo '<h4><i class="bi bi-shield-lock"></i> ' . __('analytics.access_denied') . '</h4>';
    echo '<p>' . __('analytics.access_denied_msg') . '</p>';
    echo '</div></div>';
    return;
}

if ($token_just_generated) {
    $full_url = 'admin.php?page=analytics&token=' . $valid_token;
    echo '<div class="container py-5"><div class="alert alert-success">';
    echo '<h5><i class="bi bi-key"></i> ' . __('analytics.token_generated') . '</h5>';
    echo '<code class="d-block p-2 bg-dark text-light rounded mb-3" style="font-size:0.85rem;word-break:break-all;">' . e($valid_token) . '</code>';
    echo '<p>' . __('analytics.token_bookmark') . '</p>';
    echo '<a href="' . e($full_url) . '" class="btn btn-primary"><i class="bi bi-bookmark"></i> ' . e($full_url) . '</a>';
    echo '</div></div>';
    return;
}

// AJAX: renderuj treść analityki
if (isset($_GET['action']) && $_GET['action'] === 'render') {

// --- Load data ---
require_once __DIR__ . '/../inc/stats.php';

$clients = vbk_read_klienci();
$total_clients = count($clients);
$active_count = 0;
$inactive_count = 0;
$total_debt = 0.0;

foreach ($clients as $c) {
    if ($c['active_flag'] === '1') $active_count++;
    else $inactive_count++;
    $total_debt += (float)str_replace(',', '.', $c['saldo_zalegle_raw'] ?? '0');
}

$pdo = db_get_pdo();

// Finance data
$rev_pay = stats_invoices_vs_payments(12);
$mrr = end($rev_pay['invoiced']) ?: 0;
$collection = stats_collection_rate(12);
$current_collection = end($collection['values']) ?: 0;
$debt_trend = stats_debt_trend($clients, 12);
$debt_aging = stats_debt_aging();
$corrections = stats_corrections_by_month(12);
$forecast = stats_revenue_forecast($rev_pay);
$pay_seasonality = stats_payment_day_distribution();

// Invoice status distribution
$all_faktury = [];
if ($pdo) {
    try {
        $stmt = $pdo->query("SELECT FV_KWOTAROZLICZONA, FV_KWOTADOROZLICZENIA FROM vFvLista WHERE FV_DATAWYSTAWIENIA >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) AND FV_DATAWYSTAWIENIA <> '0000-00-00'");
        foreach ($stmt->fetchAll() as $row) {
            $rozl = (float)$row['FV_KWOTAROZLICZONA'];
            $do_rozl = (float)$row['FV_KWOTADOROZLICZENIA'];
            $all_faktury[] = ['status' => $do_rozl <= 0 ? 'paid' : ($rozl > 0 ? 'partial' : 'unpaid')];
        }
    } catch (PDOException $e) {}
}
$invoice_status = stats_invoice_status_dist($all_faktury);

// Payment methods
$all_oplaty = [];
if ($pdo) {
    try {
        $stmt = $pdo->query("SELECT O_FORMAPLATNOSCI FROM vOplatyLista WHERE O_DATAWPLATY >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH) AND O_DATAWPLATY <> '0000-00-00'");
        foreach ($stmt->fetchAll() as $row) {
            $all_oplaty[] = ['forma_platn' => (string)($row['O_FORMAPLATNOSCI'] ?? '')];
        }
    } catch (PDOException $e) {}
}
$payment_methods = stats_payment_methods($all_oplaty);
$top_debtors = stats_top_debtors($clients, 10);

// Client data
$client_growth = stats_client_growth($clients, 12);
$tariff_dist = stats_tariff_distribution($clients);
$geo_dist = stats_geo_distribution($clients, 15);
$client_churn = stats_client_churn($clients, 6);
$retention = stats_client_retention($clients);
$ltv = stats_client_ltv($clients);
$client_type = stats_client_type_distribution($clients);
$churn_rate = stats_churn_rate($clients, 12);
$overpayments = stats_overpayment_distribution($clients);
$contract_dur = stats_contract_duration_distribution($clients);

// Operations data
$zlecenia = db_read_zlecenia();
$service_data = stats_service_resolution($zlecenia, 12);
$service_avg = stats_service_avg_resolution($zlecenia, 12);
$service_cats = stats_service_category_distribution($zlecenia);
$open_tickets = 0;
foreach ($zlecenia as $z) { if (empty($z['data_zakonczenia'])) $open_tickets++; }

$avg_pay_days = 0;
if ($pdo) {
    try {
        $stmt = $pdo->query("SELECT AVG(DATEDIFF(O_DATAWPLATY, FV_DATAWYSTAWIENIA)) AS avg_days FROM vFvLista f JOIN vOplatyLista o ON f.U_NRKLIENTA = o.U_NRKLIENTA WHERE FV_DATAWYSTAWIENIA >= DATE_SUB(CURDATE(), INTERVAL 6 MONTH) AND FV_DATAWYSTAWIENIA <> '0000-00-00' AND O_DATAWPLATY <> '0000-00-00' AND O_DATAWPLATY >= FV_DATAWYSTAWIENIA");
        $row = $stmt->fetch();
        $avg_pay_days = $row ? round((float)$row['avg_days'], 0) : 0;
    } catch (PDOException $e) {}
}

$login_activity = stats_login_activity(30);
$failed_logins = stats_failed_logins_trend(30);
$login_hours = stats_login_hourly(30);

// New finance data
$rev_by_tariff = stats_revenue_by_tariff($clients);
$avg_invoice = stats_avg_invoice_value(12);
$pay_time = stats_payment_time_by_month(12);
$arpu = stats_arpu($clients, 12);
$cashflow = stats_cumulative_cashflow(12);

// New client data
$tenure = stats_client_tenure_dist($clients);
$contract_status = stats_contract_status_dist($clients);
$reg_heatmap = stats_registration_heatmap($clients);
$top_revenue = stats_top_revenue_clients(10);
$no_contract = stats_clients_no_contract($clients);
$cumul_clients = stats_cumulative_clients($clients, 24);

// New operations data
$tickets_priority = stats_tickets_by_priority($zlecenia);
$tickets_weekday = stats_tickets_by_weekday($zlecenia);
$admin_sessions = stats_unique_admin_sessions(30);

// Risk data
$at_risk = stats_at_risk_clients($clients);
$scoring = stats_client_scoring($clients, 50);

// Helpers
$short_labels = function($labels) {
    return array_map(function($k) {
        $parts = explode('-', $k);
        return (count($parts) >= 2) ? $parts[1] . '/' . substr($parts[0], 2) : $k;
    }, $labels);
};
$short_day_labels = function($labels) {
    return array_map(function($k) {
        $parts = explode('-', $k);
        return (count($parts) >= 3) ? $parts[2] . '.' . $parts[1] : $k;
    }, $labels);
};
?>

<div>
<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0"><i class="bi bi-graph-up-arrow"></i> <?= __('analytics.title') ?></h4>
    <div>
        <button class="btn btn-sm btn-outline-info me-2" type="button" data-bs-toggle="offcanvas" data-bs-target="#analyticsHelp">
            <i class="bi bi-question-circle me-1"></i><?= __('analytics.help_btn') ?>
        </button>
    </div>
</div>

<!-- Offcanvas: chart legend -->
<div class="offcanvas offcanvas-end" tabindex="-1" id="analyticsHelp" style="width:420px;">
    <div class="offcanvas-header border-bottom">
        <h5 class="offcanvas-title"><i class="bi bi-info-circle me-2"></i><?= __('analytics.help_title') ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
    </div>
    <div class="offcanvas-body small">
        <!-- KPI -->
        <h6 class="text-primary fw-bold mb-2"><i class="bi bi-speedometer2 me-1"></i><?= __('analytics.help_section_kpi') ?></h6>
        <dl class="mb-4">
            <dt><?= __('analytics.kpi_mrr') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_mrr') ?></dd>
            <dt><?= __('analytics.kpi_total_debt') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_total_debt') ?></dd>
            <dt><?= __('analytics.kpi_collection') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_collection') ?></dd>
            <dt><?= __('analytics.kpi_active_clients') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_active_clients') ?></dd>
            <dt><?= __('analytics.kpi_avg_pay_time') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_avg_pay_time') ?></dd>
            <dt><?= __('analytics.kpi_open_tickets') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_open_tickets') ?></dd>
            <dt><?= __('analytics.kpi_ltv') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_ltv') ?></dd>
            <dt><?= __('analytics.kpi_churn') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_churn') ?></dd>
            <dt><?= __('analytics.kpi_at_risk') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_at_risk') ?></dd>
            <dt><?= __('analytics.kpi_overpayments') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_overpayments') ?></dd>
            <dt><?= __('analytics.kpi_no_contract') ?></dt><dd class="text-muted"><?= __('analytics.help_kpi_no_contract') ?></dd>
        </dl>

        <!-- Finance -->
        <h6 class="text-primary fw-bold mb-2"><i class="bi bi-cash-stack me-1"></i><?= __('analytics.help_section_finance') ?></h6>
        <dl class="mb-4">
            <dt><?= __('analytics.chart_revenue_vs_payments') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_revenue_vs_payments') ?></dd>
            <dt><?= __('analytics.chart_revenue_forecast') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_revenue_forecast') ?></dd>
            <dt><?= __('analytics.chart_debt_trend') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_debt_trend') ?></dd>
            <dt><?= __('analytics.chart_collection_rate') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_collection_rate') ?></dd>
            <dt><?= __('analytics.chart_invoice_status') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_invoice_status') ?></dd>
            <dt><?= __('analytics.chart_debt_aging') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_debt_aging') ?></dd>
            <dt><?= __('analytics.chart_payment_methods') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_payment_methods') ?></dd>
            <dt><?= __('analytics.chart_payment_seasonality') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_payment_seasonality') ?></dd>
            <dt><?= __('analytics.chart_top_debtors') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_top_debtors') ?></dd>
            <dt><?= __('analytics.chart_corrections') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_corrections') ?></dd>
            <dt><?= __('analytics.chart_revenue_by_tariff') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_revenue_by_tariff') ?></dd>
            <dt><?= __('analytics.chart_avg_invoice') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_avg_invoice') ?></dd>
            <dt><?= __('analytics.chart_payment_time') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_payment_time') ?></dd>
            <dt><?= __('analytics.chart_arpu') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_arpu') ?></dd>
            <dt><?= __('analytics.chart_cashflow') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_cashflow') ?></dd>
        </dl>

        <!-- Clients -->
        <h6 class="text-primary fw-bold mb-2"><i class="bi bi-people me-1"></i><?= __('analytics.help_section_clients') ?></h6>
        <dl class="mb-4">
            <dt><?= __('analytics.chart_client_growth') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_client_growth') ?></dd>
            <dt><?= __('analytics.chart_retention') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_retention') ?></dd>
            <dt><?= __('analytics.chart_tariff_dist') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_tariff_dist') ?></dd>
            <dt><?= __('analytics.chart_client_type') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_client_type') ?></dd>
            <dt><?= __('analytics.chart_geo_dist') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_geo_dist') ?></dd>
            <dt><?= __('analytics.chart_churn_rate') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_churn_rate') ?></dd>
            <dt><?= __('analytics.chart_expiring_contracts') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_expiring_contracts') ?></dd>
            <dt><?= __('analytics.chart_contract_duration') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_contract_duration') ?></dd>
            <dt><?= __('analytics.chart_active_inactive') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_active_inactive') ?></dd>
            <dt><?= __('analytics.chart_overpayments') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_overpayments') ?></dd>
            <dt><?= __('analytics.chart_tenure_dist') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_tenure_dist') ?></dd>
            <dt><?= __('analytics.chart_contract_status') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_contract_status') ?></dd>
            <dt><?= __('analytics.chart_registration_heatmap') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_registration_heatmap') ?></dd>
            <dt><?= __('analytics.chart_top_revenue') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_top_revenue') ?></dd>
        </dl>

        <!-- Operations -->
        <h6 class="text-primary fw-bold mb-2"><i class="bi bi-tools me-1"></i><?= __('analytics.help_section_operations') ?></h6>
        <dl class="mb-4">
            <dt><?= __('analytics.chart_service_orders') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_service_orders') ?></dd>
            <dt><?= __('analytics.chart_service_avg_time') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_service_avg_time') ?></dd>
            <dt><?= __('analytics.chart_service_categories') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_service_categories') ?></dd>
            <dt><?= __('analytics.chart_login_activity') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_login_activity') ?></dd>
            <dt><?= __('analytics.chart_failed_logins') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_failed_logins') ?></dd>
            <dt><?= __('analytics.chart_login_hours') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_login_hours') ?></dd>
            <dt><?= __('analytics.chart_cumulative_clients') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_cumulative_clients') ?></dd>
            <dt><?= __('analytics.chart_tickets_priority') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_tickets_priority') ?></dd>
            <dt><?= __('analytics.chart_tickets_weekday') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_tickets_weekday') ?></dd>
            <dt><?= __('analytics.chart_admin_sessions') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_admin_sessions') ?></dd>
        </dl>

        <!-- Risk -->
        <h6 class="text-primary fw-bold mb-2"><i class="bi bi-shield-exclamation me-1"></i><?= __('analytics.help_section_risk') ?></h6>
        <dl class="mb-4">
            <dt><?= __('analytics.chart_at_risk') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_at_risk') ?></dd>
            <dt><?= __('analytics.chart_client_scoring') ?></dt><dd class="text-muted"><?= __('analytics.help_chart_client_scoring') ?></dd>
        </dl>
    </div>
</div>

<!-- Tab navigation -->
<ul class="nav nav-tabs mb-4" id="analyticsTab" role="tablist">
    <li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#tab-overview" role="tab"><i class="bi bi-grid"></i> <?= __('analytics.tab_overview') ?></a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-finance" role="tab"><i class="bi bi-cash-stack"></i> <?= __('analytics.tab_finance') ?></a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-clients" role="tab"><i class="bi bi-people"></i> <?= __('analytics.tab_clients') ?></a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-operations" role="tab"><i class="bi bi-tools"></i> <?= __('analytics.tab_operations') ?></a></li>
    <li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#tab-risk" role="tab"><i class="bi bi-shield-exclamation"></i> <?= __('analytics.tab_risk') ?></a></li>
</ul>

<div class="tab-content" id="analyticsTabContent">

<!-- ==================== TAB: OVERVIEW ==================== -->
<div class="tab-pane fade show active" id="tab-overview" role="tabpanel">
    <div class="row g-3 mb-4">
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_mrr') ?></div>
                <div class="fs-4 fw-bold text-primary"><?= number_format($mrr, 0, ',', ' ') ?> <small class="text-muted fs-6">zł</small></div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_total_debt') ?></div>
                <div class="fs-4 fw-bold text-danger"><?= number_format($total_debt, 0, ',', ' ') ?> <small class="text-muted fs-6">zł</small></div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_collection') ?></div>
                <div class="fs-4 fw-bold text-success"><?= number_format($current_collection, 1) ?>%</div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_active_clients') ?></div>
                <div class="fs-4 fw-bold text-info"><?= $active_count ?> <small class="text-muted fs-6">/ <?= $total_clients ?></small></div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_avg_pay_time') ?></div>
                <div class="fs-4 fw-bold text-warning"><?= $avg_pay_days ?> <small class="text-muted fs-6"><?= __('analytics.kpi_days') ?></small></div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_open_tickets') ?></div>
                <div class="fs-4 fw-bold text-secondary"><?= $open_tickets ?></div>
            </div></div>
        </div>
    </div>
    <div class="row g-3 mb-4">
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_ltv') ?></div>
                <div class="fs-4 fw-bold text-primary"><?= number_format($ltv, 0, ',', ' ') ?> <small class="text-muted fs-6">zł</small></div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_churn') ?></div>
                <?php $last_churn = end($churn_rate['values']) ?: 0; ?>
                <div class="fs-4 fw-bold <?= $last_churn > 2 ? 'text-danger' : 'text-success' ?>"><?= number_format($last_churn, 2) ?>%</div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_at_risk') ?></div>
                <div class="fs-4 fw-bold <?= count($at_risk) > 0 ? 'text-danger' : 'text-success' ?>"><?= count($at_risk) ?></div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_overpayments') ?></div>
                <div class="fs-4 fw-bold text-info"><?= number_format($overpayments['total'], 0, ',', ' ') ?> <small class="text-muted fs-6">zł</small></div>
            </div></div>
        </div>
        <div class="col-lg-2 col-md-4 col-sm-4 col-6">
            <div class="card text-center h-100"><div class="card-body py-3">
                <div class="text-muted small"><?= __('analytics.kpi_no_contract') ?></div>
                <div class="fs-4 fw-bold <?= $no_contract > 0 ? 'text-warning' : 'text-success' ?>"><?= $no_contract ?></div>
            </div></div>
        </div>
    </div>
    <!-- Mini overview charts -->
    <div class="row g-3">
        <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-graph-up"></i> <?= __('analytics.chart_revenue_vs_payments') ?></div><div class="card-body" style="height:280px;"><canvas id="chartOverRevPay"></canvas></div></div></div>
        <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-pie-chart"></i> <?= __('analytics.chart_active_inactive') ?></div><div class="card-body" style="height:280px;"><canvas id="chartOverStatus"></canvas></div></div></div>
    </div>
</div>

<!-- ==================== TAB: FINANCE ==================== -->
<div class="tab-pane fade" id="tab-finance" role="tabpanel">
<div class="row g-3">
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-graph-up"></i> <?= __('analytics.chart_revenue_vs_payments') ?></div><div class="card-body" style="height:300px;"><canvas id="chartRevPay"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-graph-up-arrow"></i> <?= __('analytics.chart_revenue_forecast') ?></div><div class="card-body" style="height:300px;"><canvas id="chartForecast"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-graph-down-arrow"></i> <?= __('analytics.chart_debt_trend') ?></div><div class="card-body" style="height:300px;"><canvas id="chartDebtTrend"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-percent"></i> <?= __('analytics.chart_collection_rate') ?></div><div class="card-body" style="height:300px;"><canvas id="chartCollection"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-pie-chart"></i> <?= __('analytics.chart_invoice_status') ?></div><div class="card-body" style="height:300px;"><canvas id="chartInvStatus"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-clock-history"></i> <?= __('analytics.chart_debt_aging') ?></div><div class="card-body" style="height:300px;"><canvas id="chartDebtAging"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-credit-card"></i> <?= __('analytics.chart_payment_methods') ?></div><div class="card-body" style="height:300px;"><canvas id="chartPayMethods"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-calendar-week"></i> <?= __('analytics.chart_payment_seasonality') ?></div><div class="card-body" style="height:300px;"><canvas id="chartSeasonality"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-exclamation-triangle"></i> <?= __('analytics.chart_top_debtors') ?></div><div class="card-body" style="height:300px;"><canvas id="chartDebtors"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-arrow-return-left"></i> <?= __('analytics.chart_corrections') ?></div><div class="card-body" style="height:300px;"><canvas id="chartCorrections"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-tags"></i> <?= __('analytics.chart_revenue_by_tariff') ?></div><div class="card-body" style="height:300px;"><canvas id="chartRevTariff"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-receipt"></i> <?= __('analytics.chart_avg_invoice') ?></div><div class="card-body" style="height:300px;"><canvas id="chartAvgInvoice"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-stopwatch"></i> <?= __('analytics.chart_payment_time') ?></div><div class="card-body" style="height:300px;"><canvas id="chartPayTime"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-person-lines-fill"></i> <?= __('analytics.chart_arpu') ?></div><div class="card-body" style="height:300px;"><canvas id="chartArpu"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-graph-up"></i> <?= __('analytics.chart_cashflow') ?></div><div class="card-body" style="height:300px;"><canvas id="chartCashflow"></canvas></div></div></div>
</div>
</div>

<!-- ==================== TAB: CLIENTS ==================== -->
<div class="tab-pane fade" id="tab-clients" role="tabpanel">
<div class="row g-3">
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-bar-chart"></i> <?= __('analytics.chart_client_growth') ?></div><div class="card-body" style="height:300px;"><canvas id="chartGrowth"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-arrow-repeat"></i> <?= __('analytics.chart_retention') ?></div><div class="card-body" style="height:300px;"><canvas id="chartRetention"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-speedometer2"></i> <?= __('analytics.chart_tariff_dist') ?></div><div class="card-body" style="height:300px;"><canvas id="chartTariff"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-building"></i> <?= __('analytics.chart_client_type') ?></div><div class="card-body" style="height:300px;"><canvas id="chartClientType"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-geo-alt"></i> <?= __('analytics.chart_geo_dist') ?></div><div class="card-body" style="height:300px;"><canvas id="chartGeo"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-arrow-down-circle"></i> <?= __('analytics.chart_churn_rate') ?></div><div class="card-body" style="height:300px;"><canvas id="chartChurnRate"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-calendar-x"></i> <?= __('analytics.chart_expiring_contracts') ?></div><div class="card-body" style="height:300px;"><canvas id="chartChurn"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-file-earmark-text"></i> <?= __('analytics.chart_contract_duration') ?></div><div class="card-body" style="height:300px;"><canvas id="chartContractDur"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-toggle-on"></i> <?= __('analytics.chart_active_inactive') ?></div><div class="card-body" style="height:300px;"><canvas id="chartActiveInactive"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-wallet2"></i> <?= __('analytics.chart_overpayments') ?></div><div class="card-body" style="height:300px;"><canvas id="chartOverpayments"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-clock-history"></i> <?= __('analytics.chart_tenure_dist') ?></div><div class="card-body" style="height:300px;"><canvas id="chartTenure"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-file-earmark-check"></i> <?= __('analytics.chart_contract_status') ?></div><div class="card-body" style="height:300px;"><canvas id="chartContractStatus"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-calendar-event"></i> <?= __('analytics.chart_registration_heatmap') ?></div><div class="card-body" style="height:300px;"><canvas id="chartRegHeatmap"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-trophy"></i> <?= __('analytics.chart_top_revenue') ?></div><div class="card-body" style="height:300px;"><canvas id="chartTopRevenue"></canvas></div></div></div>
</div>
</div>

<!-- ==================== TAB: OPERATIONS ==================== -->
<div class="tab-pane fade" id="tab-operations" role="tabpanel">
<div class="row g-3">
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-wrench"></i> <?= __('analytics.chart_service_orders') ?></div><div class="card-body" style="height:300px;"><canvas id="chartService"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-hourglass-split"></i> <?= __('analytics.chart_service_avg_time') ?></div><div class="card-body" style="height:300px;"><canvas id="chartServiceAvg"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-diagram-3"></i> <?= __('analytics.chart_service_categories') ?></div><div class="card-body" style="height:300px;"><canvas id="chartServiceCats"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-box-arrow-in-right"></i> <?= __('analytics.chart_login_activity') ?></div><div class="card-body" style="height:300px;"><canvas id="chartLogins"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-shield-exclamation"></i> <?= __('analytics.chart_failed_logins') ?></div><div class="card-body" style="height:300px;"><canvas id="chartFailedLogins"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-clock"></i> <?= __('analytics.chart_login_hours') ?></div><div class="card-body" style="height:300px;"><canvas id="chartLoginHours"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-graph-up-arrow"></i> <?= __('analytics.chart_cumulative_clients') ?></div><div class="card-body" style="height:300px;"><canvas id="chartCumulClients"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-speedometer"></i> <?= __('analytics.chart_tickets_priority') ?></div><div class="card-body" style="height:300px;"><canvas id="chartTicketsPriority"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-calendar-day"></i> <?= __('analytics.chart_tickets_weekday') ?></div><div class="card-body" style="height:300px;"><canvas id="chartTicketsWeekday"></canvas></div></div></div>
    <div class="col-md-6"><div class="card h-100"><div class="card-header"><i class="bi bi-person-badge"></i> <?= __('analytics.chart_admin_sessions') ?></div><div class="card-body" style="height:300px;"><canvas id="chartAdminSessions"></canvas></div></div></div>
</div>
</div>

<!-- ==================== TAB: RISK ==================== -->
<div class="tab-pane fade" id="tab-risk" role="tabpanel">
    <div class="row g-3 mb-4">
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header"><i class="bi bi-exclamation-diamond"></i> <?= __('analytics.chart_at_risk') ?></div>
                <div class="card-body">
                    <p class="text-muted small mb-3"><?= __('analytics.risk_desc') ?></p>
                    <?php if (empty($at_risk)): ?>
                        <div class="alert alert-success"><i class="bi bi-check-circle"></i> <?= __('analytics.label_no_data') ?></div>
                    <?php else: ?>
                        <div class="table-responsive">
                        <table class="table table-sm table-hover">
                            <thead class="table-light"><tr>
                                <th>#</th><th><?= __('service.client') ?></th><th><?= __('analytics.label_debt') ?></th><th><?= __('analytics.label_contracts') ?></th><th><?= __('analytics.kpi_days') ?></th>
                            </tr></thead>
                            <tbody>
                            <?php foreach ($at_risk as $i => $r): ?>
                                <tr>
                                    <td><?= $i + 1 ?></td>
                                    <td><?= e($r['nazwisko']) ?></td>
                                    <td class="text-danger fw-bold"><?= number_format($r['kwota'], 2, ',', ' ') ?> zł</td>
                                    <td><?= e($r['umowa_do']) ?></td>
                                    <td><span class="badge <?= $r['dni_do'] <= 30 ? 'bg-danger' : 'bg-warning text-dark' ?>"><?= $r['dni_do'] ?></span></td>
                                </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="card h-100">
                <div class="card-header"><i class="bi bi-bullseye"></i> <?= __('analytics.chart_client_scoring') ?></div>
                <div class="card-body">
                    <p class="text-muted small mb-2"><?= __('analytics.scoring_desc') ?></p>
                    <div style="height:350px;"><canvas id="chartScoring"></canvas></div>
                </div>
            </div>
        </div>
    </div>
</div>

</div><!-- /tab-content -->

<script nonce="<?= csp_nonce() ?>">
(function() {
    var _dk = document.body.classList.contains('dark-mode');
    var _tc = _dk ? '#f1f5f9' : '#666';
    var _gc = _dk ? 'rgba(255,255,255,0.15)' : 'rgba(0,0,0,0.1)';
    var _bc = _dk ? '#2d3748' : '#fff';

    if (typeof Chart !== 'undefined') {
        Chart.defaults.color = _tc;
        Chart.defaults.borderColor = _gc;
        if (Chart.defaults.plugins.legend && Chart.defaults.plugins.legend.labels) Chart.defaults.plugins.legend.labels.color = _tc;
        if (Chart.defaults.plugins.tooltip) { Chart.defaults.plugins.tooltip.titleColor = '#fff'; Chart.defaults.plugins.tooltip.bodyColor = '#fff'; }
        if (Chart.defaults.scale) { Chart.defaults.scale.ticks.color = _tc; Chart.defaults.scale.grid.color = _gc; }
    }

    var _p = {
        id: 'analyticsLegendColorForce',
        beforeDraw: function(chart) {
            if (!_dk) return;
            if (chart.legend) { chart.legend.options.labels.color = _tc; if (chart.legend.legendItems) chart.legend.legendItems.forEach(function(i) { i.fontColor = _tc; }); }
            if (chart.options && chart.options.scales) Object.values(chart.options.scales).forEach(function(s) { if (s.ticks) s.ticks.color = _tc; if (s.grid) s.grid.color = _gc; });
        }
    };
    if (typeof Chart !== 'undefined') Chart.register(_p);

    var palette = ['rgba(79,70,229,0.8)','rgba(14,165,233,0.8)','rgba(16,185,129,0.8)','rgba(245,158,11,0.8)','rgba(239,68,68,0.8)','rgba(168,85,247,0.8)','rgba(236,72,153,0.8)','rgba(107,114,128,0.8)','rgba(20,184,166,0.8)','rgba(99,102,241,0.8)','rgba(251,146,60,0.8)','rgba(52,211,153,0.8)','rgba(196,181,253,0.8)','rgba(253,186,116,0.8)','rgba(156,163,175,0.8)'];
    var legBot = { position: 'bottom', labels: { color: _tc, fontColor: _tc, boxWidth: 12, padding: 8, font: { size: 11 } } };
    var legTop = { position: 'top', labels: { color: _tc, fontColor: _tc, boxWidth: 12, padding: 8, font: { size: 11 } } };

    function mkLine(id, labels, datasets) {
        var c = document.getElementById(id); if (!c) return;
        new Chart(c.getContext('2d'), { type: 'line', data: { labels: labels, datasets: datasets }, options: { responsive: true, maintainAspectRatio: false, scales: { x: { ticks: { color: _tc, maxRotation: 45 }, grid: { color: _gc } }, y: { beginAtZero: true, ticks: { color: _tc }, grid: { color: _gc } } }, plugins: { legend: legTop } } });
    }
    function mkBar(id, labels, data, color, horiz) {
        var c = document.getElementById(id); if (!c) return;
        var o = { responsive: true, maintainAspectRatio: false, scales: { x: { beginAtZero: true, ticks: { color: _tc }, grid: { color: _gc } }, y: { beginAtZero: true, ticks: { color: _tc }, grid: { color: _gc } } }, plugins: { legend: { display: false } } };
        if (horiz) o.indexAxis = 'y';
        new Chart(c.getContext('2d'), { type: 'bar', data: { labels: labels, datasets: [{ data: data, backgroundColor: color || palette[0], borderWidth: 1 }] }, options: o });
    }
    function mkDoughnut(id, labels, data, colors) {
        var c = document.getElementById(id); if (!c) return;
        new Chart(c.getContext('2d'), { type: 'doughnut', data: { labels: labels, datasets: [{ data: data, backgroundColor: (colors || palette).slice(0, labels.length), borderWidth: 2, borderColor: _bc }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: legBot } } });
    }
    function mkPctLine(id, labels, datasets) {
        var c = document.getElementById(id); if (!c) return;
        new Chart(c.getContext('2d'), { type: 'line', data: { labels: labels, datasets: datasets }, options: { responsive: true, maintainAspectRatio: false, scales: { x: { ticks: { color: _tc, maxRotation: 45 }, grid: { color: _gc } }, y: { beginAtZero: true, max: 100, ticks: { color: _tc, callback: function(v) { return v+'%'; } }, grid: { color: _gc } } }, plugins: { legend: legTop } } });
    }

    // Lazy init: only create charts when tab becomes visible
    var initialized = { overview: false, finance: false, clients: false, operations: false, risk: false };

    function initOverview() {
        if (initialized.overview) return; initialized.overview = true;
        mkLine('chartOverRevPay', <?= json_encode($short_labels($rev_pay['labels'])) ?>, [
            { label: '<?= __('analytics.label_invoiced') ?>', data: <?= json_encode($rev_pay['invoiced']) ?>, borderColor: 'rgba(79,70,229,1)', backgroundColor: 'rgba(79,70,229,0.1)', fill: true, tension: 0.3 },
            { label: '<?= __('analytics.label_paid') ?>', data: <?= json_encode($rev_pay['paid']) ?>, borderColor: 'rgba(16,185,129,1)', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.3 }
        ]);
        mkDoughnut('chartOverStatus', ['<?= __('analytics.label_active') ?>', '<?= __('analytics.label_inactive') ?>'], [<?= $active_count ?>, <?= $inactive_count ?>], ['rgba(16,185,129,0.8)', 'rgba(107,114,128,0.8)']);
    }

    function initFinance() {
        if (initialized.finance) return; initialized.finance = true;
        // Revenue vs Payments
        mkLine('chartRevPay', <?= json_encode($short_labels($rev_pay['labels'])) ?>, [
            { label: '<?= __('analytics.label_invoiced') ?>', data: <?= json_encode($rev_pay['invoiced']) ?>, borderColor: 'rgba(79,70,229,1)', backgroundColor: 'rgba(79,70,229,0.1)', fill: true, tension: 0.3 },
            { label: '<?= __('analytics.label_paid') ?>', data: <?= json_encode($rev_pay['paid']) ?>, borderColor: 'rgba(16,185,129,1)', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.3 }
        ]);
        // Forecast
        mkLine('chartForecast', <?= json_encode($short_labels($forecast['labels'])) ?>, [
            { label: '<?= __('analytics.label_actual') ?>', data: <?= json_encode($forecast['actual']) ?>, borderColor: 'rgba(79,70,229,1)', backgroundColor: 'rgba(79,70,229,0.1)', fill: true, tension: 0.3, spanGaps: false },
            { label: '<?= __('analytics.label_forecast') ?>', data: <?= json_encode($forecast['forecast']) ?>, borderColor: 'rgba(245,158,11,1)', backgroundColor: 'rgba(245,158,11,0.1)', borderDash: [6,3], fill: true, tension: 0.3, spanGaps: false }
        ]);
        // Debt trend
        mkLine('chartDebtTrend', <?= json_encode($short_labels($debt_trend['labels'])) ?>, [{ label: '<?= __('analytics.label_debt') ?>', data: <?= json_encode($debt_trend['values']) ?>, borderColor: 'rgba(239,68,68,1)', backgroundColor: 'rgba(239,68,68,0.1)', fill: true, tension: 0.3 }]);
        // Collection rate
        mkPctLine('chartCollection', <?= json_encode($short_labels($collection['labels'])) ?>, [{ label: '<?= __('analytics.label_rate') ?>', data: <?= json_encode($collection['values']) ?>, borderColor: 'rgba(16,185,129,1)', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.3 }]);
        // Invoice status
        mkDoughnut('chartInvStatus', ['<?= __('analytics.label_paid_full') ?>', '<?= __('analytics.label_paid_partial') ?>', '<?= __('analytics.label_unpaid') ?>'], [<?= $invoice_status['paid'] ?>, <?= $invoice_status['partial'] ?>, <?= $invoice_status['unpaid'] ?>], ['rgba(16,185,129,0.8)', 'rgba(245,158,11,0.8)', 'rgba(239,68,68,0.8)']);
        // Debt aging
        mkDoughnut('chartDebtAging', ['<?= __('analytics.label_0_30') ?>', '<?= __('analytics.label_31_60') ?>', '<?= __('analytics.label_61_90') ?>', '<?= __('analytics.label_90_plus') ?>'], <?= json_encode(array_values($debt_aging)) ?>, ['rgba(16,185,129,0.8)', 'rgba(245,158,11,0.8)', 'rgba(239,68,68,0.8)', 'rgba(127,29,29,0.8)']);
        // Payment methods
        mkDoughnut('chartPayMethods', <?= json_encode(array_keys($payment_methods)) ?>, <?= json_encode(array_values($payment_methods)) ?>);
        // Seasonality
        mkBar('chartSeasonality', <?= json_encode($pay_seasonality['labels']) ?>, <?= json_encode($pay_seasonality['values']) ?>, 'rgba(14,165,233,0.7)');
        // Top debtors
        mkBar('chartDebtors', <?= json_encode(array_map(fn($d) => $d['nazwisko'], $top_debtors)) ?>, <?= json_encode(array_map(fn($d) => $d['kwota'], $top_debtors)) ?>, 'rgba(239,68,68,0.7)', true);
        // Corrections
        mkBar('chartCorrections', <?= json_encode($short_labels($corrections['labels'])) ?>, <?= json_encode($corrections['values']) ?>, 'rgba(168,85,247,0.7)');
        // Revenue by tariff
        mkDoughnut('chartRevTariff', <?= json_encode(array_keys($rev_by_tariff)) ?>, <?= json_encode(array_values($rev_by_tariff)) ?>);
        // Avg invoice
        mkLine('chartAvgInvoice', <?= json_encode($short_labels($avg_invoice['labels'])) ?>, [{ label: '<?= __('analytics.label_avg_value') ?>', data: <?= json_encode($avg_invoice['values']) ?>, borderColor: 'rgba(14,165,233,1)', backgroundColor: 'rgba(14,165,233,0.1)', fill: true, tension: 0.3 }]);
        // Payment time
        mkLine('chartPayTime', <?= json_encode($short_labels($pay_time['labels'])) ?>, [{ label: '<?= __('analytics.label_payment_days') ?>', data: <?= json_encode($pay_time['values']) ?>, borderColor: 'rgba(245,158,11,1)', backgroundColor: 'rgba(245,158,11,0.1)', fill: true, tension: 0.3 }]);
        // ARPU
        mkLine('chartArpu', <?= json_encode($short_labels($arpu['labels'])) ?>, [{ label: '<?= __('analytics.label_arpu_value') ?>', data: <?= json_encode($arpu['values']) ?>, borderColor: 'rgba(168,85,247,1)', backgroundColor: 'rgba(168,85,247,0.1)', fill: true, tension: 0.3 }]);
        // Cumulative cashflow
        mkLine('chartCashflow', <?= json_encode($short_labels($cashflow['labels'])) ?>, [{ label: '<?= __('analytics.label_cashflow_value') ?>', data: <?= json_encode($cashflow['values']) ?>, borderColor: 'rgba(16,185,129,1)', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.3 }]);
    }

    function initClients() {
        if (initialized.clients) return; initialized.clients = true;
        mkBar('chartGrowth', <?= json_encode($short_labels($client_growth['labels'])) ?>, <?= json_encode($client_growth['values']) ?>, 'rgba(14,165,233,0.7)');
        // Retention
        mkPctLine('chartRetention', <?= json_encode($retention['labels']) ?>, [{ label: '<?= __('analytics.label_retention_pct') ?>', data: <?= json_encode($retention['values']) ?>, borderColor: 'rgba(16,185,129,1)', backgroundColor: 'rgba(16,185,129,0.1)', fill: true, tension: 0.3 }]);
        mkDoughnut('chartTariff', <?= json_encode(array_keys($tariff_dist)) ?>, <?= json_encode(array_values($tariff_dist)) ?>);
        // Client type
        mkDoughnut('chartClientType', ['<?= __('analytics.label_individuals') ?>', '<?= __('analytics.label_companies') ?>'], [<?= $client_type['individuals'] ?>, <?= $client_type['companies'] ?>], ['rgba(79,70,229,0.8)', 'rgba(14,165,233,0.8)']);
        // Geo
        (function() {
            var c = document.getElementById('chartGeo'); if (!c) return;
            var l = <?= json_encode(array_keys($geo_dist)) ?>;
            new Chart(c.getContext('2d'), { type: 'bar', data: { labels: l, datasets: [{ data: <?= json_encode(array_values($geo_dist)) ?>, backgroundColor: palette.slice(0, l.length), borderWidth: 1 }] }, options: { indexAxis: 'y', responsive: true, maintainAspectRatio: false, scales: { x: { beginAtZero: true, ticks: { stepSize: 1, color: _tc }, grid: { color: _gc } }, y: { ticks: { color: _tc }, grid: { color: _gc } } }, plugins: { legend: { display: false } } } });
        })();
        // Churn rate
        mkLine('chartChurnRate', <?= json_encode($short_labels($churn_rate['labels'])) ?>, [{ label: '<?= __('analytics.label_churn_pct') ?>', data: <?= json_encode($churn_rate['values']) ?>, borderColor: 'rgba(239,68,68,1)', backgroundColor: 'rgba(239,68,68,0.1)', fill: true, tension: 0.3 }]);
        // Expiring contracts
        mkBar('chartChurn', <?= json_encode($short_labels($client_churn['labels'])) ?>, <?= json_encode($client_churn['values']) ?>, 'rgba(245,158,11,0.7)');
        // Contract duration
        mkDoughnut('chartContractDur', ['<?= __('analytics.label_indefinite') ?>', '<?= __('analytics.label_up_to_12m') ?>', '<?= __('analytics.label_12_24m') ?>', '<?= __('analytics.label_24_plus') ?>'], [<?= $contract_dur['indefinite'] ?>, <?= $contract_dur['up_to_12'] ?>, <?= $contract_dur['12_24'] ?>, <?= $contract_dur['24_plus'] ?>]);
        // Active vs Inactive
        mkDoughnut('chartActiveInactive', ['<?= __('analytics.label_active') ?>', '<?= __('analytics.label_inactive') ?>'], [<?= $active_count ?>, <?= $inactive_count ?>], ['rgba(16,185,129,0.8)', 'rgba(107,114,128,0.8)']);
        // Overpayments
        mkBar('chartOverpayments', <?= json_encode($overpayments['labels']) ?>, <?= json_encode($overpayments['values']) ?>, 'rgba(14,165,233,0.7)');
        // Tenure distribution
        mkDoughnut('chartTenure', ['<?= __('analytics.label_tenure_lt1') ?>', '<?= __('analytics.label_tenure_1_3') ?>', '<?= __('analytics.label_tenure_3_5') ?>', '<?= __('analytics.label_tenure_5_10') ?>', '<?= __('analytics.label_tenure_10plus') ?>'], [<?= $tenure['<1'] ?>, <?= $tenure['1-3'] ?>, <?= $tenure['3-5'] ?>, <?= $tenure['5-10'] ?>, <?= $tenure['10+'] ?>]);
        // Contract status
        mkDoughnut('chartContractStatus', ['<?= __('analytics.label_contract_active') ?>', '<?= __('analytics.label_contract_expiring') ?>', '<?= __('analytics.label_contract_expired') ?>', '<?= __('analytics.label_contract_indefinite') ?>'], [<?= $contract_status['active'] ?>, <?= $contract_status['expiring'] ?>, <?= $contract_status['expired'] ?>, <?= $contract_status['indefinite'] ?>], ['rgba(16,185,129,0.8)', 'rgba(245,158,11,0.8)', 'rgba(239,68,68,0.8)', 'rgba(107,114,128,0.8)']);
        // Registration heatmap
        mkBar('chartRegHeatmap', <?= json_encode(explode(',', __('analytics.label_months_short'))) ?>, <?= json_encode($reg_heatmap) ?>, 'rgba(79,70,229,0.7)');
        // Top revenue
        mkBar('chartTopRevenue', <?= json_encode(array_map(fn($r) => $r['nazwisko'], $top_revenue)) ?>, <?= json_encode(array_map(fn($r) => $r['kwota'], $top_revenue)) ?>, 'rgba(16,185,129,0.7)', true);
    }

    function initOperations() {
        if (initialized.operations) return; initialized.operations = true;
        // Service orders stacked
        (function() {
            var c = document.getElementById('chartService'); if (!c) return;
            new Chart(c.getContext('2d'), { type: 'bar', data: { labels: <?= json_encode($short_labels($service_data['labels'])) ?>, datasets: [
                { label: '<?= __('analytics.label_closed') ?>', data: <?= json_encode($service_data['closed']) ?>, backgroundColor: 'rgba(16,185,129,0.7)', borderColor: 'rgba(16,185,129,1)', borderWidth: 1 },
                { label: '<?= __('analytics.label_open') ?>', data: <?= json_encode($service_data['open']) ?>, backgroundColor: 'rgba(245,158,11,0.7)', borderColor: 'rgba(245,158,11,1)', borderWidth: 1 }
            ] }, options: { responsive: true, maintainAspectRatio: false, scales: { x: { stacked: true, ticks: { color: _tc }, grid: { color: _gc } }, y: { stacked: true, beginAtZero: true, ticks: { stepSize: 1, color: _tc }, grid: { color: _gc } } }, plugins: { legend: legTop } } });
        })();
        // Avg resolution
        mkLine('chartServiceAvg', <?= json_encode($short_labels($service_avg['labels'])) ?>, [{ label: '<?= __('analytics.label_avg_days') ?>', data: <?= json_encode($service_avg['values']) ?>, borderColor: 'rgba(168,85,247,1)', backgroundColor: 'rgba(168,85,247,0.1)', fill: true, tension: 0.3 }]);
        // Categories
        (function() {
            var c = document.getElementById('chartServiceCats'); if (!c) return;
            var l = <?= json_encode(array_keys($service_cats)) ?>;
            new Chart(c.getContext('2d'), { type: 'bar', data: { labels: l, datasets: [{ data: <?= json_encode(array_values($service_cats)) ?>, backgroundColor: palette.slice(0, l.length), borderWidth: 1 }] }, options: { indexAxis: 'y', responsive: true, maintainAspectRatio: false, scales: { x: { beginAtZero: true, ticks: { stepSize: 1, color: _tc }, grid: { color: _gc } }, y: { ticks: { color: _tc, font: { size: 10 } }, grid: { color: _gc } } }, plugins: { legend: { display: false } } } });
        })();
        // Login activity
        mkBar('chartLogins', <?= json_encode($short_day_labels($login_activity['labels'])) ?>, <?= json_encode($login_activity['values']) ?>, 'rgba(79,70,229,0.7)');
        // Failed logins
        mkLine('chartFailedLogins', <?= json_encode($short_day_labels($failed_logins['labels'])) ?>, [{ label: '<?= __('analytics.label_failed') ?>', data: <?= json_encode($failed_logins['values']) ?>, borderColor: 'rgba(239,68,68,1)', backgroundColor: 'rgba(239,68,68,0.1)', fill: true, tension: 0.3 }]);
        // Hourly
        mkBar('chartLoginHours', <?= json_encode(array_map(fn($h) => sprintf('%02d:00', $h), $login_hours['labels'])) ?>, <?= json_encode($login_hours['values']) ?>, 'rgba(99,102,241,0.7)');
        // Cumulative clients (24 months)
        mkLine('chartCumulClients', <?= json_encode($short_labels($cumul_clients['labels'])) ?>, [{ label: '<?= __('analytics.label_total_clients') ?>', data: <?= json_encode($cumul_clients['values']) ?>, borderColor: 'rgba(79,70,229,1)', backgroundColor: 'rgba(79,70,229,0.1)', fill: true, tension: 0.3 }]);
        // Tickets by priority
        mkDoughnut('chartTicketsPriority', ['<?= __('analytics.label_fast_resolve') ?>', '<?= __('analytics.label_normal_resolve') ?>', '<?= __('analytics.label_slow_resolve') ?>', '<?= __('analytics.label_open') ?>'], [<?= $tickets_priority['fast'] ?>, <?= $tickets_priority['normal'] ?>, <?= $tickets_priority['slow'] ?>, <?= $tickets_priority['open'] ?>], ['rgba(16,185,129,0.8)', 'rgba(14,165,233,0.8)', 'rgba(239,68,68,0.8)', 'rgba(107,114,128,0.8)']);
        // Tickets by weekday
        mkBar('chartTicketsWeekday', <?= json_encode(explode(',', __('analytics.label_weekdays_short'))) ?>, <?= json_encode($tickets_weekday) ?>, 'rgba(168,85,247,0.7)');
        // Admin sessions
        mkBar('chartAdminSessions', <?= json_encode($short_day_labels($admin_sessions['labels'])) ?>, <?= json_encode($admin_sessions['values']) ?>, 'rgba(20,184,166,0.7)');
    }

    function initRisk() {
        if (initialized.risk) return; initialized.risk = true;
        // Scoring scatter (bubble chart)
        var scoringCtx = document.getElementById('chartScoring');
        if (scoringCtx) {
            var scoringData = <?= json_encode($scoring) ?>;
            new Chart(scoringCtx.getContext('2d'), {
                type: 'bubble',
                data: { datasets: [{ label: '<?= __('analytics.label_debt_and_expiring') ?>', data: scoringData, backgroundColor: 'rgba(239,68,68,0.5)', borderColor: 'rgba(239,68,68,1)', borderWidth: 1 }] },
                options: {
                    responsive: true, maintainAspectRatio: false,
                    scales: {
                        x: { title: { display: true, text: '<?= __('analytics.label_client_age_years') ?>', color: _tc }, ticks: { color: _tc }, grid: { color: _gc } },
                        y: { title: { display: true, text: '<?= __('analytics.label_debt_amount') ?>', color: _tc }, beginAtZero: true, ticks: { color: _tc }, grid: { color: _gc } }
                    },
                    plugins: {
                        legend: { display: false },
                        tooltip: { callbacks: { label: function(ctx) { var p = ctx.raw; return p.label + ': ' + p.y.toFixed(2) + ' zł (' + p.x + ' lat)'; } } }
                    }
                }
            });
        }
    }

    // Init overview immediately
    initOverview();

    // Init other tabs on show
    document.querySelectorAll('#analyticsTab a[data-bs-toggle="tab"]').forEach(function(tab) {
        tab.addEventListener('shown.bs.tab', function(e) {
            var target = e.target.getAttribute('href');
            if (target === '#tab-finance') initFinance();
            else if (target === '#tab-clients') initClients();
            else if (target === '#tab-operations') initOperations();
            else if (target === '#tab-risk') initRisk();
        });
    });

})();
</script>
<?php
    exit; // koniec renderowania AJAX
}
// --- Normalny widok: loader + AJAX ---
?>
<div id="analyticsLoader" class="text-center py-5">
    <div class="spinner-border text-primary mb-3" style="width:3rem;height:3rem;" role="status"></div>
    <p class="text-muted"><?= __('analytics.loading') ?></p>
</div>
<div id="analyticsContent"></div>
<script nonce="<?= csp_nonce() ?>">
(function(){
    var x = new XMLHttpRequest();
    x.open('GET', 'admin.php?page=analytics&action=render');
    x.onload = function() {
        if (x.status === 200) {
            document.getElementById('analyticsLoader').style.display = 'none';
            var c = document.getElementById('analyticsContent');
            c.innerHTML = x.responseText;
            c.querySelectorAll('script').forEach(function(old) {
                var s = document.createElement('script');
                s.textContent = old.textContent;
                old.parentNode.replaceChild(s, old);
            });
        }
    };
    x.send();
})();
</script>
