<?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 - Podgląd klienta (admin)
 */

$id = $_GET['id'] ?? '';
if (empty($id)) {
    echo '<div class="alert alert-danger">' . __('common.error') . '</div>';
    return;
}

$clients = vbk_read_klienci();
$client = $clients[$id] ?? null;

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

$dokumenty = vbk_read_dokumenty($id);
$oplaty = vbk_read_oplaty($id);
$devices = vbk_read_mac($id);
$info = vbk_read_info($id);
$infoadmin = vbk_read_infoadmin($id);

usort($dokumenty, function($a, $b) { return strcmp($b['data_wystawienia'], $a['data_wystawienia']); });

// Batch-check PDF existence
$pdf_filenames = [];
foreach ($dokumenty as $f) {
    if (!empty($f['pdf_filename'])) {
        $pdf_filenames[] = $f['pdf_filename'];
    }
}
$pdf_exists = [];
if (!empty($pdf_filenames) && function_exists('db_check_pdfs_exist')) {
    $pdf_exists = db_check_pdfs_exist($pdf_filenames, (int)$id);
} elseif (!empty($pdf_filenames)) {
    foreach ($pdf_filenames as $fn) {
        $pdf_exists[$fn] = file_exists(IBOK_DATA_DIR . '/' . $id . '/' . $fn);
    }
}
usort($oplaty, function($a, $b) { return strcmp($b['data_ksieg'], $a['data_ksieg']); });
?>

