<?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 - Dashboard admina (start + upload ZIP + statystyki)
 */

// AJAX: force logout sesji
if (isset($_GET['action']) && $_GET['action'] === 'force_logout' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    if (!csrf_validate()) {
        echo json_encode(['success' => false, 'error' => 'CSRF']);
        exit;
    }
    $hash = $_POST['session_hash'] ?? '';
    if (empty($hash) || !preg_match('/^[a-f0-9]{32}$/', $hash)) {
        echo json_encode(['success' => false, 'error' => 'Invalid hash']);
        exit;
    }
    $ok = session_force_logout($hash);
    echo json_encode(['success' => $ok]);
    exit;
}

/**
 * Parsuj logi nieudanych logowań
 */
function parse_failed_logins($limit = 20) {
    $results = [];
    $log_files = glob(IBOK_LOGS_DIR . '/ibok_*.log');
    if (empty($log_files)) return $results;

    rsort($log_files);
    // Czytaj max 2 najnowsze pliki
    $files_to_read = array_slice($log_files, 0, 2);

    $pattern = '/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[warning\] \[([^\]]+)\] Login (klienta|admina) (nieudany|zablokowany)(.*)$/';

    foreach ($files_to_read as $f) {
        $lines = @file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        if (!$lines) continue;
        foreach (array_reverse($lines) as $line) {
            if (preg_match($pattern, $line, $m)) {
                $type = ($m[3] === 'admina') ? 'admin' : 'client';
                $action = $m[4]; // nieudany / zablokowany

                // Wyciągnij login i szczegóły z reszty
                $rest = trim($m[5]);
                $login = '';
                $reason_key = 'bad_password';

                if ($action === 'zablokowany') {
                    $reason_key = 'rate_limit';
                    // Format: " (rate limit): login"
                    if (preg_match('/\(rate limit\):\s*(.+)/', $rest, $rm)) {
                        $login = $rm[1];
                    }
                } else {
                    // Format: " (nie znaleziono): login" lub " (złe hasło): login" lub ": login"
                    if (preg_match('/\(nie znaleziono\):\s*(.+)/', $rest, $rm)) {
                        $reason_key = 'not_found';
                        $login = $rm[1];
                    } elseif (preg_match('/\(złe hasło\):\s*(.+)/', $rest, $rm)) {
                        $reason_key = 'bad_password';
                        $login = $rm[1];
                    } elseif (preg_match('/:\s*(.+)/', $rest, $rm)) {
                        $login = $rm[1];
                    }
                }

                $reason_map = [
                    'bad_password' => __('admin_dashboard.reason_bad_password'),
                    'not_found'    => __('admin_dashboard.reason_not_found'),
                    'rate_limit'   => __('admin_dashboard.reason_rate_limit'),
                ];

                $results[] = [
                    'time'       => $m[1],
                    'ip'         => $m[2],
                    'type'       => $type,
                    'type_label' => $type === 'admin' ? __('admin_dashboard.type_admin') : __('admin_dashboard.type_client'),
                    'login'      => $login,
                    'reason_key' => $reason_key,
                    'reason'     => $reason_map[$reason_key] ?? $reason_key,
                ];

                if (count($results) >= $limit) break 2;
            }
        }
    }

    return $results;
}

/**
 * Parsuj user-agent na krótką nazwę przeglądarki
 */
function parse_browser_short($ua) {
    if (empty($ua)) return '—';
    if (preg_match('/Edg\//', $ua)) return 'Edge';
    if (preg_match('/OPR\/|Opera\//', $ua)) return 'Opera';
    if (preg_match('/Chrome\//', $ua)) return 'Chrome';
    if (preg_match('/Firefox\//', $ua)) return 'Firefox';
    if (preg_match('/Safari\//', $ua) && !preg_match('/Chrome/', $ua)) return 'Safari';
    if (preg_match('/MSIE|Trident/', $ua)) return 'IE';
    return 'Other';
}

// Obsługa uploadu logo
$import_msg = '';
$import_type = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['upload_logo'])) {
    if (csrf_validate() && isset($_FILES['logofile']) && $_FILES['logofile']['error'] === UPLOAD_ERR_OK) {
        if ($_FILES['logofile']['size'] > 2097152) {
            $import_msg = __('admin.logo_too_large');
            $import_type = 'danger';
        } else {
            $img_info = @getimagesize($_FILES['logofile']['tmp_name']);
            if ($img_info === false) {
                $import_msg = __('admin.logo_invalid_format');
                $import_type = 'danger';
            } else {
                $target = IBOK_ADMIN_DIR . '/logo.jpg';
                if (move_uploaded_file($_FILES['logofile']['tmp_name'], $target)) {
                    $import_msg = __('common.success');
                    $import_type = 'success';
                } else {
                    $import_msg = __('admin.logo_upload_error');
                    $import_type = 'danger';
                }
            }
        }
    }
}

// Obsługa usunięcia logo
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_logo'])) {
    if (csrf_validate()) {
        $logo_path = IBOK_ADMIN_DIR . '/logo.jpg';
        if (file_exists($logo_path) && @unlink($logo_path)) {
            $import_msg = __('admin.logo_deleted');
            $import_type = 'success';
        }
    }
}

