<?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 - Konfiguracja bramek płatniczych (admin)
 */

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

// Obsługa AJAX
if (isset($_GET['action'])) {
    header('Content-Type: application/json; charset=utf-8');

    $action = $_GET['action'];

    // GET config
    if (preg_match('/^get_(tpay|p24|payu)$/', $action, $m)) {
        $cfg = payment_load_config($m[1]);
        echo json_encode(['success' => true, 'config' => $cfg]);
        exit;
    }

    // SAVE config
    if (preg_match('/^save_(tpay|p24|payu)$/', $action, $m)) {
        if (ibok_is_demo()) {
            echo json_encode(['success' => false, 'message' => __('demo.save_blocked')]);
            exit;
        }
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            echo json_encode(['success' => false, 'message' => 'POST required']);
            exit;
        }
        if (!csrf_validate()) {
            echo json_encode(['success' => false, 'message' => __('login.error_csrf')]);
            exit;
        }

        $gw = $m[1];
        $input = json_decode(file_get_contents('php://input'), true);
        if (!is_array($input)) {
            $input = $_POST;
        }

        $cfg = payment_load_config($gw);

        // Common fields
        $cfg['enabled'] = !empty($input['enabled']);
        $cfg['test_mode'] = !empty($input['test_mode']);
        $cfg['notification_url'] = trim($input['notification_url'] ?? '');
        $cfg['return_url'] = trim($input['return_url'] ?? '');
        $cfg['description_template'] = trim($input['description_template'] ?? $cfg['description_template']);
        $cfg['terms_url'] = trim($input['terms_url'] ?? ($cfg['terms_url'] ?? ''));

        // Gateway-specific fields
        switch ($gw) {
            case 'tpay':
                $cfg['merchant_id'] = trim($input['merchant_id'] ?? '');
                $cfg['security_code'] = trim($input['security_code'] ?? '');
                break;
            case 'p24':
                $cfg['merchant_id'] = trim($input['merchant_id'] ?? '');
                $cfg['pos_id'] = trim($input['pos_id'] ?? '');
                $cfg['crc_key'] = trim($input['crc_key'] ?? '');
                $cfg['api_key'] = trim($input['api_key'] ?? '');
                break;
            case 'payu':
                $cfg['pos_id'] = trim($input['pos_id'] ?? '');
                $cfg['md5_key'] = trim($input['md5_key'] ?? '');
                $cfg['client_id'] = trim($input['client_id'] ?? '');
                $cfg['client_secret'] = trim($input['client_secret'] ?? '');
                break;
        }

        if (payment_save_config($gw, $cfg)) {
            ibok_log("Admin: zapisano konfigurację bramki {$gw}", 'info');
            echo json_encode(['success' => true, 'message' => __('payment_admin.saved')]);
        } else {
            echo json_encode(['success' => false, 'message' => __('payment_admin.error_save')]);
        }
        exit;
    }

    // GET history
    if ($action === 'get_history') {
        $sessions = payment_get_completed_sessions(200);
        echo json_encode(['success' => true, 'sessions' => $sessions]);
        exit;
    }

    // GET logs
    if ($action === 'get_logs') {
        $logs = payment_get_log_files();
        $entries = [];
        // Read most recent log
        if (!empty($logs)) {
            $entries = payment_read_log($logs[0]['name']);
        }
        echo json_encode(['success' => true, 'logs' => $logs, 'entries' => array_slice($entries, 0, 200)]);
        exit;
    }

    echo json_encode(['success' => false, 'message' => 'Unknown action']);
    exit;
}

