<?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 - Panel klienta: Umowy do podpisu (z bazy PYXIS — vUmowyLista)
 */

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

$client_id = $_SESSION['client_id'] ?? '';
$client_name = $_SESSION['nazwisko'] ?? '';

// AJAX: oznacz PDF jako pobrany (session tracking)
if (isset($_GET['action']) && $_GET['action'] === 'mark_downloaded' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');
    $um_index = (int)($_POST['um_index'] ?? 0);
    if ($um_index === 0) {
        echo json_encode(['success' => false]);
        exit;
    }
    $_SESSION['umowa_downloaded_' . $um_index] = date('Y-m-d H:i:s');
    echo json_encode(['success' => true]);
    exit;
}

$msg = '';
$msg_type = '';

// POST: podpisanie umowy
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['sign_contract'])) {
    if (ibok_is_demo()) {
        $msg = __('demo.feature_blocked');
        $msg_type = 'warning';
    } elseif (!csrf_validate()) {
        $msg = __('login.error_csrf');
        $msg_type = 'danger';
    } else {
        $um_index = (int)($_POST['um_index'] ?? 0);
        $consent1 = !empty($_POST['consent_1']);
        $consent2 = !empty($_POST['consent_2']);

        if ($um_index === 0) {
            $msg = __('contracts.error_not_found');
            $msg_type = 'danger';
        } elseif (empty($_SESSION['umowa_downloaded_' . $um_index])) {
            $msg = __('contracts.sign_locked_msg');
            $msg_type = 'danger';
        } elseif (!$consent1 || !$consent2) {
            $msg = __('contracts.error_consents_required');
            $msg_type = 'danger';
        } else {
            $result = db_podpisz_umowe($um_index, $client_id);
            if ($result) {
                $sign_ip = $_SERVER['REMOTE_ADDR'] ?? '';
                contracts_record_signature($um_index, (string)$client_id, $sign_ip);
                ibok_log("Klient #{$client_id} podpisał umowę UM_INDEX={$um_index} z IP {$sign_ip}", 'info');
                $msg = __('contracts.sign_success');
                $msg_type = 'success';
                unset($_SESSION['umowa_downloaded_' . $um_index]);
            } else {
                $msg = __('contracts.error_already_signed');
                $msg_type = 'warning';
            }
        }
    }
}

// Pobierz umowy z bazy
$pending = db_read_umowy_do_podpisu($client_id);
$all_umowy = db_read_umowy_klienta($client_id);
$signed = array_filter($all_umowy, function($u) { return $u['podpisana']; });