// Obsługa zapisu motywu
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_theme'])) {
    if (ibok_is_demo()) {
        $import_msg = __('demo.save_blocked');
        $import_type = 'warning';
    } elseif (csrf_validate()) {
        $allowed_themes = ['default', 'emerald', 'violet', 'rose', 'amber', 'slate', 'ocean', 'crimson', 'forest', 'royal'];
        $selected_theme = $_POST['theme'] ?? 'default';
        if (in_array($selected_theme, $allowed_themes)) {
            $theme_file = IBOK_CFG_DIR . '/theme.cfg';
            file_put_contents($theme_file, json_encode(['theme' => $selected_theme], JSON_PRETTY_PRINT));
            $import_msg = __('theme.saved');
            $import_type = 'success';
        }
    }
}

// Odczytaj aktualny motyw
$current_theme = 'default';
$theme_cfg_file = IBOK_CFG_DIR . '/theme.cfg';
if (file_exists($theme_cfg_file)) {
    $td = @json_decode(file_get_contents($theme_cfg_file), true);
    if (!empty($td['theme'])) $current_theme = $td['theme'];
}

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

// Statystyki
$clients = vbk_read_klienci();
$total = count($clients);
$active = 0;
$with_debt = 0;

$total_debt = 0;
foreach ($clients as $c) {
    if ($c['active_flag'] === '1') $active++;
    if ((int)$c['wg_salda'] > 0 || $c['zalega'] === '1') $with_debt++;
    $total_debt += (float)str_replace(',', '.', $c['saldo_zalegle_raw']);
}

// Dane do wykresów
$tariff_dist = stats_tariff_distribution($clients);
$debt_summary = stats_debt_summary($clients);

// Top 10 dłużników
$debtors = [];
foreach ($clients as $cid => $c) {
    $saldo = (int)$c['wg_salda'];
    if ($saldo > 0) {
        $debtors[] = ['id' => $cid, 'nazwisko' => $c['nazwisko'], 'saldo' => $saldo];
    }
}
usort($debtors, function($a, $b) { return $b['saldo'] - $a['saldo']; });
$debtors = array_slice($debtors, 0, 10);

// Dane do wykresu MRR - wyłączony (punkt 13 todo)
// $revenue_data = stats_revenue_by_month(12);

// Wygasające umowy (w ciągu 90 dni)
$expiring = [];
$today_ts = strtotime('today');
foreach ($clients as $cid => $c) {
    $umowa_do = $c['umowa_do'] ?? '';
    if (empty($umowa_do) || $umowa_do === '0000-00-00') continue;
    $end_ts = strtotime($umowa_do);
    if ($end_ts === false) continue;
    $days_left = (int)floor(($end_ts - $today_ts) / 86400);
    if ($days_left >= 0 && $days_left <= 90) {
        $expiring[] = [
            'id' => $cid,
            'nazwisko' => $c['nazwisko'],
            'umowa_do' => $umowa_do,
            'days_left' => $days_left,
        ];
    }
}
usort($expiring, function($a, $b) { return $a['days_left'] - $b['days_left']; });

// Zlecenia serwisowe — timeline wg miesięcy (ostatnie 12 miesięcy)
$zlecenia = db_read_zlecenia();
$zlecenia_months = [];
for ($i = 11; $i >= 0; $i--) {
    $key = date('Y-m', strtotime("-{$i} months"));
    $zlecenia_months[$key] = ['open' => 0, 'closed' => 0];
}
foreach ($zlecenia as $z) {
    $m = substr($z['data'], 0, 7); // YYYY-MM
    if (isset($zlecenia_months[$m])) {
        if (empty($z['data_zakonczenia'])) {
            $zlecenia_months[$m]['open']++;
        } else {
            $zlecenia_months[$m]['closed']++;
        }
    }
}

// Klienci wg miejscowości (top 10)
$city_counts = [];
foreach ($clients as $c) {
    $city = trim($c['miejscowosc'] ?? '');
    if ($city === '') continue;
    $city_counts[$city] = ($city_counts[$city] ?? 0) + 1;
}
arsort($city_counts);
$top_cities = array_slice($city_counts, 0, 10, true);
$other_count = array_sum(array_slice($city_counts, 10));
if ($other_count > 0) {
    $top_cities[__('admin.other_cities')] = $other_count;
}

// Data aktualizacji
global $stan_na_dzien;