// Wczytaj aktualne konfiguracje
$cfg_tpay = payment_load_config('tpay');
$cfg_p24 = payment_load_config('p24');
$cfg_payu = payment_load_config('payu');
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-credit-card me-2"></i> <?= __('payment_admin.title') ?>
        <small class="text-muted ms-2"><?= __('payment_admin.subtitle') ?></small>
    </h4>

    <?= ibok_help_section('admin_platnosci', __('help.show_help'), __('help_admin.platnosci_section_content')) ?>

    <div id="paymentAlert" class="alert d-none" role="alert"></div>

    <ul class="nav nav-tabs mb-4" id="paymentTabs" role="tablist">
        <li class="nav-item">
            <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tab-tpay" type="button">
                <i class="bi bi-wallet2 me-1"></i> <?= __('payment_admin.tab_tpay') ?>
                <?php if (!empty($cfg_tpay['enabled'])): ?>
                    <span class="badge bg-success ms-1"><?= __('payment_admin.enabled') ?></span>
                <?php endif; ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-p24" type="button">
                <i class="bi bi-wallet2 me-1"></i> <?= __('payment_admin.tab_p24') ?>
                <?php if (!empty($cfg_p24['enabled'])): ?>
                    <span class="badge bg-success ms-1"><?= __('payment_admin.enabled') ?></span>
                <?php endif; ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-payu" type="button">
                <i class="bi bi-wallet2 me-1"></i> <?= __('payment_admin.tab_payu') ?>
                <?php if (!empty($cfg_payu['enabled'])): ?>
                    <span class="badge bg-success ms-1"><?= __('payment_admin.enabled') ?></span>
                <?php endif; ?>
            </button>
        </li>
        <li class="nav-item">
            <button class="nav-link" data-bs-toggle="tab" data-bs-target="#tab-history" type="button">
                <i class="bi bi-clock-history me-1"></i> <?= __('payment_admin.tab_history') ?>
            </button>
        </li>
    </ul>

    <div class="tab-content">
        <!-- Tpay -->
        <div class="tab-pane fade show active" id="tab-tpay">
            <div class="card">
                <div class="card-body">
                    <form id="formTpay" data-gateway="tpay">
                        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="tpay_enabled" <?= !empty($cfg_tpay['enabled']) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="tpay_enabled"><?= __('payment_admin.enabled') ?></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="tpay_test_mode" <?= !empty($cfg_tpay['test_mode']) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="tpay_test_mode"><?= __('payment_admin.test_mode') ?></label>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.merchant_id') ?></label>
                                <input type="text" class="form-control" id="tpay_merchant_id" value="<?= e($cfg_tpay['merchant_id']) ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.security_code') ?></label>
                                <input type="text" class="form-control" id="tpay_security_code" value="<?= e($cfg_tpay['security_code']) ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.notification_url') ?></label>
                            <input type="text" class="form-control" id="tpay_notification_url" value="<?= e($cfg_tpay['notification_url']) ?>"
                                   placeholder="https://twoja-domena.pl/ibok5/payment_callback.php?gateway=tpay">
                            <small class="form-text text-muted"><?= __('payment_admin.urls_info') ?></small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.return_url') ?></label>
                            <input type="text" class="form-control" id="tpay_return_url" value="<?= e($cfg_tpay['return_url']) ?>"
                                   placeholder="https://twoja-domena.pl/ibok5/payment_return.php">
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.description_template') ?></label>
                            <input type="text" class="form-control" id="tpay_description_template" value="<?= e($cfg_tpay['description_template']) ?>">
                            <small class="form-text text-muted"><?= __('payment_admin.description_help') ?></small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.terms_url') ?></label>
                            <input type="url" class="form-control" id="tpay_terms_url" value="<?= e($cfg_tpay['terms_url'] ?? '') ?>" placeholder="https://...">
                            <small class="form-text text-muted"><?= __('payment_admin.terms_url_help') ?></small>
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-1"></i> <?= __('payment_admin.btn_save') ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Przelewy24 -->
        <div class="tab-pane fade" id="tab-p24">
            <div class="card">
                <div class="card-body">
                    <form id="formP24" data-gateway="p24">
                        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="p24_enabled" <?= !empty($cfg_p24['enabled']) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="p24_enabled"><?= __('payment_admin.enabled') ?></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="p24_test_mode" <?= !empty($cfg_p24['test_mode']) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="p24_test_mode"><?= __('payment_admin.test_mode') ?></label>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.merchant_id') ?></label>
                                <input type="text" class="form-control" id="p24_merchant_id" value="<?= e($cfg_p24['merchant_id']) ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.pos_id') ?></label>
                                <input type="text" class="form-control" id="p24_pos_id" value="<?= e($cfg_p24['pos_id']) ?>">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.crc_key') ?></label>
                                <input type="text" class="form-control" id="p24_crc_key" value="<?= e($cfg_p24['crc_key']) ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.api_key') ?></label>
                                <input type="text" class="form-control" id="p24_api_key" value="<?= e($cfg_p24['api_key']) ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.notification_url') ?></label>
                            <input type="text" class="form-control" id="p24_notification_url" value="<?= e($cfg_p24['notification_url']) ?>"
                                   placeholder="https://twoja-domena.pl/ibok5/payment_callback.php?gateway=p24">
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.return_url') ?></label>
                            <input type="text" class="form-control" id="p24_return_url" value="<?= e($cfg_p24['return_url']) ?>"
                                   placeholder="https://twoja-domena.pl/ibok5/payment_return.php">
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.description_template') ?></label>
                            <input type="text" class="form-control" id="p24_description_template" value="<?= e($cfg_p24['description_template']) ?>">
                            <small class="form-text text-muted"><?= __('payment_admin.description_help') ?></small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.terms_url') ?></label>
                            <input type="url" class="form-control" id="p24_terms_url" value="<?= e($cfg_p24['terms_url'] ?? '') ?>" placeholder="https://...">
                            <small class="form-text text-muted"><?= __('payment_admin.terms_url_help') ?></small>
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-1"></i> <?= __('payment_admin.btn_save') ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- PayU -->
        <div class="tab-pane fade" id="tab-payu">
            <div class="card">
                <div class="card-body">
                    <form id="formPayu" data-gateway="payu">
                        <input type="hidden" name="csrf_token" value="<?= csrf_token() ?>">

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="payu_enabled" <?= !empty($cfg_payu['enabled']) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="payu_enabled"><?= __('payment_admin.enabled') ?></label>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-check form-switch mb-3">
                                    <input class="form-check-input" type="checkbox" id="payu_test_mode" <?= !empty($cfg_payu['test_mode']) ? 'checked' : '' ?>>
                                    <label class="form-check-label" for="payu_test_mode"><?= __('payment_admin.test_mode') ?></label>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.pos_id') ?></label>
                                <input type="text" class="form-control" id="payu_pos_id" value="<?= e($cfg_payu['pos_id']) ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.md5_key') ?></label>
                                <input type="text" class="form-control" id="payu_md5_key" value="<?= e($cfg_payu['md5_key']) ?>">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.client_id') ?></label>
                                <input type="text" class="form-control" id="payu_client_id" value="<?= e($cfg_payu['client_id']) ?>">
                            </div>
                            <div class="col-md-6">
                                <label class="form-label"><?= __('payment_admin.client_secret') ?></label>
                                <input type="text" class="form-control" id="payu_client_secret" value="<?= e($cfg_payu['client_secret']) ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.notification_url') ?></label>
                            <input type="text" class="form-control" id="payu_notification_url" value="<?= e($cfg_payu['notification_url']) ?>"
                                   placeholder="https://twoja-domena.pl/ibok5/payment_callback.php?gateway=payu">
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.return_url') ?></label>
                            <input type="text" class="form-control" id="payu_return_url" value="<?= e($cfg_payu['return_url']) ?>"
                                   placeholder="https://twoja-domena.pl/ibok5/payment_return.php">
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.description_template') ?></label>
                            <input type="text" class="form-control" id="payu_description_template" value="<?= e($cfg_payu['description_template']) ?>">
                            <small class="form-text text-muted"><?= __('payment_admin.description_help') ?></small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><?= __('payment_admin.terms_url') ?></label>
                            <input type="url" class="form-control" id="payu_terms_url" value="<?= e($cfg_payu['terms_url'] ?? '') ?>" placeholder="https://...">
                            <small class="form-text text-muted"><?= __('payment_admin.terms_url_help') ?></small>
                        </div>

                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-check-lg me-1"></i> <?= __('payment_admin.btn_save') ?>
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Historia -->
        <div class="tab-pane fade" id="tab-history">
            <div class="card">
                <div class="card-body">
                    <h6 class="mb-3"><i class="bi bi-clock-history me-1"></i> <?= __('payment_admin.history_title') ?></h6>
                    <div id="historyContent">
                        <p class="text-muted"><?= __('common.loading') ?></p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script nonce="<?= csp_nonce() ?>">
