<?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 - Admin: Umowy (read-only z bazy PYXIS — vUmowyLista)
 *
 * Umowy tworzone w PYXIS, tutaj tylko podgląd.
 */

require_once __DIR__ . '/../inc/contracts.php';
require_once __DIR__ . '/../inc/db_mysql.php';

// AJAX: toggle show_in_menu setting
$ajax_action = $_GET['action'] ?? '';

if ($ajax_action === 'toggle_menu' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');
    if (!csrf_validate()) {
        echo json_encode(['success' => false, 'error' => __('login.error_csrf')]);
        exit;
    }
    $settings = contracts_load_settings();
    $settings['show_in_menu'] = !empty($_POST['show_in_menu']);
    contracts_save_settings($settings);
    ibok_log("Zmieniono widoczność umów w menu klienta: " . ($settings['show_in_menu'] ? 'ON' : 'OFF'), 'info');
    echo json_encode(['success' => true]);
    exit;
}

// --- Widoki ---
$view = $_GET['v'] ?? 'list';

// Badge typów
function admin_umowa_type_badge($typ) {
    $map = [
        'umowa' => ['bg-primary', 'contracts.type_umowa'],
        'aneks' => ['bg-warning text-dark', 'contracts.type_aneks'],
        'pzo'   => ['bg-success', 'contracts.type_pzo'],
        'info'  => ['bg-info text-dark', 'contracts.type_info'],
    ];
    $cfg = $map[$typ] ?? $map['umowa'];
    return '<span class="badge ' . $cfg[0] . '">' . __($cfg[1]) . '</span>';
}

// ========================
// WIDOK: Szczegóły klienta
// ========================
if ($view === 'view'):
    $cid = $_GET['cid'] ?? '';
    if (empty($cid)):
?>
    <div class="alert alert-danger"><?= __('contracts.error_invalid_client') ?></div>
    <a href="admin.php?page=contracts" class="btn btn-outline-secondary"><i class="bi bi-arrow-left me-1"></i> <?= __('common.back') ?></a>
<?php else:
    $umowy = db_read_umowy_admin($cid);
    $clients = vbk_read_klienci();
    $client_name = $clients[(int)$cid]['nazwisko'] ?? '-';
?>
<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-file-earmark-check me-2"></i><?= __('contracts.view_title') ?>
        — <?= e(nr_klienta((int)$cid)) ?> <?= e($client_name) ?>
    </h4>

    <a href="admin.php?page=contracts" class="btn btn-outline-secondary mb-3">
        <i class="bi bi-arrow-left me-1"></i> <?= __('common.back') ?>
    </a>

    <?php if (empty($umowy)): ?>
        <div class="alert alert-info">
            <i class="bi bi-info-circle me-1"></i> <?= __('contracts.no_contracts') ?>
        </div>
    <?php else: ?>
        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-sm mb-0">
                        <thead class="table-light">
                            <tr>
                                <th><?= __('contracts.contract_number') ?></th>
                                <th><?= __('contracts.contract_type') ?></th>
                                <th><?= __('contracts.contract_date_from') ?></th>
                                <th><?= __('contracts.contract_date_to') ?></th>
                                <th><?= __('common.status') ?></th>
                                <th>i-BOK</th>
                                <th>PDF</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($umowy as $u): ?>
                            <tr class="<?= $u['nieaktywna'] ? 'text-muted' : '' ?>">
                                <td>
                                    <?= e($u['numer']) ?>
                                    <?php if (!empty($u['uwagi'])): ?>
                                        <div class="small text-muted mt-1"><i class="bi bi-chat-left-text me-1"></i><?= e($u['uwagi']) ?></div>
                                    <?php endif; ?>
                                </td>
                                <td><?= admin_umowa_type_badge($u['typ']) ?></td>
                                <td><?= format_date($u['data_od']) ?></td>
                                <td><?= format_date($u['data_do']) ?></td>
                                <td>
                                    <?php if ($u['nieaktywna']): ?>
                                        <span class="badge bg-secondary"><?= __('dashboard.inactive') ?></span>
                                    <?php elseif ($u['podpisana']): ?>
                                        <span class="badge bg-success"><i class="bi bi-check-circle me-1"></i><?= __('contracts.status_signed') ?></span>
                                        <?php $sig = contracts_get_signature((int)$u['um_index']); ?>
                                        <?php if ($sig): ?>
                                        <div class="small text-muted mt-1">
                                            <i class="bi bi-clock me-1"></i><?= __('contracts.signed_at_label') ?>: <?= e($sig['signed_at']) ?>
                                            <?php if (!empty($sig['ip'])): ?>
                                            <br><i class="bi bi-hdd-network me-1"></i><?= __('contracts.signed_ip_label') ?>: <?= e($sig['ip']) ?>
                                            <?php endif; ?>
                                        </div>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <span class="badge bg-warning text-dark"><i class="bi bi-hourglass-split me-1"></i><?= __('contracts.status_pending') ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($u['na_iboku']): ?>
                                        <i class="bi bi-eye text-success" title="<?= __('contracts.show_in_menu') ?>"></i>
                                    <?php else: ?>
                                        <i class="bi bi-eye-slash text-muted"></i>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if (!empty($u['pdf_filename'])): ?>
                                    <a href="pobierz.php?id=<?= e($cid) ?>&file=<?= urlencode($u['pdf_filename']) ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                        <i class="bi bi-file-earmark-pdf"></i>
                                    </a>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>