// Ostatnie logi
$log_files = glob(IBOK_LOGS_DIR . '/ibok_*.log');
$recent_logs = [];
if (!empty($log_files)) {
    rsort($log_files);
    $latest = $log_files[0] ?? '';
    if (file_exists($latest)) {
        $lines = file($latest, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $recent_logs = array_slice(array_reverse($lines), 0, 15);
    }
}
?>

<div class="fade-in">
    <div class="d-flex flex-wrap justify-content-between align-items-center mb-4 gap-3">
        <h4 class="mb-0">
            <i class="bi bi-speedometer2 me-2"></i> <?= __('admin.dashboard') ?>
        </h4>
        <!-- Global Search -->
        <div class="global-search-wrapper global-search-page">
            <div class="position-relative">
                <div class="input-group">
                    <span class="input-group-text border-end-0">
                        <i class="bi bi-search text-muted"></i>
                    </span>
                    <input type="text" class="form-control border-start-0"
                           id="globalSearchInput"
                           placeholder="<?= __('global_search.placeholder') ?>"
                           autocomplete="off" aria-label="Search">
                </div>
                <div class="global-search-dropdown" id="globalSearchDropdown"></div>
            </div>
        </div>
    </div>

    <?= ibok_help_section('admin_dashboard', __('help.show_help'), __('help_admin.dashboard_section_content')) ?>

    <?php if ($import_msg): ?>
        <div class="alert alert-<?= $import_type ?> alert-dismissible fade show">
            <?= e($import_msg) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Statystyki -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card stat-info p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label"><?= __('admin.total_clients') ?></div>
                        <div class="stat-value"><?= $total ?></div>
                    </div>
                    <div class="stat-icon"><i class="bi bi-people"></i></div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card stat-success p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label"><?= __('admin.active_clients') ?></div>
                        <div class="stat-value"><?= $active ?></div>
                    </div>
                    <div class="stat-icon"><i class="bi bi-check-circle"></i></div>
                </div>
            </div>
        </div>
        <?php if (!is_service_user()): ?>
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card stat-danger p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label"><?= __('admin.with_debt') ?></div>
                        <div class="stat-value"><?= $with_debt ?></div>
                    </div>
                    <div class="stat-icon"><i class="bi bi-exclamation-triangle"></i></div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card stat-warning p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label"><?= __('admin.total_debt') ?></div>
                        <div class="stat-value text-nowrap" style="font-size: clamp(0.9rem, 2vw, 1.5rem);"><?= number_format($total_debt, 2, ',', ' ') ?> PLN</div>
                    </div>
                    <div class="stat-icon"><i class="bi bi-cash-stack"></i></div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Wykresy -->
    <div class="row g-4 mb-4">
        <!-- Rozkład taryf -->
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header">
                    <i class="bi bi-pie-chart me-1"></i> <?= __('admin.tariff_chart') ?>
                </div>
                <div class="card-body d-flex align-items-center justify-content-center">
                    <canvas id="tariffChart" style="max-height: 250px;"></canvas>
                </div>
            </div>
        </div>

        <!-- Status klientów -->
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header">
                    <i class="bi bi-pie-chart me-1"></i> <?= __('admin.client_status_chart') ?>
                </div>
                <div class="card-body d-flex align-items-center justify-content-center">
                    <canvas id="statusChart" style="max-height: 250px;"></canvas>
                </div>
            </div>
        </div>

        <?php if (!is_service_user()): ?>
        <!-- Top dłużnicy -->
        <div class="col-lg-4">
            <div class="card h-100">
                <div class="card-header">
                    <i class="bi bi-exclamation-triangle me-1"></i> <?= __('admin.top_debtors') ?>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($debtors)): ?>
                        <p class="text-muted text-center py-4"><?= __('admin.top_debtors_empty') ?></p>
                    <?php else: ?>
                        <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
                            <table class="table table-sm table-striped mb-0">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th><?= __('admin_clients.name') ?></th>
                                        <th class="text-end"><?= __('admin.debt_amount') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($debtors as $d): ?>
                                    <tr>
                                        <td>
                                            <a href="admin.php?page=klient_info&id=<?= e($d['id']) ?>"><?= e(nr_klienta($d['id'])) ?></a>
                                        </td>
                                        <td><?= e($d['nazwisko']) ?></td>
                                        <td class="text-end text-danger fw-bold"><?= e($d['saldo']) ?> PLN</td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <!-- Zlecenia serwisowe + Klienci wg miejscowości -->
    <div class="row g-4 mb-4">
        <div class="col-lg-7">
            <div class="card h-100">
                <div class="card-header">
                    <i class="bi bi-graph-up me-1"></i> <?= __('admin.service_timeline') ?>
                </div>
                <div class="card-body" style="height: 400px;">
                    <canvas id="serviceTimelineChart"></canvas>
                </div>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="card h-100">
                <div class="card-header">
                    <i class="bi bi-geo-alt me-1"></i> <?= __('admin.clients_by_city') ?>
                </div>
                <div class="card-body" style="height: 400px;">
                    <?php if (empty($top_cities)): ?>
                        <p class="text-muted text-center"><?= __('common.no_data') ?></p>
                    <?php else: ?>
                        <canvas id="cityChart"></canvas>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Wygasające umowy -->
    <?php if (!empty($expiring)): ?>
    <div class="row g-4 mb-4">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-calendar-x me-1"></i> <?= __('admin.expiring_contracts') ?> (<?= count($expiring) ?>)
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive" style="max-height: 350px; overflow-y: auto;">
                        <table class="table table-sm table-striped mb-0">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th><?= __('admin_clients.name') ?></th>
                                    <th><?= __('admin.contract_end') ?></th>
                                    <th><?= __('admin.days_remaining') ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($expiring as $ex): ?>
                                <tr>
                                    <td>
                                        <a href="admin.php?page=klient_info&id=<?= e($ex['id']) ?>"><?= e(nr_klienta($ex['id'])) ?></a>
                                    </td>
                                    <td><?= e($ex['nazwisko']) ?></td>
                                    <td><?= format_date($ex['umowa_do']) ?></td>
                                    <td>
                                        <?php
                                        $badge_class = 'bg-info';
                                        if ($ex['days_left'] < 30) $badge_class = 'bg-danger';
                                        elseif ($ex['days_left'] < 60) $badge_class = 'bg-warning text-dark';
                                        ?>
                                        <span class="badge <?= $badge_class ?>"><?= $ex['days_left'] ?> <?= __('admin.days_unit') ?></span>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Nieudane logowania + Aktywne sesje -->
    <div class="row g-4 mb-4">
        <div class="col-lg-6">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-shield-exclamation me-1"></i> <?= __('admin_dashboard.failed_logins') ?><?= ibok_tooltip(__('help_admin.tooltip_failed_logins')) ?></span>
                    <?php
                    $failed_logins = ibok_is_demo() ? [] : parse_failed_logins(20);
                    $count_24h = 0;
                    $ts_24h = time() - 86400;
                    foreach ($failed_logins as $fl) {
                        if (strtotime($fl['time']) >= $ts_24h) $count_24h++;
                    }
                    ?>
                    <?php if ($count_24h > 0): ?>
                        <span class="badge bg-danger"><?= $count_24h ?> <?= __('admin_dashboard.failed_last_24h') ?></span>
                    <?php endif; ?>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($failed_logins)): ?>
                        <p class="text-muted text-center py-4"><?= __('admin_dashboard.no_failed_logins') ?></p>
                    <?php else: ?>
                        <div class="table-responsive" style="max-height: 350px; overflow-y: auto;">
                            <table class="table table-sm table-striped mb-0" style="font-size: 0.8rem;">
                                <thead>
                                    <tr>
                                        <th><?= __('admin_dashboard.col_time') ?></th>
                                        <th><?= __('admin_dashboard.col_type') ?></th>
                                        <th><?= __('admin_dashboard.col_login') ?></th>
                                        <th><?= __('admin_dashboard.col_ip') ?></th>
                                        <th><?= __('admin_dashboard.col_reason') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($failed_logins as $fl): ?>
                                    <tr class="<?= $fl['reason_key'] === 'rate_limit' ? 'table-danger' : '' ?>">
                                        <td class="text-nowrap"><?= e($fl['time']) ?></td>
                                        <td>
                                            <span class="badge <?= $fl['type'] === 'admin' ? 'bg-danger' : 'bg-info' ?>">
                                                <?= e($fl['type_label']) ?>
                                            </span>
                                        </td>
                                        <td><?= e($fl['login']) ?></td>
                                        <td class="font-monospace"><?= e($fl['ip']) ?></td>
                                        <td><?= e($fl['reason']) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <div class="text-center py-2">
                            <a href="admin.php?page=logi" class="small text-muted">
                                <?= __('admin_dashboard.view_all_logs') ?> <i class="bi bi-arrow-right"></i>
                            </a>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="col-lg-6">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span><i class="bi bi-people me-1"></i> <?= __('admin_dashboard.active_sessions') ?><?= ibok_tooltip(__('help_admin.tooltip_active_sessions')) ?></span>
                    <?php $active_sessions = ibok_is_demo() ? [] : session_get_active(); ?>
                    <span class="badge bg-primary"><?= count($active_sessions) ?></span>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($active_sessions)): ?>
                        <p class="text-muted text-center py-4"><?= __('admin_dashboard.no_active_sessions') ?></p>
                    <?php else: ?>
                        <div class="table-responsive" style="max-height: 350px; overflow-y: auto;">
                            <table class="table table-sm table-striped mb-0" style="font-size: 0.8rem;">
                                <thead>
                                    <tr>
                                        <th><?= __('admin_dashboard.col_type') ?></th>
                                        <th><?= __('admin_dashboard.col_user') ?></th>
                                        <th><?= __('admin_dashboard.col_ip') ?></th>
                                        <th><?= __('admin_dashboard.col_last_active') ?></th>
                                        <th><?= __('admin_dashboard.col_browser') ?><?= ibok_tooltip(__('help_admin.tooltip_browser')) ?></th>
                                        <th></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $current_hash = md5(session_id());
                                    foreach ($active_sessions as $hash => $sess):
                                        $is_current = ($hash === $current_hash);
                                        $ua_short = parse_browser_short($sess['user_agent'] ?? '');
                                    ?>
                                    <tr <?= $is_current ? 'class="table-active"' : '' ?>>
                                        <td>
                                            <span class="badge <?= $sess['user_type'] === 'admin' ? 'bg-danger' : 'bg-info' ?>">
                                                <?= $sess['user_type'] === 'admin' ? __('admin_dashboard.type_admin') : __('admin_dashboard.type_client') ?>
                                            </span>
                                        </td>
                                        <td><?= e($sess['login']) ?></td>
                                        <td class="font-monospace"><?= e($sess['ip']) ?></td>
                                        <td class="text-nowrap"><?= date('H:i:s', $sess['last_activity']) ?></td>
                                        <td title="<?= e($sess['user_agent'] ?? '') ?>"><?= e($ua_short) ?></td>
                                        <td>
                                            <?php if (!$is_current): ?>
                                            <button class="btn btn-outline-danger btn-sm py-0 px-1 btn-force-logout" data-hash="<?= e($hash) ?>" data-bs-toggle="tooltip" title="<?= e(__('help_admin.tooltip_force_logout')) ?>">
                                                <i class="bi bi-x-lg"></i>
                                            </button>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <!-- Upload logo + Logi -->
        <div class="col-lg-6">
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-image me-1"></i> <?= __('admin.upload_logo') ?>
                </div>
                <div class="card-body">
                    <?php $logo_exists = file_exists(IBOK_ADMIN_DIR . '/logo.jpg'); ?>
                    <?php if ($logo_exists): ?>
                        <div class="mb-3 d-flex align-items-center gap-3">
                            <img src="admin/logo.jpg?t=<?= time() ?>" alt="Logo" style="max-height: 60px;" class="border rounded p-1">
                            <form method="post" action="admin.php?page=dashboard" class="d-inline">
                                <?= csrf_field() ?>
                                <input type="hidden" name="delete_logo" value="1">
                                <button type="submit" class="btn btn-outline-danger btn-sm" id="btnDeleteLogo"
                                        data-confirm="<?= e(__('admin.logo_confirm_delete')) ?>">
                                    <i class="bi bi-trash me-1"></i> <?= __('admin.logo_delete') ?>
                                </button>
                            </form>
                        </div>
                    <?php endif; ?>
                    <form method="post" enctype="multipart/form-data" action="admin.php?page=dashboard">
                        <?= csrf_field() ?>
                        <input type="hidden" name="upload_logo" value="1">
                        <div class="mb-2">
                            <input type="file" class="form-control" name="logofile" accept=".jpg,.jpeg,.png,.gif" required>
                        </div>
                        <div class="form-text text-muted mb-3">
                            <i class="bi bi-info-circle me-1"></i><?= __('admin.logo_help') ?>
                        </div>
                        <button type="submit" class="btn btn-outline-primary btn-sm">
                            <i class="bi bi-upload me-1"></i> <?= __('common.upload') ?>
                        </button>
                    </form>
                </div>
            </div>

            <!-- Motyw kolorystyczny -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-palette me-1"></i> <?= __('theme.title') ?>
                </div>
                <div class="card-body">
                    <p class="text-muted small mb-3"><?= __('theme.description') ?></p>
                    <form method="post" action="admin.php?page=dashboard">
                        <?= csrf_field() ?>
                        <input type="hidden" name="save_theme" value="1">
                        <?php
                        $themes = [
                            'default' => ['label' => __('theme.default'),  'colors' => ['#1a365d', '#2c5282', '#3182ce']],
                            'emerald' => ['label' => __('theme.emerald'), 'colors' => ['#064e3b', '#065f46', '#10b981']],
                            'violet'  => ['label' => __('theme.violet'),  'colors' => ['#2e1065', '#4c1d95', '#8b5cf6']],
                            'rose'    => ['label' => __('theme.rose'),    'colors' => ['#881337', '#9f1239', '#f43f5e']],
                            'amber'   => ['label' => __('theme.amber'),   'colors' => ['#78350f', '#92400e', '#f59e0b']],
                            'slate'   => ['label' => __('theme.slate'),   'colors' => ['#1e293b', '#334155', '#64748b']],
                            'ocean'   => ['label' => __('theme.ocean'),   'colors' => ['#134e4a', '#0d9488', '#2dd4bf']],
                            'crimson' => ['label' => __('theme.crimson'), 'colors' => ['#7f1d1d', '#b91c1c', '#ef4444']],
                            'forest'  => ['label' => __('theme.forest'),  'colors' => ['#1a2e05', '#365314', '#65a30d']],
                            'royal'   => ['label' => __('theme.royal'),   'colors' => ['#1e1b4b', '#3730a3', '#c084fc']],
                        ];
                        foreach ($themes as $key => $t): ?>
                        <div class="form-check mb-2">
                            <input class="form-check-input theme-radio-auto" type="radio" name="theme" value="<?= $key ?>"
                                   id="theme_<?= $key ?>" <?= $current_theme === $key ? 'checked' : '' ?>>
                            <label class="form-check-label d-flex align-items-center gap-2" for="theme_<?= $key ?>">
                                <?php foreach ($t['colors'] as $c): ?>
                                    <span style="display:inline-block;width:16px;height:16px;border-radius:50%;background:<?= $c ?>;border:1px solid rgba(0,0,0,.15);"></span>
                                <?php endforeach; ?>
                                <span><?= e($t['label']) ?></span>
                            </label>
                        </div>
                        <?php endforeach; ?>
                    </form>
                </div>
            </div>
        </div>

        <!-- Ostatnie logi -->
        <div class="col-lg-6">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-journal-text me-1"></i> <?= __('admin.session_logs') ?>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($recent_logs)): ?>
                        <p class="text-muted text-center py-4"><?= __('common.no_data') ?></p>
                    <?php else: ?>
                        <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                            <table class="table table-sm table-striped mb-0" style="font-size: 0.8rem;">
                                <tbody>
                                    <?php foreach ($recent_logs as $line): ?>
                                    <tr>
                                        <td class="font-monospace text-nowrap"><?= e($line) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Licencja i-BOK -->
            <?php
            require_once __DIR__ . '/../inc/db_mysql.php';
            $lic_info = db_read_license_info();
            $lic_valid = db_check_license();
            ?>
            <div class="card mt-4 <?= !$lic_valid ? 'border-danger' : '' ?>">
                <div class="card-header d-flex align-items-center justify-content-between">
                    <span><i class="bi bi-key me-1"></i> <?= __('license_info.title') ?></span>
                    <?php if ($lic_valid): ?>
                        <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i><?= __('license_info.status_valid') ?></span>
                    <?php else: ?>
                        <span class="badge bg-danger"><i class="bi bi-x-circle me-1"></i><?= __('license_info.status_invalid') ?></span>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <?php if ($lic_info === null): ?>
                        <div class="text-center text-muted py-3">
                            <i class="bi bi-exclamation-triangle text-warning" style="font-size: 2rem;"></i>
                            <p class="mt-2 mb-0"><?= __('license_info.no_data') ?></p>
                        </div>
                    <?php else: ?>
                        <table class="table table-sm mb-0">
                            <tbody>
                                <tr>
                                    <td class="text-muted" style="width: 40%;"><?= __('license_info.key') ?></td>
                                    <td>
                                        <code><?= e($lic_info['L_KLUCZ'] ?? '—') ?></code>
                                        <?php if ($lic_valid): ?>
                                            <i class="bi bi-check-circle-fill text-success ms-1"></i>
                                        <?php else: ?>
                                            <i class="bi bi-x-circle-fill text-danger ms-1"></i>
                                        <?php endif; ?>
                                    </td>
                                </tr>
                                <?php if (!empty($lic_info['L_NAZWA'])): ?>
                                <tr>
                                    <td class="text-muted"><?= __('license_info.name') ?></td>
                                    <td><?= e($lic_info['L_NAZWA']) ?></td>
                                </tr>
                                <?php endif; ?>
                                <?php if (!empty($lic_info['L_DATA'])): ?>
                                <tr>
                                    <td class="text-muted"><?= __('license_info.date') ?></td>
                                    <td><?= e($lic_info['L_DATA']) ?></td>
                                </tr>
                                <?php endif; ?>
                                <?php if (!empty($lic_info['L_WAZNA'])): ?>
                                <tr>
                                    <td class="text-muted"><?= __('license_info.valid_until') ?></td>
                                    <td><?= e($lic_info['L_WAZNA']) ?></td>
                                </tr>
                                <?php endif; ?>
                                <?php if (!empty($lic_info['L_FIRMA'])): ?>
                                <tr>
                                    <td class="text-muted"><?= __('license_info.company') ?></td>
                                    <td><?= e($lic_info['L_FIRMA']) ?></td>
                                </tr>
                                <?php endif; ?>
                                <?php if (!empty($lic_info['L_INFO'])): ?>
                                <tr>
                                    <td class="text-muted"><?= __('license_info.info') ?></td>
                                    <td><?= e($lic_info['L_INFO']) ?></td>
                                </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                        <?php if (!$lic_valid): ?>
                            <div class="alert alert-danger mt-3 mb-0 small">
                                <i class="bi bi-exclamation-triangle-fill me-1"></i>
                                <?= e(__('license_info.invalid_warning')) ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