// Badge typów
function 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>';
}
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-file-earmark-check me-2"></i><?= __('contracts.title') ?>
    </h4>

    <?= ibok_help_section('umowy', __('help.show_help'), __('help.umowy_section_content')) ?>

    <?php if ($msg): ?>
        <div class="alert alert-<?= $msg_type ?> alert-dismissible fade show">
            <i class="bi bi-<?= $msg_type === 'success' ? 'check-circle' : 'exclamation-triangle' ?> me-1"></i>
            <?= e($msg) ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>

    <!-- Oczekujące umowy -->
    <?php if (empty($pending)): ?>
        <div class="alert alert-info">
            <i class="bi bi-info-circle me-1"></i> <?= __('contracts.no_pending') ?>
        </div>
    <?php else: ?>
        <?php foreach ($pending as $u):
            $um_idx = $u['um_index'];
            $pdf = $u['pdf_filename'];
            $is_downloaded = !empty($_SESSION['umowa_downloaded_' . $um_idx]);
            $display_name = !empty($u['tytul']) ? $u['tytul'] : $u['numer'];
        ?>
        <div class="card mb-4">
            <div class="card-header d-flex justify-content-between align-items-center">
                <span>
                    <i class="bi bi-file-earmark-text me-1"></i>
                    <strong><?= e($display_name) ?></strong>
                    <?php if (!empty($u['tytul']) && $u['tytul'] !== $u['numer']): ?>
                        <small class="text-muted ms-2">(<?= e($u['numer']) ?>)</small>
                    <?php endif; ?>
                </span>
                <span>
                    <?= umowa_type_badge($u['typ']) ?>
                    <span class="badge bg-secondary ms-1"><i class="bi bi-hourglass-split me-1"></i><?= __('contracts.status_pending') ?></span>
                </span>
            </div>
            <div class="card-body">
                <div class="row mb-3">
                    <?php if (!empty($u['data_od'])): ?>
                    <div class="col-sm-4">
                        <small class="text-muted"><?= __('contracts.contract_date_from') ?>:</small>
                        <?= format_date($u['data_od']) ?>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($u['data_do'])): ?>
                    <div class="col-sm-4">
                        <small class="text-muted"><?= __('contracts.contract_date_to') ?>:</small>
                        <?= format_date($u['data_do']) ?>
                    </div>
                    <?php endif; ?>
                </div>

                <!-- Pobierz PDF -->
                <div class="mb-3">
                    <?php if (!empty($pdf)): ?>
                    <a href="pobierz.php?id=<?= e($client_id) ?>&file=<?= urlencode($pdf) ?>" target="_blank"
                       class="btn btn-outline-primary btn-download-pdf" data-umidx="<?= $um_idx ?>">
                        <i class="bi bi-file-earmark-pdf me-1"></i> <?= __('contracts.btn_download_pdf') ?>
                    </a>
                    <?php endif; ?>
                    <?php if ($is_downloaded): ?>
                        <span class="text-success ms-2"><i class="bi bi-check-circle"></i> <?= __('contracts.pdf_downloaded') ?></span>
                    <?php endif; ?>
                    <div class="small text-muted mt-1">
                        <i class="bi bi-info-circle me-1"></i><?= __('contracts.sign_info_download') ?>
                    </div>
                </div>

                <!-- Formularz podpisu -->
                <form method="post" action="index.php?page=umowy">
                    <?= csrf_field() ?>
                    <input type="hidden" name="sign_contract" value="1">
                    <input type="hidden" name="um_index" value="<?= $um_idx ?>">

                    <!-- Hardcoded 2 checkboxy zgód -->
                    <div class="border rounded p-3 mb-3 consent-area" id="consents_<?= $um_idx ?>">
                        <div class="form-check mb-2">
                            <input class="form-check-input consent-check" type="checkbox" name="consent_1" value="1"
                                   id="consent1_<?= $um_idx ?>"
                                   data-umidx="<?= $um_idx ?>"
                                   <?= $is_downloaded ? '' : 'disabled' ?>
                                   data-required="1">
                            <label class="form-check-label" for="consent1_<?= $um_idx ?>">
                                <?= __('contracts.consent_1') ?>
                                <span class="text-danger">*</span>
                            </label>
                        </div>
                        <div class="form-check mb-2">
                            <input class="form-check-input consent-check" type="checkbox" name="consent_2" value="1"
                                   id="consent2_<?= $um_idx ?>"
                                   data-umidx="<?= $um_idx ?>"
                                   <?= $is_downloaded ? '' : 'disabled' ?>
                                   data-required="1">
                            <label class="form-check-label" for="consent2_<?= $um_idx ?>">
                                <?= __('contracts.consent_2') ?>
                                <span class="text-danger">*</span>
                            </label>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-success btn-sign" data-umidx="<?= $um_idx ?>"
                            <?= $is_downloaded ? '' : 'disabled' ?>>
                        <i class="bi bi-pen me-1"></i> <?= __('contracts.btn_sign') ?>
                    </button>
                    <?php if (!$is_downloaded): ?>
                        <small class="text-muted ms-2 sign-locked-hint"><?= __('contracts.sign_locked_msg') ?></small>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>

    <!-- Podpisane umowy -->
    <?php if (!empty($signed)): ?>
    <div class="card mt-4">
        <div class="card-header" data-bs-toggle="collapse" data-bs-target="#signedContracts" role="button">
            <i class="bi bi-check-circle me-1"></i>
            <?= __('contracts.signed_title') ?> (<?= count($signed) ?>)
            <i class="bi bi-chevron-down float-end"></i>
        </div>
        <div class="collapse" id="signedContracts">
            <div class="card-body p-0">
                <div class="table-responsive">
                <table class="table table-sm mb-0">
                    <thead class="table-light">
                        <tr>
                            <th><?= __('contracts.contract_number') ?></th>
                            <th><?= __('contracts.contract_type') ?></th>
                            <th><?= __('contracts.contract_date_from') ?><?= ibok_tooltip(__('help.tooltip_contract_dates')) ?></th>
                            <th><?= __('contracts.contract_date_to') ?></th>
                            <th>PDF<?= ibok_tooltip(__('help.tooltip_contract_pdf')) ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($signed as $u): ?>
                        <tr>
                            <td>
                                <?= e($u['numer']) ?>
                                <?php if (!empty($u['tytul'])): ?>
                                    <small class="text-muted d-block"><?= e($u['tytul']) ?></small>
                                <?php endif; ?>
                            </td>
                            <td><?= umowa_type_badge($u['typ']) ?></td>
                            <td><?= format_date($u['data_od']) ?></td>
                            <td><?= format_date($u['data_do']) ?></td>
                            <td>
                                <?php if (!empty($u['pdf_filename'])): ?>
                                <a href="pobierz.php?id=<?= e($client_id) ?>&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>
    </div>
    <?php endif; ?>
