<?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 - 2FA setup page (client)
 */

require_once __DIR__ . '/../inc/totp.php';
require_once __DIR__ . '/../inc/qrcode.php';

$client_id = $_SESSION['client_id'];
$client_login = $_SESSION['client_login'] ?? '';
$twofa_type = 'client';

$msg = '';
$msg_type = 'success';
$show_backup_codes = false;
$backup_codes = [];

// Handle POST actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && csrf_validate()) {
    if (ibok_is_demo()) {
        $msg = __('demo.feature_blocked');
        $msg_type = 'warning';
    } else {
    $action = $_POST['2fa_action'] ?? '';

    if ($action === 'generate') {
        // Generate new secret and store in session for verification
        $_SESSION['2fa_setup_secret'] = totp_generate_secret();
    }

    if ($action === 'enable') {
        $code = trim($_POST['code'] ?? '');
        $secret = $_SESSION['2fa_setup_secret'] ?? '';

        if (empty($secret)) {
            $msg = __('2fa.invalid_code');
            $msg_type = 'danger';
        } elseif (totp_verify($secret, $code)) {
            // Save 2FA
            $backup_codes = twofa_generate_backup_codes();
            twofa_save($twofa_type, $client_id, [
                'secret'       => $secret,
                'enabled'      => true,
                'backup_codes' => $backup_codes,
                'created_at'   => date('Y-m-d H:i:s'),
            ]);
            unset($_SESSION['2fa_setup_secret']);
            $msg = __('2fa.enabled_success');
            $show_backup_codes = true;
            ibok_log("2FA enabled for client ID: {$client_id}", 'info');
        } else {
            $msg = __('2fa.invalid_code');
            $msg_type = 'danger';
        }
    }

    if ($action === 'disable') {
        $code = trim($_POST['code'] ?? '');
        $data = twofa_load($twofa_type, $client_id);

        if ($data && (totp_verify($data['secret'], $code) || twofa_use_backup_code($twofa_type, $client_id, $code))) {
            twofa_delete($twofa_type, $client_id);
            $msg = __('2fa.disabled_success');
            ibok_log("2FA disabled for client ID: {$client_id}", 'info');
        } else {
            $msg = __('2fa.invalid_code');
            $msg_type = 'danger';
        }
    }

    if ($action === 'regenerate') {
        $code = trim($_POST['code'] ?? '');
        $data = twofa_load($twofa_type, $client_id);

        if ($data && totp_verify($data['secret'], $code)) {
            $backup_codes = twofa_generate_backup_codes();
            $data['backup_codes'] = $backup_codes;
            twofa_save($twofa_type, $client_id, $data);
            $msg = __('2fa.codes_regenerated');
            $show_backup_codes = true;
        } else {
            $msg = __('2fa.invalid_code');
            $msg_type = 'danger';
        }
    }
    } // end else (not demo)
}

$is_enabled = twofa_is_enabled($twofa_type, $client_id);
$setup_secret = $_SESSION['2fa_setup_secret'] ?? '';
$twofa_data = twofa_load($twofa_type, $client_id);
?>