(function() {
    // Theme radio auto-submit
    document.querySelectorAll('.theme-radio-auto').forEach(function(r) {
        r.addEventListener('change', function() { this.form.submit(); });
    });

    // Chart.js — kolory dark mode
    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;
        }
    }
    // Wymuszenie koloru legendy przez globalny plugin
    var _chartLegendColorPlugin = {
        id: 'legendColorForce',
        beforeDraw: function(chart) {
            if (!_dk) return;
            if (chart.legend) {
                chart.legend.options.labels.color = _tc;
                if (chart.legend.legendItems) {
                    chart.legend.legendItems.forEach(function(item) {
                        item.fontColor = _tc;
                    });
                }
            }
            // Wymuszaj kolor na osiach
            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(_chartLegendColorPlugin);
    }

    // Wykres taryf (doughnut)
    var tariffCtx = document.getElementById('tariffChart');
    if (tariffCtx) {
        var tariffLabels = <?= json_encode(array_keys($tariff_dist)) ?>;
        var tariffValues = <?= json_encode(array_values($tariff_dist)) ?>;
        var tariffColors = [
            '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)'
        ];

        new Chart(tariffCtx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: tariffLabels,
                datasets: [{
                    data: tariffValues,
                    backgroundColor: tariffColors.slice(0, tariffLabels.length),
                    borderWidth: 2,
                    borderColor: _bc
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom', labels: { color: _tc, fontColor: _tc, boxWidth: 12, padding: 8, font: { size: 11, color: _tc } } }
                }
            }
        });
    }

    // Wykres zleceń serwisowych (bar - stacked)
    var serviceCtx = document.getElementById('serviceTimelineChart');
    if (serviceCtx) {
        var sLabels = <?= json_encode(array_map(function($k) {
            $parts = explode('-', $k);
            return $parts[1] . '/' . substr($parts[0], 2);
        }, array_keys($zlecenia_months))) ?>;
        var sOpen = <?= json_encode(array_map(function($m) { return $m['open']; }, array_values($zlecenia_months))) ?>;
        var sClosed = <?= json_encode(array_map(function($m) { return $m['closed']; }, array_values($zlecenia_months))) ?>;

        new Chart(serviceCtx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: sLabels,
                datasets: [
                    {
                        label: '<?= __('admin.service_closed') ?>',
                        data: sClosed,
                        backgroundColor: 'rgba(16, 185, 129, 0.7)',
                        borderColor: 'rgba(16, 185, 129, 1)',
                        borderWidth: 1
                    },
                    {
                        label: '<?= __('admin.service_open') ?>',
                        data: sOpen,
                        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: { position: 'top', labels: { color: _tc, fontColor: _tc, boxWidth: 12, padding: 8, font: { size: 11, color: _tc } } }
                }
            }
        });
    }

    // Wykres klientów wg miejscowości (horizontal bar)
    var cityCtx = document.getElementById('cityChart');
    if (cityCtx) {
        var cityLabels = <?= json_encode(array_keys($top_cities)) ?>;
        var cityValues = <?= json_encode(array_values($top_cities)) ?>;
        var cityColors = [
            'rgba(79, 70, 229, 0.7)',
            'rgba(14, 165, 233, 0.7)',
            'rgba(16, 185, 129, 0.7)',
            'rgba(245, 158, 11, 0.7)',
            'rgba(239, 68, 68, 0.7)',
            'rgba(168, 85, 247, 0.7)',
            'rgba(236, 72, 153, 0.7)',
            'rgba(107, 114, 128, 0.7)',
            'rgba(20, 184, 166, 0.7)',
            'rgba(99, 102, 241, 0.7)',
            'rgba(156, 163, 175, 0.7)'
        ];

        new Chart(cityCtx.getContext('2d'), {
            type: 'bar',
            data: {
                labels: cityLabels,
                datasets: [{
                    data: cityValues,
                    backgroundColor: cityColors.slice(0, cityLabels.length),
                    borderWidth: 1,
                    borderColor: cityColors.slice(0, cityLabels.length).map(function(c) { return c.replace('0.7', '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 }
                }
            }
        });
    }

    // Wykres statusów (doughnut)
    var statusCtx = document.getElementById('statusChart');
    if (statusCtx) {
        <?php if (!is_service_user()): ?>
        var activeOk = <?= $debt_summary['active'] - $debt_summary['with_debt'] ?>;
        var withDebt = <?= $debt_summary['with_debt'] ?>;
        var inactive = <?= $debt_summary['inactive'] ?>;
        var statusLabels = [
            '<?= __('admin.active_clients') ?>',
            '<?= __('admin.clients_with_debt') ?>',
            '<?= __('admin.clients_inactive') ?>'
        ];
        var statusData = [activeOk, withDebt, inactive];
        var statusColors = [
            'rgba(14, 165, 233, 0.8)',
            'rgba(239, 68, 68, 0.8)',
            'rgba(156, 163, 175, 0.8)'
        ];
        <?php else: ?>
        var statusLabels = [
            '<?= __('admin.active_clients') ?>',
            '<?= __('admin.clients_inactive') ?>'
        ];
        var statusData = [<?= $debt_summary['active'] ?>, <?= $debt_summary['inactive'] ?>];
        var statusColors = [
            'rgba(14, 165, 233, 0.8)',
            'rgba(156, 163, 175, 0.8)'
        ];
        <?php endif; ?>

        new Chart(statusCtx.getContext('2d'), {
            type: 'doughnut',
            data: {
                labels: statusLabels,
                datasets: [{
                    data: statusData,
                    backgroundColor: statusColors,
                    borderWidth: 2,
                    borderColor: _bc
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: { position: 'bottom', labels: { color: _tc, fontColor: _tc, boxWidth: 12, padding: 8, font: { size: 11, color: _tc } } }
                }
            }
        });
    }
})();
</script>

<!-- Global Search -->
<script nonce="<?= csp_nonce() ?>">
(function() {
    const SEARCH_LANG = {
        no_results: <?= json_encode(__('global_search.no_results')) ?>,
        min_chars: <?= json_encode(__('global_search.min_chars')) ?>,
        error: <?= json_encode(__('global_search.error')) ?>
    };

    const input = document.getElementById('globalSearchInput');
    const dropdown = document.getElementById('globalSearchDropdown');
    if (!input || !dropdown) return;

    let debounceTimer = null;
    let currentXhr = null;
    let searchId = 0;
    let lastSearchTime = 0;
    let pendingQuery = null;
    const MIN_INTERVAL = 1000; // min 1s between requests

    input.addEventListener('input', function() {
        clearTimeout(debounceTimer);
        const q = this.value.trim();

        if (q.length < 2) {
            if (currentXhr) { currentXhr.abort(); currentXhr = null; }
            pendingQuery = null;
            hideDropdown();
            return;
        }

        debounceTimer = setTimeout(function() {
            var elapsed = Date.now() - lastSearchTime;
            if (currentXhr || elapsed < MIN_INTERVAL) {
                // Request in flight or too soon — queue it
                pendingQuery = q;
                if (!currentXhr) {
                    setTimeout(function() {
                        if (pendingQuery) { doSearch(pendingQuery); pendingQuery = null; }
                    }, MIN_INTERVAL - elapsed);
                }
                return;
            }
            doSearch(q);
        }, 350);
    });

    input.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            hideDropdown();
            input.blur();
        }
        if (e.key === 'ArrowDown') {
            e.preventDefault();
            const first = dropdown.querySelector('.gs-item');
            if (first) first.focus();
        }
    });

    document.addEventListener('click', function(e) {
        if (!e.target.closest('.global-search-wrapper')) {
            hideDropdown();
        }
    });

    dropdown.addEventListener('keydown', function(e) {
        const items = Array.from(dropdown.querySelectorAll('.gs-item'));
        const idx = items.indexOf(document.activeElement);

        if (e.key === 'ArrowDown') {
            e.preventDefault();
            if (idx < items.length - 1) items[idx + 1].focus();
        } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            if (idx > 0) items[idx - 1].focus();
            else input.focus();
        } else if (e.key === 'Escape') {
            hideDropdown();
            input.focus();
        }
    });

    function doSearch(q) {
        if (currentXhr) {
            currentXhr.abort();
            currentXhr = null;
        }
        var myId = ++searchId;
        lastSearchTime = Date.now();
        pendingQuery = null;
        showLoading();
        var xhr = $.ajax({
            url: 'admin.php',
            data: { page: 'search', action: 'query', q: q, _t: myId },
            dataType: 'json',
            timeout: 15000,
            cache: false,
            success: function(data) {
                if (myId !== searchId) return;
                if (data.error) {
                    dropdown.innerHTML = '<div class="gs-empty">' + SEARCH_LANG.error + ': ' + escHtml(data.error) + '</div>';
                    showDropdown();
                } else {
                    renderResults(data.results || []);
                }
            },
            error: function(jqXhr, status) {
                if (myId !== searchId) return;
                if (status !== 'abort') {
                    var msg = SEARCH_LANG.error;
                    if (status === 'timeout') msg += ' (timeout)';
                    else if (status === 'parsererror') msg += ': ' + (jqXhr.responseText || '').substring(0, 300);
                    dropdown.innerHTML = '<div class="gs-empty">' + escHtml(msg) + '</div>';
                    showDropdown();
                }
            },
            complete: function() {
                if (xhr === currentXhr) currentXhr = null;
                // Process queued search after request finishes
                if (pendingQuery) {
                    var pq = pendingQuery;
                    pendingQuery = null;
                    var wait = Math.max(0, MIN_INTERVAL - (Date.now() - lastSearchTime));
                    setTimeout(function() { doSearch(pq); }, wait);
                }
            }
        });
        currentXhr = xhr;
    }

    function renderResults(groups) {
        if (groups.length === 0) {
            dropdown.innerHTML = '<div class="gs-empty"><i class="bi bi-search me-1"></i>' + SEARCH_LANG.no_results + '</div>';
            showDropdown();
            return;
        }
        let html = '';
        groups.forEach(function(group) {
            html += '<div class="gs-category">';
            html += '<div class="gs-category-header"><i class="bi ' + escHtml(group.icon) + ' me-1"></i>' + escHtml(group.category) + '</div>';
            group.items.forEach(function(item) {
                html += '<a href="' + escAttr(item.url) + '" class="gs-item" tabindex="0">';
                html += '<i class="bi ' + escHtml(item.icon) + ' gs-item-icon"></i>';
                html += '<div class="gs-item-text">';
                html += '<div class="gs-item-label">' + escHtml(item.label) + '</div>';
                if (item.sublabel) {
                    html += '<div class="gs-item-sublabel">' + escHtml(item.sublabel) + '</div>';
                }
                html += '</div>';
                html += '</a>';
            });
            html += '</div>';
        });
        dropdown.innerHTML = html;
        showDropdown();
    }

    function showLoading() {
        dropdown.innerHTML = '<div class="gs-empty"><span class="spinner-border spinner-border-sm me-2"></span></div>';
        showDropdown();
    }

    function showDropdown() { dropdown.classList.add('show'); }
    function hideDropdown() { dropdown.classList.remove('show'); }

    function escHtml(str) {
        const div = document.createElement('div');
        div.textContent = str;
        return div.innerHTML;
    }
    function escAttr(str) {
        return str.replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    }
})();
</script>

