<?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 klienta
 */

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

$client_id = $_SESSION['client_id'];
$clients = vbk_read_klienci();
$client = $clients[$client_id] ?? null;
$podmiot_id = (int)($_SESSION['podmiot'] ?? 0);
$firma = vbk_read_firma($podmiot_id);
$enabled_gateways = payment_get_enabled_gateways();

if (!$client) {
    echo '<div class="alert alert-danger">' . __('common.error') . '</div>';
    return;
}

// Dane klienta
$nazwisko = $client['nazwisko'];
$nr_rach = $client['nr_rachunku'];
$dl_dzien = $client['dl_dzien'];
$ul_dzien = $client['ul_dzien'];
$dl_noc = $client['dl_noc'];
$ul_noc = $client['ul_noc'];
$umowa_od = $client['umowa_od'];
$umowa_do = $client['umowa_do'];

// Fallback: prędkości z urządzeń (vMac) gdy brak w karcie usera
if ((empty($dl_dzien) || $dl_dzien === '0') && ibok_feature('speed_from_devices')) {
    $devices_for_speed = vbk_read_mac($client_id);
    $dev_speed = get_max_device_speed($devices_for_speed);
    if (!empty($dev_speed['dl_dzien'])) {
        $dl_dzien = $dev_speed['dl_dzien'];
        $ul_dzien = $dev_speed['ul_dzien'];
        $dl_noc   = $dev_speed['dl_noc'];
        $ul_noc   = $dev_speed['ul_noc'];
    }
}

// Nadpisz datami z najnowszej podpisanej umowy z bazy (jeśli dostępna)
if (function_exists('db_read_najnowsza_umowa')) {
    $najnowsza = db_read_najnowsza_umowa($client_id);
    if ($najnowsza) {
        $umowa_od = $najnowsza['data_od'];
        $umowa_do = $najnowsza['data_do'];
    }
}
$nadplata = (int)$client['nadplata'];
$wg_salda = (int)$client['wg_salda'];
$wg_salda2 = (int)$client['wg_salda2'];
$zalega = $client['zalega'];
$active = $client['active_flag'] ?? '1';
$saldo_raw = $client['saldo_raw'] ?? '';
$saldo_zalegle_raw = $client['saldo_zalegle_raw'] ?? '';

// Nierozliczone dokumenty (FV + PZ)
$dokumenty_all = vbk_read_dokumenty($client_id);
$faktury = $dokumenty_all; // dla alertów (nowa faktura)
$nierozliczone = [];
foreach ($dokumenty_all as $f) {
    if (stripos($f['status'], 'NIEROZLICZONA') !== false || stripos($f['status'], 'nierozliczona') !== false) {
        $nierozliczone[] = $f;
    }
}

// Najbliższy termin płatności
$next_payment = null;
if (!empty($nierozliczone)) {
    $earliest_ts = null;
    foreach ($nierozliczone as $f) {
        $tp = $f['termin_platnosci'] ?? '';
        if (empty($tp) || $tp === '0000-00-00') continue;
        $ts = strtotime($tp);
        if ($ts === false) continue;
        if ($earliest_ts === null || $ts < $earliest_ts) {
            $earliest_ts = $ts;
            $next_payment = $f;
        }
    }
}

// Aktualności
$aktualnosci = read_admin_text('aktualnosci_start.txt');
$info1 = vbk_read_global_info(1);
$info2 = vbk_read_global_info(2);
$termin_platn = read_admin_text('termin_platnosci.txt');

// Nagłówek
$naglowek = read_admin_text('naglowek.txt');

// Powiadomienia (alerty)
$alerts = [];

// 1. Termin płatności < 7 dni
foreach ($nierozliczone as $f) {
    $tp = $f['termin_platnosci'] ?? '';
    if (empty($tp) || $tp === '0000-00-00') continue;
    $ts = strtotime($tp);
    if ($ts === false) continue;
    $days_to = (int)floor(($ts - strtotime('today')) / 86400);
    if ($days_to >= 0 && $days_to <= 7) {
        $alerts[] = [
            'type' => 'warning',
            'icon' => 'bi-exclamation-triangle',
            'text' => __('dashboard.alert_payment_soon', [
                'invoice' => $f['nr_faktury'],
                'date' => format_date($tp),
                'days' => $days_to,
            ]),
        ];
    }
}