var PAYMENT_LANG = {
    saved: '<?= __('payment_admin.saved') ?>',
    error_save: '<?= __('payment_admin.error_save') ?>',
    history_empty: '<?= __('payment_admin.history_empty') ?>',
    no_logs: '<?= __('payment_admin.no_logs') ?>',
    status_completed: '<?= __('payment_admin.status_completed') ?>',
    status_pending: '<?= __('payment_admin.status_pending') ?>',
    status_failed: '<?= __('payment_admin.status_failed') ?>'
};

document.querySelectorAll('[data-gateway]').forEach(function(form) {
    form.addEventListener('submit', function(e) {
        e.preventDefault();
        saveGateway(this.getAttribute('data-gateway'));
    });
});

function saveGateway(gw) {
    var data = {
        csrf_token: '<?= csrf_token() ?>',
        enabled: document.getElementById(gw + '_enabled').checked ? '1' : '',
        test_mode: document.getElementById(gw + '_test_mode').checked ? '1' : '',
        notification_url: document.getElementById(gw + '_notification_url').value,
        return_url: document.getElementById(gw + '_return_url').value,
        description_template: document.getElementById(gw + '_description_template').value,
        terms_url: document.getElementById(gw + '_terms_url').value
    };

    // Gateway-specific fields
    if (gw === 'tpay') {
        data.merchant_id = document.getElementById('tpay_merchant_id').value;
        data.security_code = document.getElementById('tpay_security_code').value;
    } else if (gw === 'p24') {
        data.merchant_id = document.getElementById('p24_merchant_id').value;
        data.pos_id = document.getElementById('p24_pos_id').value;
        data.crc_key = document.getElementById('p24_crc_key').value;
        data.api_key = document.getElementById('p24_api_key').value;
    } else if (gw === 'payu') {
        data.pos_id = document.getElementById('payu_pos_id').value;
        data.md5_key = document.getElementById('payu_md5_key').value;
        data.client_id = document.getElementById('payu_client_id').value;
        data.client_secret = document.getElementById('payu_client_secret').value;
    }

    $.ajax({
        url: 'admin.php?page=platnosci&action=save_' + gw,
        method: 'POST',
        data: data,
        dataType: 'json',
        success: function(resp) {
            showAlert(resp.success ? 'success' : 'danger', resp.message);
        },
        error: function() {
            showAlert('danger', PAYMENT_LANG.error_save);
        }
    });
    return false;
}