<!-- Force logout AJAX + confirm handlers -->
<script nonce="<?= csp_nonce() ?>">
document.querySelectorAll('.btn-force-logout').forEach(function(btn) {
    btn.addEventListener('click', function() {
        var hash = this.getAttribute('data-hash');
        if (!confirm(<?= json_encode(__('admin_dashboard.btn_force_logout') . '?') ?>)) return;
        $.ajax({
            url: 'admin.php?page=dashboard&action=force_logout',
            method: 'POST',
            data: { session_hash: hash, csrf_token: <?= json_encode($_SESSION['csrf_token'] ?? '') ?> },
            dataType: 'json',
            success: function(data) {
                if (data.success) {
                    alert(<?= json_encode(__('admin_dashboard.session_terminated')) ?>);
                    location.reload();
                } else {
                    alert(data.error || <?= json_encode(__('admin_dashboard.session_terminate_error')) ?>);
                }
            },
            error: function() {
                alert(<?= json_encode(__('admin_dashboard.session_terminate_error')) ?>);
            }
        });
    });
});
var delLogo = document.getElementById('btnDeleteLogo');
if (delLogo) {
    delLogo.closest('form').addEventListener('submit', function(e) {
        if (!confirm(delLogo.getAttribute('data-confirm'))) e.preventDefault();
    });
}
</script>