<div class="fade-in">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0">
            <i class="bi bi-person me-2"></i>
            <?= e($client['nazwisko']) ?>
            <small class="text-muted">(ID: <?= e(nr_klienta($id)) ?>)</small>
        </h4>
        <a href="admin.php?page=klienci" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i> <?= __('common.back') ?>
        </a>
    </div>

    <?= ibok_help_section('admin_klient', __('help.show_help'), __('help_admin.klient_section_content')) ?>

    <!-- Dane klienta -->
    <div class="row g-3 mb-4">
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card <?= $client['active_flag'] === '1' ? 'stat-success' : 'stat-danger' ?> p-3">
                <div class="stat-label"><?= __('admin_clients.status') ?></div>
                <div class="stat-value"><?= $client['active_flag'] === '1' ? __('admin_clients.active') : __('admin_clients.inactive') ?></div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card stat-info p-3">
                <div class="stat-label"><?= __('admin_clients.tariff') ?></div>
                <div class="stat-value">
                    <i class="bi bi-arrow-down text-success"></i> <?= e($client['dl_dzien']) ?>
                    / <i class="bi bi-arrow-up text-primary"></i> <?= e($client['ul_dzien']) ?>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card p-3">
                <div class="stat-label"><?= __('invoices.documents_title') ?></div>
                <div class="stat-value"><?= count($dokumenty) ?></div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6">
            <div class="card stat-card p-3">
                <div class="stat-label"><?= __('payments.title') ?></div>
                <div class="stat-value"><?= count($oplaty) ?></div>
            </div>
        </div>
    </div>

    <div class="row g-4">
        <!-- Lewa kolumna -->
        <div class="col-lg-4">
            <!-- Szczegóły klienta -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-person-lines-fill me-1"></i> <?= __('admin.client_view') ?>
                </div>
                <div class="card-body p-0">
                    <table class="table table-sm mb-0">
                        <tr><td class="fw-bold w-40">ID</td><td><?= e($id) ?></td></tr>
                        <tr><td class="fw-bold">Login</td><td class="font-monospace"><?= e($client['login']) ?></td></tr>
                        <?php if (!empty($client['haslo_encoded'])): ?>
                        <tr><td class="fw-bold"><?= __('admin_clients.password') ?></td>
                            <td>
                                <span class="font-monospace" id="clientPassMask">&bull;&bull;&bull;&bull;&bull;&bull;&bull;&bull;</span>
                                <span class="font-monospace d-none" id="clientPassPlain"><?= e($client['haslo_encoded']) ?></span>
                                <button type="button" class="btn btn-sm btn-link p-0 ms-2" id="btnTogglePass" title="<?= __('admin_clients.show_password') ?>">
                                    <i class="bi bi-eye" id="iconTogglePass"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <tr><td class="fw-bold"><?= __('dashboard.account_number') ?></td><td class="font-monospace small"><?= e($client['nr_rachunku']) ?></td></tr>
                        <?php if (ibok_has_night_speed($client['dl_dzien'], $client['ul_dzien'], $client['dl_noc'], $client['ul_noc'])): ?>
                        <tr><td class="fw-bold"><?= __('admin_clients.tariff') ?> (<?= __('dashboard.night') ?>)</td>
                            <td>
                                <i class="bi bi-arrow-down text-success"></i> <?= e($client['dl_noc']) ?>
                                / <i class="bi bi-arrow-up text-primary"></i> <?= e($client['ul_noc']) ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <tr><td class="fw-bold"><?= __('dashboard.total_obligations') ?></td>
                            <td>
                                <?php
                                $saldo_r = $client['saldo_raw'] ?? '';
                                $wg = (int)$client['wg_salda'];
                                if (!empty($saldo_r) && parse_kwota($saldo_r) > 0):
                                    echo '<span class="text-danger fw-bold">' . e($saldo_r) . ' PLN</span>';
                                elseif ($wg > 0):
                                    echo '<span class="text-danger fw-bold">' . number_format($wg, 2, ',', ' ') . ' PLN</span>';
                                elseif ((int)$client['nadplata'] > 0):
                                    echo '<span class="text-success">+' . e($client['nadplata']) . ' PLN</span>';
                                else:
                                    echo '<span class="text-success">OK</span>';
                                endif;
                                ?>
                            </td>
                        </tr>
                        <tr><td class="fw-bold"><?= __('dashboard.overdue_balance') ?></td>
                            <td>
                                <?php
                                $saldo_zr = $client['saldo_zalegle_raw'] ?? '';
                                if (!empty($saldo_zr) && parse_kwota($saldo_zr) > 0):
                                    echo '<span class="text-danger fw-bold">' . e($saldo_zr) . ' PLN</span>';
                                elseif ($wg > 0):
                                    echo '<span class="text-danger fw-bold">' . number_format($wg, 2, ',', ' ') . ' PLN</span>';
                                else:
                                    echo '<span class="text-success">0,00 PLN</span>';
                                endif;
                                ?>
                            </td>
                        </tr>
                        <?php if (!empty($client['umowa_od'])): ?>
                        <tr><td class="fw-bold"><?= __('dashboard.contract') ?></td>
                            <td><?= format_date($client['umowa_od']) ?>
                                <?php if (!empty($client['umowa_do'])): ?> - <?= format_date($client['umowa_do']) ?><?php endif; ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                        <?php
                        $data_ost_wplaty = $client['data_ostatniej_wplaty'] ?? '';
                        if (!empty($data_ost_wplaty)):
                        ?>
                        <tr><td class="fw-bold"><?= __('dashboard.last_payment_date') ?></td><td><?= format_date($data_ost_wplaty) ?></td></tr>
                        <?php endif; ?>
                        <?php
                        $powiadamiaj = $client['powiadamiaj'] ?? '';
                        $blokuj = $client['blokuj'] ?? '';
                        if (!empty($powiadamiaj) || !empty($blokuj)):
                        ?>
                        <tr><td class="fw-bold"><?= __('admin_clients.notifications') ?></td>
                            <td>
                                <?php if (!empty($powiadamiaj) && $powiadamiaj !== '0'): ?>
                                    <span class="badge bg-info"><?= __('admin_clients.notify_active') ?></span>
                                <?php else: ?>
                                    <span class="badge bg-secondary"><?= __('admin_clients.notify_inactive') ?></span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr><td class="fw-bold"><?= __('admin_clients.blocking') ?></td>
                            <td>
                                <?php if (!empty($blokuj) && $blokuj !== '0'): ?>
                                    <span class="badge bg-danger"><?= __('admin_clients.block_active') ?></span>
                                <?php else: ?>
                                    <span class="badge bg-secondary"><?= __('admin_clients.block_inactive') ?></span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endif; ?>
                    </table>
                </div>
            </div>

            <!-- Adres klienta (z infoadmin) -->
            <?php if (!empty($infoadmin['raw'])): ?>
            <div class="card mb-4">
                <div class="card-header"><i class="bi bi-geo-alt me-1"></i> <?= __('contact.address') ?></div>
                <div class="card-body">
                    <?php if (!empty($infoadmin['nazwa_pelna'])): ?>
                        <p class="fw-bold mb-1"><?= e($infoadmin['nazwa_pelna']) ?></p>
                    <?php else: ?>
                        <p class="mb-1"><?= e($infoadmin['nazwisko'] ?? '') ?></p>
                    <?php endif; ?>
                    <?php
                    // Ustal główny adres do mapy
                    $map_address_main = '';
                    if (!empty($infoadmin['adres_pelny'])) {
                        $map_address_main = $infoadmin['adres_pelny'];
                    } elseif (!empty($infoadmin['ulica']) || !empty($infoadmin['miejscowosc'])) {
                        $map_address_main = trim(($infoadmin['ulica'] ?? '') . ', ' . ($infoadmin['miejscowosc'] ?? ''), ', ');
                    }
                    ?>
                    <?php if (!empty($infoadmin['adres_pelny'])): ?>
                        <p class="mb-1"><?= e($infoadmin['adres_pelny']) ?></p>
                    <?php else: ?>
                        <?php if (!empty($infoadmin['ulica'])): ?><p class="mb-1"><?= e($infoadmin['ulica']) ?></p><?php endif; ?>
                        <?php if (!empty($infoadmin['miejscowosc'])): ?><p class="mb-0"><?= e($infoadmin['miejscowosc']) ?></p><?php endif; ?>
                    <?php endif; ?>
                    <?php if (!empty($map_address_main)): ?>
                        <a href="https://www.google.com/maps/search/?api=1&query=<?= urlencode($map_address_main) ?>" target="_blank" class="btn btn-sm btn-outline-primary mt-2">
                            <i class="bi bi-geo-alt-fill me-1"></i><?= __('contact.show_on_map') ?>
                        </a>
                    <?php endif; ?>
                    <?php if (!empty($infoadmin['adres_instalacji'])): ?>
                        <hr class="my-2">
                        <small class="text-muted d-block"><?= __('contact.installation_address') ?>:</small>
                        <p class="mb-1"><?= e($infoadmin['adres_instalacji']) ?></p>
                        <a href="https://www.google.com/maps/search/?api=1&query=<?= urlencode($infoadmin['adres_instalacji']) ?>" target="_blank" class="btn btn-sm btn-outline-success">
                            <i class="bi bi-geo-alt-fill me-1"></i><?= __('contact.show_on_map') ?>
                        </a>
                    <?php endif; ?>
                    <?php if (!empty($infoadmin['adres_korespondencyjny'])): ?>
                        <hr class="my-2">
                        <small class="text-muted d-block"><?= __('contact.correspondence_address') ?>:</small>
                        <p class="mb-0"><?= e($infoadmin['adres_korespondencyjny']) ?></p>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>

            <!-- Dane kontaktowe -->
            <?php
            $has_contact = !empty($infoadmin['tel1']) || !empty($infoadmin['tel2']) || !empty($infoadmin['email']) || !empty($infoadmin['nip']);
            if ($has_contact):
            ?>
            <div class="card mb-4">
                <div class="card-header"><i class="bi bi-telephone me-1"></i> <?= __('dashboard.contact_info') ?></div>
                <div class="card-body p-0">
                    <table class="table table-sm mb-0">
                        <?php if (!empty($infoadmin['tel1'])): ?>
                        <tr><td class="fw-bold w-40"><i class="bi bi-telephone me-1"></i> <?= __('contact.phone') ?></td><td><?= e($infoadmin['tel1']) ?></td></tr>
                        <?php endif; ?>
                        <?php if (!empty($infoadmin['tel2'])): ?>
                        <tr><td class="fw-bold"><i class="bi bi-telephone me-1"></i> <?= __('contact.phone') ?> 2</td><td><?= e($infoadmin['tel2']) ?></td></tr>
                        <?php endif; ?>
                        <?php if (!empty($infoadmin['email'])): ?>
                        <tr><td class="fw-bold"><i class="bi bi-envelope me-1"></i> <?= __('contact.email') ?></td><td><?= e($infoadmin['email']) ?></td></tr>
                        <?php endif; ?>
                        <?php if (!empty($infoadmin['nip'])): ?>
                        <tr><td class="fw-bold">NIP</td><td><?= e($infoadmin['nip']) ?></td></tr>
                        <?php endif; ?>
                    </table>
                </div>
            </div>
            <?php endif; ?>

            <!-- Urządzenia -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-router me-1"></i> <?= __('info.devices') ?>
                    <span class="badge bg-secondary ms-1"><?= count($devices) ?></span>
                </div>
                <div class="card-body">
                    <?php if (empty($devices)): ?>
                        <p class="text-muted"><?= __('info.no_devices') ?></p>
                    <?php else: ?>
                        <?php foreach ($devices as $dev): ?>
                        <div class="border rounded p-2 mb-2 small">
                            <strong><?= e($dev['rodzaj']) ?></strong>
                            <?php if (!empty($dev['typ'])): ?><span class="text-muted">(<?= e($dev['typ']) ?>)</span><?php endif; ?>
                            <br>
                            <?php if (!empty($dev['ip'])): ?>
                                <span class="font-monospace"><?= e($dev['ip']) ?></span>
                            <?php endif; ?>
                            <?php if (!empty($dev['mac'])): ?>
                                <span class="text-muted ms-2"><?= e($dev['mac']) ?></span>
                            <?php endif; ?>
                            <?php if (!empty($dev['taryfa'])): ?>
                                <br><i class="bi bi-speedometer2 me-1 text-info"></i> <strong><?= e($dev['taryfa']) ?></strong>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Prawa kolumna - Faktury + Płatności -->
        <div class="col-lg-8">
            <!-- Dokumenty (FV + PZ + FVK) -->
            <div class="card mb-4">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <span>
                        <i class="bi bi-receipt me-1"></i> <?= __('invoices.documents_title') ?>
                        <span class="badge bg-secondary ms-1"><?= count($dokumenty) ?></span>
                    </span>
                    <?php if (!empty($dokumenty)): ?>
                    <select class="form-select form-select-sm w-auto" id="adminDocTypeFilter" style="min-width: 160px;">
                        <option value=""><?= __('invoices.filter_all') ?></option>
                        <option value="FV"><?= __('invoices.filter_fv') ?></option>
                        <option value="FVK"><?= __('invoices.filter_fvk') ?></option>
                        <option value="PZ"><?= __('invoices.filter_pz') ?></option>
                    </select>
                    <?php endif; ?>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($dokumenty)): ?>
                        <p class="text-muted text-center py-3"><?= __('invoices.no_invoices') ?></p>
                    <?php else: ?>
                        <div class="table-responsive" style="max-height: 350px; overflow-y: auto;">
                            <table class="table table-sm table-hover mb-0" id="tblAdminDocs">
                                <thead class="table-light sticky-top">
                                    <tr>
                                        <th><?= __('invoices.issue_date') ?></th>
                                        <th><?= __('invoices.doc_type') ?></th>
                                        <th><?= __('invoices.invoice_number') ?></th>
                                        <th>PDF</th>
                                        <th><?= __('invoices.amount') ?></th>
                                        <th><?= __('invoices.remaining_amount') ?></th>
                                        <th><?= __('invoices.status') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($dokumenty as $f):
                                        $nr = $f['nr_faktury'] ?? '';
                                        $typ = $f['typ_dokumentu'] ?? 'FV';
                                        if ($typ === 'PZ') {
                                            $badge = '<span class="badge bg-success">PZ</span>';
                                        } elseif ($typ === 'FVK') {
                                            $badge = '<span class="badge bg-warning text-dark">FVK</span>';
                                        } else {
                                            $badge = '<span class="badge bg-primary">FV</span>';
                                        }
                                        $has_pdf = !empty($f['pdf_filename']) && !empty($pdf_exists[$f['pdf_filename']]);
                                    ?>
                                    <tr data-doc-type="<?= e(strtoupper($typ)) ?>">
                                        <td><?= format_date($f['data_wystawienia']) ?></td>
                                        <td><?= $badge ?></td>
                                        <td><?= e($nr) ?></td>
                                        <td>
                                            <?php if (!empty($f['pdf_filename'])): ?>
                                                <?php if ($has_pdf): ?>
                                                    <a href="pobierz.php?id=<?= urlencode($id) ?>&file=<?= urlencode($f['pdf_filename']) ?>"
                                                       class="text-danger" target="_blank" title="PDF"><i class="bi bi-file-pdf"></i></a>
                                                <?php else: ?>
                                                    <i class="bi bi-file-pdf text-muted" title="<?= __('invoices.pdf_not_available') ?>"></i>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </td>
                                        <td class="fw-bold"><?= e($f['kwota_brutto']) ?></td>
                                        <td>
                                            <?php
                                            $do_rozl_val = parse_kwota($f['kwota_do_rozl'] ?? '0');
                                            if ($do_rozl_val > 0): ?>
                                                <span class="text-danger"><?= e($f['kwota_do_rozl']) ?></span>
                                            <?php else: ?>
                                                <span class="text-success">-</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?= status_badge($f['status']) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Płatności -->
            <div class="card mb-4">
                <div class="card-header">
                    <i class="bi bi-credit-card me-1"></i> <?= __('payments.title') ?>
                    <span class="badge bg-secondary ms-1"><?= count($oplaty) ?></span>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($oplaty)): ?>
                        <p class="text-muted text-center py-3"><?= __('payments.no_payments') ?></p>
                    <?php else: ?>
                        <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
                            <table class="table table-sm table-hover mb-0">
                                <thead class="table-light sticky-top">
                                    <tr>
                                        <th><?= __('payments.booking_date') ?></th>
                                        <th><?= __('payments.payment_number') ?></th>
                                        <th><?= __('payments.payment_method') ?></th>
                                        <th><?= __('payments.amount') ?></th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach (array_slice($oplaty, 0, 30) as $o): ?>
                                    <tr>
                                        <td><?= format_date($o['data_ksieg']) ?></td>
                                        <td><?= e($o['nr_wplaty']) ?></td>
                                        <td><?= e($o['forma_platn']) ?></td>
                                        <td class="fw-bold"><?= e($o['kwota']) ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

        </div>
    </div>
</div>
<script nonce="<?= csp_nonce() ?>">
document.getElementById('adminDocTypeFilter')?.addEventListener('change', function() {
    var filter = this.value;
    var rows = document.querySelectorAll('#tblAdminDocs tbody tr');
    rows.forEach(function(row) {
        if (!filter || row.getAttribute('data-doc-type') === filter) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    });
});

document.getElementById('btnTogglePass')?.addEventListener('click', function() {
    var mask = document.getElementById('clientPassMask');
    var plain = document.getElementById('clientPassPlain');
    var icon = document.getElementById('iconTogglePass');
    if (plain.classList.contains('d-none')) {
        plain.classList.remove('d-none');
        mask.classList.add('d-none');
        icon.classList.replace('bi-eye', 'bi-eye-slash');
    } else {
        plain.classList.add('d-none');
        mask.classList.remove('d-none');
        icon.classList.replace('bi-eye-slash', 'bi-eye');
    }
});
</script>