</div>

<script nonce="<?= csp_nonce() ?>">
(function() {
    // Śledź które umowy pobrano (per sesja JS) i czy AJAX się powiódł
    var downloadedMap = {};

    function unlockConsents(umIdx, btn) {
        var area = document.getElementById('consents_' + umIdx);
        if (area) {
            area.querySelectorAll('input[type=checkbox]').forEach(function(cb) {
                cb.removeAttribute('disabled');
            });
        }
        // Ukryj komunikat "najpierw pobierz"
        document.querySelectorAll('.btn-sign[data-umidx="' + umIdx + '"]').forEach(function(b) {
            var hint = b.parentElement.querySelector('.sign-locked-hint');
            if (hint) hint.style.display = 'none';
        });
        // Pokaż znacznik pobrania
        if (btn && !btn.parentElement.querySelector('.text-success')) {
            btn.insertAdjacentHTML('afterend', ' <span class="text-success ms-2"><i class="bi bi-check-circle"></i> <?= __('contracts.pdf_downloaded') ?></span>');
        }
    }

    function markDownloadedAjax(umIdx) {
        return fetch('index.php?page=umowy&action=mark_downloaded', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'um_index=' + encodeURIComponent(umIdx)
        }).then(function(r) { return r.json(); }).then(function(d) {
            if (d.success) downloadedMap[umIdx] = 'confirmed';
        }).catch(function() {
            // AJAX nie powiódł się — oznaczymy jako pending
            if (downloadedMap[umIdx] !== 'confirmed') downloadedMap[umIdx] = 'pending';
        });
    }

    // Kliknięcie "Pobierz PDF" → odblokuj natychmiast + AJAX w tle
    document.querySelectorAll('.btn-download-pdf').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            var umIdx = this.getAttribute('data-umidx');
            downloadedMap[umIdx] = 'pending';

            // Odblokuj UI natychmiast (niezależnie od AJAX)
            unlockConsents(umIdx, btn);

            // AJAX: zapisz w sesji w tle
            markDownloadedAjax(umIdx);
        });
    });

    // Walidacja: przycisk sign disabled dopóki wymagane checkboxy niezaznaczone
    document.querySelectorAll('.consent-check').forEach(function(cb) {
        cb.addEventListener('change', function() {
            var umIdx = this.getAttribute('data-umidx');
            var area = document.getElementById('consents_' + umIdx);
            var allRequired = area.querySelectorAll('[data-required="1"]');
            var allChecked = true;
            allRequired.forEach(function(r) {
                if (!r.checked) allChecked = false;
            });
            document.querySelectorAll('.btn-sign[data-umidx="' + umIdx + '"]').forEach(function(b) {
                if (allChecked) b.removeAttribute('disabled');
                else b.setAttribute('disabled', 'disabled');
            });
        });
    });

    // Przed submitem: upewnij się, że sesja ma oznaczenie pobrania
    document.querySelectorAll('form').forEach(function(form) {
        var signBtn = form.querySelector('.btn-sign');
        if (!signBtn) return;
        form.addEventListener('submit', function(e) {
            var umIdx = signBtn.getAttribute('data-umidx');
            if (downloadedMap[umIdx] === 'pending') {
                // AJAX się nie potwierdził — wyślij ponownie i poczekaj
                e.preventDefault();
                markDownloadedAjax(umIdx).then(function() {
                    form.submit();
                });
            }
        });
    });
})();
</script>