// 2. Umowa wygasa w ciągu 30 dni
if (!empty($umowa_do) && $umowa_do !== '0000-00-00') {
    $umowa_ts = strtotime($umowa_do);
    if ($umowa_ts !== false) {
        $days_to_end = (int)floor(($umowa_ts - strtotime('today')) / 86400);
        if ($days_to_end >= 0 && $days_to_end <= 30) {
            $alerts[] = [
                'type' => 'info',
                'icon' => 'bi-file-earmark-text',
                'text' => __('dashboard.alert_contract_expiring', [
                    'date' => format_date($umowa_do),
                    'days' => $days_to_end,
                ]),
            ];
        }
    }
}

// 3. Nowa faktura z bieżącego miesiąca (max 1)
$current_ym = date('Y-m');
foreach ($faktury as $f) {
    $dw = $f['data_wystawienia'] ?? '';
    if (empty($dw) || $dw === '0000-00-00') continue;
    if (substr($dw, 0, 7) === $current_ym) {
        $alerts[] = [
            'type' => 'info',
            'icon' => 'bi-receipt',
            'text' => __('dashboard.alert_new_invoice', [
                'invoice' => $f['nr_faktury'],
                'date' => format_date($dw),
            ]),
        ];
        break;
    }
}

// 4. Oczekujące umowy do podpisu (z bazy PYXIS)
require_once __DIR__ . '/../inc/contracts.php';
$pending_count = 0;
if (contracts_menu_visible()) {
    $pending_count = contracts_count_pending_db($client_id);
}
if ($pending_count > 0) {
    $alerts[] = [
        'type' => 'warning',
        'icon' => 'bi-file-earmark-check',
        'text' => __('contracts.alert_pending', ['count' => $pending_count]),
    ];
}
?>