</div>
<?php endif; ?>

<?php
// ========================
// WIDOK: Lista (domyślny)
// ========================
else:
    $all_umowy = db_read_umowy_all();
    $clients = vbk_read_klienci();

    // Tylko umowy wysłane na iBOK i jeszcze niepodpisane (aktywne)
    $by_client = [];
    foreach ($all_umowy as $u) {
        if (!$u['na_iboku'] || $u['podpisana'] || $u['nieaktywna']) continue;
        $cid = $u['client_id'];
        if (!isset($by_client[$cid])) {
            $by_client[$cid] = ['umowy' => [], 'pending' => 0];
        }
        $by_client[$cid]['umowy'][] = $u;
        $by_client[$cid]['pending']++;
    }

    // Umowy podpisane przez i-BOK (mają zapisane metadane: data/godzina/IP)
    $sigs = contracts_all_signatures();
    $signed = [];
    foreach ($all_umowy as $u) {
        $idx = (int)$u['um_index'];
        if (isset($sigs[$idx])) {
            $signed[] = ['u' => $u, 'sig' => $sigs[$idx]];
        }
    }
    usort($signed, function ($a, $b) {
        return strcmp($b['sig']['signed_at'] ?? '', $a['sig']['signed_at'] ?? '');
    });
?>
<div class="fade-in">
    <?php $contracts_settings = contracts_load_settings(); ?>
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h4 class="mb-0">
            <i class="bi bi-file-earmark-check me-2"></i><?= __('contracts.admin_title') ?>
        </h4>
    </div>

    <?= ibok_help_section('admin_contracts', __('help.show_help'), __('help_admin.contracts_section_content')) ?>

    <div class="card mb-4">
        <div class="card-body py-2 d-flex align-items-center justify-content-between">
            <div class="form-check form-switch mb-0">
                <input class="form-check-input" type="checkbox" role="switch" id="showInMenuToggle"
                       <?= !empty($contracts_settings['show_in_menu']) ? 'checked' : '' ?>>
                <label class="form-check-label" for="showInMenuToggle">
                    <i class="bi bi-layout-text-sidebar-reverse me-1"></i><?= __('contracts.show_in_menu') ?>
                </label>
            </div>
            <small class="text-muted" id="toggleStatus">
                <?= !empty($contracts_settings['show_in_menu']) ? '<i class="bi bi-eye text-success"></i>' : '<i class="bi bi-eye-slash text-muted"></i>' ?>
            </small>
        </div>
    </div>

    <?php if (empty($by_client)): ?>
        <div class="alert alert-info">
            <i class="bi bi-info-circle me-1"></i> <?= __('contracts.no_contracts') ?>
        </div>
    <?php else: ?>
        <div class="card">
            <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-sm mb-0 ibok-table">
                        <thead class="table-light">
                            <tr>
                                <th><?= __('contracts.create_client_id') ?></th>
                                <th><?= __('contracts.create_client_name') ?></th>
                                <th><?= __('contracts.status_pending') ?></th>
                                <th style="width: 80px"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($by_client as $cid => $data):
                                $cname = $clients[(int)$cid]['nazwisko'] ?? '-';
                            ?>
                            <tr>
                                <td><strong><?= e(nr_klienta((int)$cid)) ?></strong></td>
                                <td><?= e($cname) ?></td>
                                <td><span class="badge bg-warning text-dark"><?= $data['pending'] ?></span></td>
                                <td>
                                    <a href="admin.php?page=contracts&v=view&cid=<?= e($cid) ?>" class="btn btn-sm btn-outline-primary" title="<?= __('contracts.btn_details') ?>">
                                        <i class="bi bi-eye"></i>
                                    </a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    <?php endif; ?>

    <?php if (!empty($signed)): ?>
    <div class="card mt-4">
        <div class="card-header">
            <i class="bi bi-check2-circle me-1 text-success"></i><?= __('contracts.signed_admin_title') ?>
            <span class="badge bg-success ms-1"><?= count($signed) ?></span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover table-sm mb-0 ibok-table">
                    <thead class="table-light">
                        <tr>
                            <th><?= __('contracts.create_client_id') ?></th>
                            <th><?= __('contracts.create_client_name') ?></th>
                            <th><?= __('contracts.contract_number') ?></th>
                            <th><?= __('contracts.signed_at_label') ?></th>
                            <th><?= __('contracts.signed_ip_label') ?></th>
                            <th style="width: 80px"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($signed as $row): $u = $row['u']; $sig = $row['sig']; $scid = $u['client_id']; ?>
                        <tr>
                            <td><strong><?= e(nr_klienta((int)$scid)) ?></strong></td>
                            <td><?= e($clients[(int)$scid]['nazwisko'] ?? '-') ?></td>
                            <td><?= e($u['numer']) ?></td>
                            <td><i class="bi bi-clock me-1 text-muted"></i><?= e($sig['signed_at'] ?? '') ?></td>
                            <td><i class="bi bi-hdd-network me-1 text-muted"></i><?= e($sig['ip'] ?? '') ?></td>
                            <td>
                                <a href="admin.php?page=contracts&v=view&cid=<?= e($scid) ?>" class="btn btn-sm btn-outline-primary" title="<?= __('contracts.btn_details') ?>">
                                    <i class="bi bi-eye"></i>
                                </a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <?php endif; ?>
</div>

<script nonce="<?= csp_nonce() ?>">
document.getElementById('showInMenuToggle').addEventListener('change', function() {
    var checked = this.checked;
    var statusEl = document.getElementById('toggleStatus');
    fetch('admin.php?page=contracts&action=toggle_menu', {
        method: 'POST',
        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
        body: 'csrf_token=<?= csrf_token() ?>&show_in_menu=' + (checked ? '1' : '0')
    }).then(function(r) { return r.json(); })
    .then(function(d) {
        if (d.success) {
            statusEl.innerHTML = checked
                ? '<i class="bi bi-eye text-success"></i>'
                : '<i class="bi bi-eye-slash text-muted"></i>';
        } else {
            alert(d.error || '<?= __('common.error') ?>');
        }
    });
});
</script>
<?php endif; ?>