function showAlert(type, msg) {
    var el = document.getElementById('paymentAlert');
    el.className = 'alert alert-' + type;
    el.textContent = msg;
    el.classList.remove('d-none');
    setTimeout(function() { el.classList.add('d-none'); }, 5000);
}

// Load history when tab is shown
document.querySelector('[data-bs-target="#tab-history"]').addEventListener('shown.bs.tab', function() {
    loadHistory();
});

function escHtml(str) {
    if (!str) return '';
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(String(str)));
    return div.innerHTML;
}

function loadHistory() {
    $.getJSON('admin.php?page=platnosci&action=get_history', function(resp) {
        if (!resp.success || !resp.sessions || resp.sessions.length === 0) {
            $('#historyContent').html('<p class="text-muted">' + PAYMENT_LANG.history_empty + '</p>');
            return;
        }
        var html = '<div class="table-responsive"><table class="table table-sm table-hover"><thead><tr>' +
            '<th><?= __('payment_admin.history_date') ?></th>' +
            '<th><?= __('payment_admin.history_gateway') ?></th>' +
            '<th><?= __('payment_admin.history_client') ?></th>' +
            '<th><?= __('payment_admin.history_invoice') ?></th>' +
            '<th><?= __('payment_admin.history_amount') ?></th>' +
            '<th><?= __('payment_admin.history_status') ?></th>' +
            '</tr></thead><tbody>';

        resp.sessions.forEach(function(s) {
            var date = s.created ? new Date(s.created * 1000).toLocaleString() : '';
            var statusBadge = s.status === 'completed'
                ? '<span class="badge bg-success">' + PAYMENT_LANG.status_completed + '</span>'
                : (s.status === 'failed'
                    ? '<span class="badge bg-danger">' + PAYMENT_LANG.status_failed + '</span>'
                    : '<span class="badge bg-warning">' + PAYMENT_LANG.status_pending + '</span>');

            html += '<tr><td>' + escHtml(date) + '</td><td>' + escHtml(s.gateway) +
                '</td><td>' + escHtml(s.client_id) +
                '</td><td>' + escHtml(s.invoice_nr) +
                '</td><td>' + (s.amount ? escHtml(s.amount.toFixed(2)) + ' zł' : '') +
                '</td><td>' + statusBadge + '</td></tr>';
        });
        html += '</tbody></table></div>';
        $('#historyContent').html(html);
    });
}
</script>