<div class="fade-in">
    <?php if (!empty($naglowek) && stripos($naglowek, 'Nagłówek') === false): ?>
        <div class="alert alert-info mb-4"><?= $naglowek ?></div>
    <?php endif; ?>

    <!-- Powitanie -->
    <h4 class="mb-4">
        <i class="bi bi-person-circle me-2"></i>
        <?= __('dashboard.welcome', ['name' => e($nazwisko)]) ?>
        <small class="text-muted ms-2">(<?= __('dashboard.client_id') ?>: <?= e(nr_klienta($client_id)) ?>)</small>
    </h4>

    <!-- Powiadomienia -->
    <?php foreach ($alerts as $alert): ?>
        <div class="alert alert-<?= $alert['type'] ?> alert-dismissible fade show" role="alert">
            <i class="bi <?= $alert['icon'] ?> me-1"></i> <?= e($alert['text']) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endforeach; ?>

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

    <!-- Karty statystyk -->
    <div class="row g-3 mb-4">
        <!-- Status konta -->
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card <?= $active === '1' ? 'stat-success' : 'stat-danger' ?> p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label"><?= __('dashboard.account_status') ?></div>
                        <div class="stat-value"><?= $active === '1' ? __('dashboard.active') : __('dashboard.inactive') ?></div>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-<?= $active === '1' ? 'check-circle' : 'x-circle' ?>"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Saldo -->
        <div class="col-md-3 col-sm-6">
            <?php
            $saldo_class = 'stat-info';
            if ($wg_salda > 0 || $zalega === '1') $saldo_class = 'stat-danger';
            elseif ($nadplata > 0) $saldo_class = 'stat-success';
            ?>
            <div class="card stat-card <?= $saldo_class ?> p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label"><?= __('dashboard.balance') ?><?= ibok_tooltip(__('help.tooltip_balance')) ?></div>
                        <div class="stat-value">
                            <?php if ($wg_salda > 0): ?>
                                <?= number_format($wg_salda, 2, ',', ' ') ?> PLN
                            <?php elseif ($nadplata > 0): ?>
                                +<?= e($nadplata) ?> PLN
                            <?php else: ?>
                                <?= __('dashboard.no_debt') ?>
                            <?php endif; ?>
                        </div>
                        <?php if ($wg_salda > 0 && $wg_salda2 > 0 && $wg_salda != $wg_salda2): ?>
                            <div class="small mt-1 opacity-75">
                                <?= __('dashboard.overdue_balance') ?>: <?= number_format($wg_salda2, 2, ',', ' ') ?> PLN
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-wallet2"></i>
                    </div>
                </div>
            </div>
        </div>

        <!-- Nierozliczone faktury -->
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card <?= count($nierozliczone) > 0 ? 'stat-warning' : 'stat-success' ?> p-3">
                <div class="d-flex justify-content-between align-items-center">
                    <div>
                        <div class="stat-label"><?= __('dashboard.unsettled_invoices') ?><?= ibok_tooltip(__('help.tooltip_unsettled')) ?></div>
                        <div class="stat-value"><?= count($nierozliczone) ?></div>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-receipt"></i>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!ibok_feature('hide_speed')): ?>
        <!-- Taryfa -->
        <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"><?= __('dashboard.your_tariff') ?></div>
                        <div class="stat-value">
                            <i class="bi bi-arrow-down text-success"></i> <?= e($dl_dzien) ?>
                            <i class="bi bi-arrow-up text-primary ms-1"></i> <?= e($ul_dzien) ?>
                        </div>
                    </div>
                    <div class="stat-icon">
                        <i class="bi bi-speedometer"></i>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div class="row g-4">
        <!-- Lewa kolumna -->
        <div class="col-lg-8">
            <!-- Nierozliczone faktury -->
            <?php if (!empty($nierozliczone)): ?>
            <?php
                // Czy którakolwiek faktura jest po terminie?
                $any_overdue = false;
                foreach ($nierozliczone as $_nf) {
                    $_tp = $_nf['termin_platnosci'] ?? '';
                    if (!empty($_tp) && $_tp !== '0000-00-00') {
                        $_ts = strtotime($_tp);
                        if ($_ts !== false && $_ts < strtotime('today')) {
                            $any_overdue = true;
                            break;
                        }
                    }
                }
            ?>
            <div class="card mb-4 <?= $any_overdue ? 'debt-alert' : 'debt-warning' ?>">
                <div class="card-header bg-transparent border-0">
                    <h6 class="mb-0 <?= $any_overdue ? 'text-danger' : 'text-warning' ?>">
                        <i class="bi bi-exclamation-triangle me-1"></i>
                        <?= __('dashboard.unsettled_invoices') ?> (<?= count($nierozliczone) ?>)
                    </h6>
                </div>
                <div class="card-body pt-0" style="overflow: visible;">
                    <div style="overflow: visible;">
                        <table class="table table-sm mb-0">
                            <thead>
                                <tr>
                                    <th><?= __('invoices.invoice_number') ?></th>
                                    <th><?= __('invoices.amount') ?></th>
                                    <th class="d-none d-sm-table-cell"><?= __('invoices.remaining_amount') ?></th>
                                    <th class="d-none d-sm-table-cell"><?= __('invoices.due_date') ?></th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($nierozliczone as $f): ?>
                                <tr>
                                    <td><?= e($f['nr_faktury']) ?></td>
                                    <td class="fw-bold"><?= e($f['kwota_brutto']) ?></td>
                                    <td class="text-danger d-none d-sm-table-cell"><?= e($f['kwota_do_rozl'] ?? '') ?></td>
                                    <td class="d-none d-sm-table-cell"><?= format_date($f['termin_platnosci']) ?></td>
                                    <td>
                                        <?php
                                        $kwota_raw = str_replace(['zł', ' '], '', $f['kwota_brutto']);
                                        $kwota_raw = trim($kwota_raw);
                                        ?>
                                        <div class="btn-group">
                                            <?php if (!empty($enabled_gateways)): ?>
                                                <?php if (count($enabled_gateways) === 1): ?>
                                                    <form method="post" action="payment_init.php" target="_blank" class="d-inline payment-form">
                                                        <?= csrf_field() ?>
                                                        <input type="hidden" name="gateway" value="<?= e($enabled_gateways[0]) ?>">
                                                        <input type="hidden" name="invoice_nr" value="<?= e($f['nr_faktury']) ?>">
                                                        <input type="hidden" name="kwota" value="<?= e($kwota_raw) ?>">
                                                        <button type="submit" class="btn btn-sm btn-link text-success p-0" title="<?= __('payment.pay') ?>">
                                                            <i class="bi bi-credit-card"></i>
                                                        </button>
                                                    </form>
                                                <?php else: ?>
                                                    <div class="btn-group">
                                                        <button type="button" class="btn btn-sm btn-link text-success p-0 dropdown-toggle" data-bs-toggle="dropdown" title="<?= __('payment.pay_online') ?>">
                                                            <i class="bi bi-credit-card"></i>
                                                        </button>
                                                        <ul class="dropdown-menu dropdown-menu-end">
                                                            <?php foreach ($enabled_gateways as $gw): ?>
                                                            <li>
                                                                <form method="post" action="payment_init.php" target="_blank" class="payment-form">
                                                                    <?= csrf_field() ?>
                                                                    <input type="hidden" name="gateway" value="<?= e($gw) ?>">
                                                                    <input type="hidden" name="invoice_nr" value="<?= e($f['nr_faktury']) ?>">
                                                                    <input type="hidden" name="kwota" value="<?= e($kwota_raw) ?>">
                                                                    <button type="submit" class="dropdown-item">
                                                                        <i class="bi bi-wallet2 me-1"></i> <?= e(payment_gateway_label($gw)) ?>
                                                                    </button>
                                                                </form>
                                                            </li>
                                                            <?php endforeach; ?>
                                                        </ul>
                                                    </div>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <?php include __DIR__ . '/../inc/payment_terms_modal.php'; ?>
            <?php endif; ?>

            <!-- Aktualności -->
            <?php if (!empty($aktualnosci) || !empty($info1)): ?>
            <div class="card news-card mb-4">
                <div class="card-header">
                    <i class="bi bi-megaphone me-1"></i> <?= __('dashboard.news') ?>
                </div>
                <div class="card-body">
                    <?php if (!empty($info1)): ?>
                        <div class="mb-3"><?= $info1 ?></div>
                    <?php endif; ?>
                    <?php if (!empty($aktualnosci)): ?>
                        <div><?= $aktualnosci ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Informacja o płatnościach -->
            <?php if (!empty($termin_platn) || !empty($info2)): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-calendar-check me-1"></i> <?= __('dashboard.payment_info') ?>
                </div>
                <div class="card-body">
                    <?php if (!empty($info2)): ?>
                        <div class="mb-3"><?= $info2 ?></div>
                    <?php endif; ?>
                    <?php if (!empty($termin_platn)): ?>
                        <div><?= $termin_platn ?></div>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>

        <!-- Prawa kolumna -->
        <div class="col-lg-4">
            <!-- Najbliższy termin płatności -->
            <?php if ($next_payment): ?>
            <?php
                $np_termin = $next_payment['termin_platnosci'];
                $np_ts = strtotime($np_termin);
                $np_diff = (int)floor(($np_ts - strtotime('today')) / 86400);
            ?>
            <div class="card mb-4 <?= $np_diff < 0 ? 'border-danger' : ($np_diff === 0 ? 'border-warning' : '') ?>">
                <div class="card-header">
                    <i class="bi bi-clock-history me-1"></i> <?= __('dashboard.next_payment') ?><?= ibok_tooltip(__('help.tooltip_next_payment')) ?>
                </div>
                <div class="card-body">
                    <p class="mb-1"><strong><?= e($next_payment['nr_faktury']) ?></strong></p>
                    <p class="mb-1"><?= e($next_payment['kwota_brutto']) ?></p>
                    <p class="mb-2"><?= format_date($np_termin) ?></p>
                    <?php if ($np_diff > 0): ?>
                        <span class="badge bg-success"><?= __('dashboard.days_left', ['days' => $np_diff]) ?></span>
                    <?php elseif ($np_diff === 0): ?>
                        <span class="badge bg-warning text-dark payment-badge-urgent"><?= __('dashboard.due_today') ?></span>
                    <?php else: ?>
                        <span class="badge bg-danger payment-badge-urgent"><?= __('dashboard.days_overdue', ['days' => abs($np_diff)]) ?></span>
                    <?php endif; ?>

                    <?php if ($np_diff >= 0): ?>
                    <div class="payment-countdown mt-2" id="paymentCountdown" data-deadline="<?= e($np_termin) ?>">
                        <small class="text-muted">
                            <i class="bi bi-hourglass-split"></i> <span id="countdownText"></span>
                        </small>
                    </div>
                    <?php endif; ?>

                    <div class="progress mt-2" style="height: 6px;" data-bs-toggle="tooltip" title="<?= e(__('help.tooltip_progress_bar')) ?>">
                        <?php
                        $progress_pct = $np_diff >= 0 ? max(0, min(100, ($np_diff / 30) * 100)) : 0;
                        $bar_class = $np_diff < 0 ? 'bg-danger' : ($np_diff <= 3 ? 'bg-warning' : 'bg-success');
                        ?>
                        <div class="progress-bar <?= $bar_class ?>" role="progressbar"
                             style="width: <?= $progress_pct ?>%"
                             aria-valuenow="<?= $progress_pct ?>" aria-valuemin="0" aria-valuemax="100"></div>
                    </div>
                </div>
            </div>
            <?php endif; ?>

            <!-- Dane rachunku -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-bank me-1"></i> <?= __('dashboard.account_number') ?><?= ibok_tooltip(__('help.tooltip_account_number')) ?>
                </div>
                <div class="card-body">
                    <div class="d-flex align-items-center gap-2 mb-1">
                        <p class="fw-bold text-primary mb-0" style="font-family: monospace; font-size: 0.95rem;" id="accountNumber">
                            <?= e($nr_rach) ?>
                        </p>
                        <?php if (!empty($nr_rach)): ?>
                        <button type="button" class="btn btn-sm btn-link text-secondary p-0" id="btnCopyAccount"
                                title="<?= __('payment.copy_account') ?>">
                            <i class="bi bi-clipboard"></i>
                        </button>
                        <?php endif; ?>
                    </div>
                    <small class="text-muted"><?= e($firma['bank'] ?? '') ?></small>
                </div>
            </div>

            <!-- Szczegóły salda -->
            <?php if ($wg_salda > 0 || !empty($saldo_raw)): ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-wallet2 me-1"></i> <?= __('dashboard.balance_details') ?>
                </div>
                <div class="card-body p-0">
                    <table class="table table-sm mb-0">
                        <tr>
                            <td><?= __('dashboard.total_obligations') ?></td>
                            <td class="text-end fw-bold <?= $wg_salda > 0 ? 'text-danger' : 'text-success' ?>">
                                <?= !empty($saldo_raw) ? e($saldo_raw) . ' PLN' : number_format($wg_salda, 2, ',', ' ') . ' PLN' ?>
                            </td>
                        </tr>
                        <tr>
                            <td><?= __('dashboard.overdue_balance') ?></td>
                            <td class="text-end fw-bold <?= $wg_salda > 0 ? 'text-danger' : 'text-success' ?>">
                                <?= !empty($saldo_zalegle_raw) ? e($saldo_zalegle_raw) . ' PLN' : number_format($wg_salda, 2, ',', ' ') . ' PLN' ?>
                            </td>
                        </tr>
                        <?php if ($nadplata > 0): ?>
                        <tr>
                            <td><?= __('dashboard.overpayment') ?></td>
                            <td class="text-end fw-bold text-success"><?= e($nadplata) ?> PLN</td>
                        </tr>
                        <?php endif; ?>
                        <?php
                        $data_ost_wplaty = $client['data_ostatniej_wplaty'] ?? '';
                        if (!empty($data_ost_wplaty)):
                        ?>
                        <tr>
                            <td><?= __('dashboard.last_payment_date') ?></td>
                            <td class="text-end"><?= format_date($data_ost_wplaty) ?></td>
                        </tr>
                        <?php endif; ?>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <?php if (!ibok_feature('hide_speed')): ?>
            <!-- Taryfa szczegóły -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-speedometer me-1"></i> <?= __('dashboard.your_tariff') ?>
                </div>
                <div class="card-body p-0">
                    <table class="table table-sm tariff-table mb-0">
                        <tr>
                            <td><i class="bi bi-arrow-down text-success me-1"></i> <?= __('dashboard.download') ?> (<?= __('dashboard.day') ?>)</td>
                            <td><?= e($dl_dzien) ?></td>
                        </tr>
                        <tr>
                            <td><i class="bi bi-arrow-up text-primary me-1"></i> <?= __('dashboard.upload') ?> (<?= __('dashboard.day') ?>)</td>
                            <td><?= e($ul_dzien) ?></td>
                        </tr>
                        <?php if (ibok_has_night_speed($dl_dzien, $ul_dzien, $dl_noc, $ul_noc)): ?>
                        <tr>
                            <td><i class="bi bi-arrow-down text-success me-1"></i> <?= __('dashboard.download') ?> (<?= __('dashboard.night') ?>)</td>
                            <td><?= e($dl_noc) ?></td>
                        </tr>
                        <tr>
                            <td><i class="bi bi-arrow-up text-primary me-1"></i> <?= __('dashboard.upload') ?> (<?= __('dashboard.night') ?>)</td>
                            <td><?= e($ul_noc) ?></td>
                        </tr>
                        <?php endif; ?>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <!-- Umowa -->
            <?php if (!empty($umowa_od) || !empty($umowa_do)): ?>
            <?php
            // Umowa bezterminowa: brak daty końca, data zerowa, lub data < dzisiaj
            $is_indefinite = empty($umowa_do) || $umowa_do === '0000-00-00';
            if (!$is_indefinite) {
                $umowa_do_ts = strtotime($umowa_do);
                if ($umowa_do_ts !== false && $umowa_do_ts < strtotime('today')) {
                    $is_indefinite = true;
                }
            }
            ?>
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-file-earmark-text me-1"></i> <?= __('dashboard.contract') ?>
                </div>
                <div class="card-body">
                    <?php if (!empty($umowa_od)): ?>
                        <p class="mb-1"><?= __('dashboard.contract_from') ?>: <strong><?= format_date($umowa_od) ?></strong></p>
                    <?php endif; ?>
                    <?php if ($is_indefinite): ?>
                        <p class="mb-0 text-muted"><?= __('dashboard.contract_indefinite') ?></p>
                    <?php else: ?>
                        <p class="mb-0"><?= __('dashboard.contract_to') ?>: <strong><?= format_date($umowa_do) ?></strong></p>
                    <?php endif; ?>

                    <?php if (!empty($umowa_od) && !$is_indefinite && !empty($umowa_do)):
                        $contract_start = strtotime($umowa_od);
                        $contract_end = strtotime($umowa_do);
                        if ($contract_start && $contract_end && $contract_end > $contract_start):
                            $total_days = (int)floor(($contract_end - $contract_start) / 86400);
                            $elapsed_days = (int)floor((time() - $contract_start) / 86400);
                            $remaining_days = (int)floor(($contract_end - time()) / 86400);
                            $percent = $total_days > 0 ? min(100, max(0, round(($elapsed_days / $total_days) * 100))) : 0;
                            $bar_class = 'bg-success';
                            if ($remaining_days < 0) $bar_class = 'bg-danger';
                            elseif ($percent > 75) $bar_class = 'bg-danger';
                            elseif ($percent > 50) $bar_class = 'bg-warning';
                    ?>
                        <hr class="my-2">
                        <small class="text-muted d-block mb-1"><?= __('dashboard.contract_progress') ?></small>
                        <div class="progress" style="height: 8px;">
                            <div class="progress-bar <?= $bar_class ?>" style="width: <?= $percent ?>%"></div>
                        </div>
                        <small class="text-muted">
                            <?php if ($remaining_days >= 0): ?>
                                <?= __('dashboard.contract_remaining', ['days' => $remaining_days, 'percent' => (100 - $percent)]) ?>
                            <?php else: ?>
                                <span class="text-danger"><?= __('dashboard.contract_expired') ?></span>
                            <?php endif; ?>
                        </small>
                    <?php endif; endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Dane firmy -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-building me-1"></i> <?= __('dashboard.company_info') ?>
                </div>
                <div class="card-body">
                    <p class="fw-bold mb-1"><?= e($firma['nazwa'] ?? '') ?></p>
                    <p class="mb-1 small"><?= e($firma['adres1'] ?? '') ?></p>
                    <p class="mb-2 small"><?= e($firma['adres2'] ?? '') ?></p>
                    <?php if (!empty($firma['telefon'])): ?>
                        <p class="mb-1 small"><i class="bi bi-telephone me-1"></i> <?= e(trim($firma['telefon'])) ?></p>
                    <?php endif; ?>
                    <?php if (!empty($firma['email'])): ?>
                        <p class="mb-1 small"><i class="bi bi-envelope me-1"></i> <?= e(trim($firma['email'])) ?></p>
                    <?php endif; ?>
                    <?php if (!empty($firma['www'])): ?>
                        <p class="mb-0 small"><i class="bi bi-globe me-1"></i> <?= e(trim($firma['www'])) ?></p>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