<div class="fade-in">
    <h4 class="mb-4">
        <i class="bi bi-shield-lock me-2"></i> <?= __('2fa.title') ?>
    </h4>

    <?= ibok_help_section('2fa', __('help.show_help'), __('help.2fa_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; ?>

    <?php if ($show_backup_codes && !empty($backup_codes)): ?>
        <!-- Backup codes display -->
        <div class="card border-warning mb-4">
            <div class="card-header bg-warning text-dark">
                <i class="bi bi-key me-1"></i> <?= __('2fa.backup_codes_title') ?><?= ibok_tooltip(__('help.tooltip_2fa_backup')) ?>
            </div>
            <div class="card-body">
                <p class="text-muted"><?= __('2fa.backup_codes_desc') ?></p>
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-1"></i>
                    <strong><?= __('2fa.backup_codes_warn') ?></strong>
                </div>
                <div class="row g-2 mb-3" id="backup-codes-list">
                    <?php foreach ($backup_codes as $code): ?>
                        <div class="col-6 col-md-3">
                            <code class="d-block text-center p-2 bg-light border rounded" style="font-size: 1.1rem;"><?= e($code) ?></code>
                        </div>
                    <?php endforeach; ?>
                </div>
                <button type="button" class="btn btn-outline-secondary btn-sm" id="btnCopyBackup">
                    <i class="bi bi-clipboard me-1"></i> <?= __('2fa.copy_codes') ?>
                </button>
                <script nonce="<?= csp_nonce() ?>">
                document.getElementById('btnCopyBackup').addEventListener('click', function() {
                    var btn = this;
                    var codes = [];
                    document.querySelectorAll('#backup-codes-list code').forEach(function(el) { codes.push(el.textContent.trim()); });
                    navigator.clipboard.writeText(codes.join('\n')).then(function() {
                        var orig = btn.innerHTML;
                        btn.innerHTML = '<i class="bi bi-check me-1"></i> OK';
                        setTimeout(function() { btn.innerHTML = orig; }, 1500);
                    });
                });
                </script>
            </div>
        </div>
    <?php endif; ?>

    <div class="row g-4">
        <div class="col-lg-8">
            <?php if ($is_enabled && !$show_backup_codes): ?>
                <!-- 2FA is enabled -->
                <div class="card border-success mb-4">
                    <div class="card-header bg-success text-white">
                        <i class="bi bi-shield-check me-1"></i> <?= __('2fa.status') ?>: <?= __('2fa.enabled') ?>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($twofa_data['created_at'])): ?>
                            <p class="text-muted mb-3"><?= __('2fa.created_at') ?>: <strong><?= e($twofa_data['created_at']) ?></strong></p>
                        <?php endif; ?>
                        <p class="mb-3">
                            <?= __('2fa.codes_remaining', ['count' => count($twofa_data['backup_codes'] ?? [])]) ?>
                        </p>

                        <!-- Regenerate backup codes -->
                        <form method="post" class="mb-4">
                            <?= csrf_field() ?>
                            <input type="hidden" name="2fa_action" value="regenerate">
                            <div class="input-group" style="max-width: 350px;">
                                <input type="text" name="code" class="form-control" placeholder="<?= __('2fa.enter_code') ?>"
                                       maxlength="8" autocomplete="off" inputmode="numeric">
                                <button type="submit" class="btn btn-outline-primary">
                                    <i class="bi bi-arrow-repeat me-1"></i> <?= __('2fa.regenerate_codes') ?>
                                </button>
                            </div>
                        </form>

                        <hr>

                        <!-- Disable 2FA -->
                        <p class="text-muted"><?= __('2fa.confirm_disable') ?></p>
                        <form method="post">
                            <?= csrf_field() ?>
                            <input type="hidden" name="2fa_action" value="disable">
                            <div class="input-group" style="max-width: 350px;">
                                <input type="text" name="code" class="form-control"
                                       placeholder="<?= __('2fa.enter_code') ?> <?= __('2fa.or_backup_code') ?>"
                                       maxlength="8" autocomplete="off">
                                <button type="submit" class="btn btn-outline-danger" id="btnDisable2fa"
                                        data-confirm="<?= e(__('2fa.confirm_disable')) ?>">
                                    <i class="bi bi-shield-x me-1"></i> <?= __('2fa.disable') ?>
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

            <?php elseif (!empty($setup_secret)): ?>
                <!-- Setup in progress - show QR code -->
                <div class="card mb-4">
                    <div class="card-header">
                        <i class="bi bi-gear me-1"></i> <?= __('2fa.setup_title') ?>
                    </div>
                    <div class="card-body">
                        <h6><?= __('2fa.setup_step1') ?></h6>
                        <p class="text-muted mb-4"><?= __('2fa.setup_step1_desc') ?></p>

                        <h6><?= __('2fa.setup_step2') ?></h6>
                        <p class="text-muted"><?= __('2fa.setup_step2_desc') ?></p>

                        <?php
                        $otpauth = totp_get_uri($setup_secret, $client_login);
                        $qrSvg = SimpleQR::svg($otpauth, 4, 4);
                        ?>
                        <div class="text-center my-3">
                            <div class="d-inline-block p-3 bg-white border rounded shadow-sm" data-bs-toggle="tooltip" title="<?= e(__('help.tooltip_2fa_qr')) ?>">
                                <?= $qrSvg ?>
                            </div>
                        </div>

                        <div class="mb-4">
                            <label class="form-label text-muted small text-center d-block"><?= __('2fa.manual_key') ?>:</label>
                            <div class="input-group mx-auto" style="max-width: 520px;">
                                <input type="text" class="form-control font-monospace text-center" value="<?= e($setup_secret) ?>" readonly id="secret-key">
                                <button type="button" class="btn btn-outline-secondary" id="btnCopySecret">
                                    <i class="bi bi-clipboard"></i>
                                </button>
                            </div>
                        </div>

                        <hr>

                        <h6><?= __('2fa.setup_step3') ?></h6>
                        <p class="text-muted"><?= __('2fa.setup_step3_desc') ?></p>

                        <form method="post" class="mx-auto" style="max-width: 300px;">
                            <?= csrf_field() ?>
                            <input type="hidden" name="2fa_action" value="enable">
                            <input type="text" name="code" class="form-control form-control-lg text-center font-monospace mb-2"
                                   placeholder="000000" maxlength="6" autocomplete="off"
                                   inputmode="numeric" pattern="[0-9]{6}" required autofocus>
                            <button type="submit" class="btn btn-success btn-lg w-100">
                                <i class="bi bi-check-lg me-1"></i> <?= __('2fa.verify_and_enable') ?>
                            </button>
                        </form>
                    </div>
                </div>

            <?php elseif (!$is_enabled): ?>
                <!-- 2FA not enabled -->
                <div class="card mb-4">
                    <div class="card-header">
                        <i class="bi bi-shield me-1"></i> <?= __('2fa.status') ?>: <?= __('2fa.disabled') ?>
                    </div>
                    <div class="card-body text-center py-5">
                        <div class="mb-3" style="font-size: 3rem; color: #6c757d;">
                            <i class="bi bi-shield-lock"></i>
                        </div>
                        <p class="text-muted mb-4"><?= __('2fa.security_note') ?></p>
                        <form method="post">
                            <?= csrf_field() ?>
                            <input type="hidden" name="2fa_action" value="generate">
                            <button type="submit" class="btn btn-primary btn-lg" data-bs-toggle="tooltip" title="<?= e(__('help.tooltip_2fa_toggle')) ?>">
                                <i class="bi bi-shield-plus me-1"></i> <?= __('2fa.enable') ?>
                            </button>
                        </form>
                    </div>
                </div>
            <?php endif; ?>
        </div>

        <?php if (!$show_backup_codes && !$is_enabled): ?>
        <!-- Right column - info -->
        <div class="col-lg-4">
            <div class="card">
                <div class="card-header">
                    <i class="bi bi-info-circle me-1"></i> <?= __('2fa.setup_step1') ?>
                </div>
                <div class="card-body">
                    <p class="small text-muted"><?= __('2fa.setup_step1_desc') ?></p>
                    <ul class="small text-muted mb-0">
                        <li>Google Authenticator</li>
                        <li>Microsoft Authenticator</li>
                        <li>Authy</li>
                        <li>FreeOTP</li>
                    </ul>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</div>
<script nonce="<?= csp_nonce() ?>">
(function() {
    var dis = document.getElementById('btnDisable2fa');
    if (dis) {
        dis.closest('form').addEventListener('submit', function(e) {
            if (!confirm(dis.getAttribute('data-confirm'))) e.preventDefault();
        });
    }
    var cs = document.getElementById('btnCopySecret');
    if (cs) {
        cs.addEventListener('click', function() {
            navigator.clipboard.writeText(document.getElementById('secret-key').value);
        });
    }
})();
</script>
