<?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 - Lista dokumentów klienta (faktury FV, potwierdzenia zapłaty PZ, korekty FVK)
 */

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

$client_id = $_SESSION['client_id'];
$dokumenty = vbk_read_dokumenty($client_id);
$enabled_gateways = payment_get_enabled_gateways();

// Komunikat błędu po nieudanej inicjalizacji płatności (redirect z payment_init.php)
$payment_error = '';
if (!empty($_GET['error'])) {
    $payment_error_map = [
        'gateway'  => __('payment.error_gateway'),
        'disabled' => __('payment.error_disabled'),
        'amount'   => __('payment.error_amount'),
        'invoice'  => __('payment.error_invoice'),
        'demo'     => __('demo.feature_blocked'),
        'csrf'     => __('payment.error_init'),
        'init'     => __('payment.error_init'),
    ];
    $payment_error = $payment_error_map[$_GET['error']] ?? __('payment.error_init');
}

// Sortuj od najnowszych
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)$client_id);
} elseif (!empty($pdf_filenames)) {
    // Fallback: check disk only
    foreach ($pdf_filenames as $fn) {
        $pdf_exists[$fn] = file_exists(IBOK_DATA_DIR . '/' . $client_id . '/' . $fn);
    }
}
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-receipt me-2"></i> <?= __('invoices.documents_title') ?>
        <span class="badge bg-secondary ms-2"><?= count($dokumenty) ?></span>
    </h4>

    <?php if ($payment_error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="bi bi-exclamation-triangle-fill me-1"></i> <?= e($payment_error) ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="<?= __('common.close') ?>"></button>
    </div>
    <?php endif; ?>

    <?= ibok_help_section('faktury', __('help.show_help'), __('help.faktury_section_content')) ?>

    <div class="card">
        <div class="card-body">
            <?php if (empty($dokumenty)): ?>
                <p class="text-muted text-center py-4"><?= __('invoices.no_documents') ?></p>
            <?php else: ?>
                <!-- Document type filter -->
                <div class="mb-3">
                    <select class="form-select form-select-sm w-auto" id="docTypeFilter">
                        <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>
                </div>

                <div class="table-responsive">
                    <table class="table table-hover ibok-table" id="tblFaktury">
                        <thead>
                            <tr>
                                <th><?= __('invoices.issue_date') ?></th>
                                <th><?= __('invoices.doc_type') ?></th>
                                <th><?= __('invoices.invoice_number') ?></th>
                                <th><?= __('invoices.pdf') ?></th>
                                <th><?= __('invoices.amount') ?><?= ibok_tooltip(__('help.tooltip_amount_gross')) ?></th>
                                <th><?= __('invoices.status') ?><?= ibok_tooltip(__('help.tooltip_status')) ?></th>
                                <th><?= __('invoices.remaining_amount') ?></th>
                                <th><?= __('invoices.due_date') ?><?= ibok_tooltip(__('help.tooltip_due_date')) ?></th>
                                <th class="text-center"><?= __('common.actions') ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($dokumenty as $f): ?>
                            <?php
                                // Determine document type from number prefix
                                $doc_type = '';
                                $doc_badge = '';
                                $nr = $f['nr_faktury'] ?? '';
                                if (stripos($nr, 'FVK') === 0 || stripos($nr, 'FVK/') !== false) {
                                    $doc_type = 'FVK';
                                    $doc_badge = '<span class="badge bg-warning text-dark">FVK</span>';
                                } elseif (stripos($nr, 'FV') === 0 || stripos($nr, 'FV/') !== false) {
                                    $doc_type = 'FV';
                                    $doc_badge = '<span class="badge bg-primary">FV</span>';
                                } elseif (stripos($nr, 'PZ') === 0 || stripos($nr, 'PZ/') !== false) {
                                    $doc_type = 'PZ';
                                    $doc_badge = '<span class="badge bg-success">PZ</span>';
                                } else {
                                    $doc_type = isset($f['typ_dokumentu']) ? $f['typ_dokumentu'] : '';
                                    if (strtoupper($doc_type) === 'FV') {
                                        $doc_badge = '<span class="badge bg-primary">FV</span>';
                                    } elseif (strtoupper($doc_type) === 'PZ') {
                                        $doc_badge = '<span class="badge bg-success">PZ</span>';
                                    } elseif (strtoupper($doc_type) === 'FVK') {
                                        $doc_badge = '<span class="badge bg-warning text-dark">FVK</span>';
                                    } else {
                                        $doc_badge = '<span class="badge bg-secondary">' . e($doc_type ?: '?') . '</span>';
                                    }
                                }
                                $has_pdf = !empty($f['pdf_filename']) && !empty($pdf_exists[$f['pdf_filename']]);
                            ?>
                            <tr data-doc-type="<?= e(strtoupper($doc_type)) ?>">
                                <td data-order="<?= e($f['data_wystawienia']) ?>"><?= format_date($f['data_wystawienia']) ?></td>
                                <td><?= $doc_badge ?></td>
                                <td><?= e($f['nr_faktury']) ?></td>
                                <td>
                                    <?php if (!empty($f['pdf_filename'])): ?>
                                        <?php if ($has_pdf): ?>
                                            <a href="pobierz.php?id=<?= urlencode($client_id) ?>&file=<?= urlencode($f['pdf_filename']) ?>"
                                               class="btn btn-sm btn-outline-danger" target="_blank" title="<?= __('invoices.download_pdf') ?>">
                                                <i class="bi bi-file-pdf"></i> PDF
                                            </a>
                                        <?php else: ?>
                                            <span class="btn btn-sm btn-outline-secondary disabled" title="<?= __('invoices.pdf_not_available') ?>">
                                                <i class="bi bi-file-pdf text-muted"></i> PDF
                                            </span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td class="fw-bold"><?= e($f['kwota_brutto']) ?></td>
                                <td><?= status_badge($f['status']) ?></td>
                                <td>
                                    <?php
                                    $do_rozl = $f['kwota_do_rozl'] ?? '';
                                    $do_rozl_val = parse_kwota($do_rozl);
                                    if ($do_rozl_val > 0):
                                    ?>
                                        <span class="text-danger fw-bold"><?= e($do_rozl) ?></span>
                                    <?php else: ?>
                                        <span class="text-success">-</span>
                                    <?php endif; ?>
                                </td>
                                <td data-order="<?= e($f['termin_platnosci']) ?>"><?= format_date($f['termin_platnosci']) ?></td>
                                <td class="text-center">
                                    <?php
                                    $kwota_raw = str_replace(['zł', ' '], '', $f['kwota_brutto']);
                                    $kwota_raw = trim($kwota_raw);
                                    $is_unsettled = (stripos($f['status'], 'NIEROZLICZONA') !== false || stripos($f['status'], 'nierozliczona') !== false);
                                    ?>
                                    <div class="btn-group">
                                        <?php if ($is_unsettled && !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') ?> - <?= e(payment_gateway_label($enabled_gateways[0])) ?>">
                                                        <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>

                <script nonce="<?= csp_nonce() ?>">
                document.getElementById('docTypeFilter').addEventListener('change', function() {
                    var val = this.value;
                    // Column index 1 = doc type badge (contains FV, FVK, PZ text)
                    var table = $('#tblFaktury').DataTable();
                    if (val) {
                        table.column(1).search('^' + val + '$', true, false).draw();
                    } else {
                        table.column(1).search('').draw();
                    }
                });
                </script>
                <?php include __DIR__ . '/../inc/payment_terms_modal.php'; ?>
            <?php endif; ?>
        </div>
    </div>
</div>