var btnCopy = document.getElementById('btnCopyAccount');
if (btnCopy) btnCopy.addEventListener('click', copyAccountNumber);
function copyAccountNumber() {
    var text = document.getElementById('accountNumber').textContent.trim();
    var btn = document.getElementById('btnCopyAccount');
    navigator.clipboard.writeText(text).then(function() {
        btn.innerHTML = '<i class="bi bi-check-lg"></i>';
        btn.classList.remove('btn-outline-secondary');
        btn.classList.add('btn-success');
        setTimeout(function() {
            btn.innerHTML = '<i class="bi bi-clipboard"></i>';
            btn.classList.remove('btn-success');
            btn.classList.add('btn-outline-secondary');
        }, 2000);
    }).catch(function() {
        btn.innerHTML = '<i class="bi bi-x-lg"></i>';
        btn.classList.remove('btn-outline-secondary');
        btn.classList.add('btn-danger');
        setTimeout(function() {
            btn.innerHTML = '<i class="bi bi-clipboard"></i>';
            btn.classList.remove('btn-danger');
            btn.classList.add('btn-outline-secondary');
        }, 2000);
    });
}

// Payment countdown
(function() {
    var el = document.getElementById('paymentCountdown');
    if (!el) return;
    var deadline = el.getAttribute('data-deadline');
    if (!deadline) return;
    var deadlineDate = new Date(deadline + 'T23:59:59');
    var COUNTDOWN_TPL = <?= json_encode(__('dashboard.payment_countdown', ['days' => '{D}', 'hours' => '{H}', 'mins' => '{M}'])) ?>;
    var DUE_TODAY = <?= json_encode(__('dashboard.payment_due_today')) ?>;

    function update() {
        var now = new Date();
        var diff = deadlineDate - now;
        var text = document.getElementById('countdownText');
        if (!text) return;
        if (diff <= 0) {
            text.textContent = DUE_TODAY;
            return;
        }
        var days = Math.floor(diff / 86400000);
        var hours = Math.floor((diff % 86400000) / 3600000);
        var mins = Math.floor((diff % 3600000) / 60000);
        text.textContent = COUNTDOWN_TPL.replace('{D}', days).replace('{H}', hours).replace('{M}', mins);
    }
    update();
    setInterval(update, 60000);
})();
</script>
