<?php
session_start();
include('./includes/config.php');

if(empty($mobileno)){
    echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'Mobile number missing!',
                confirmButtonColor: '#d33'
            });
          </script>";
    exit;
}

// Amount fetch karna
$fetchAmount = mysqli_fetch_assoc(mysqli_query($ahk_conn, "SELECT balance FROM users WHERE phone='$mobileno'"));
$usertype = $fetchAmount['type'];
                $amount = 0;
                if($usertype == "retailer") $amount = $webdata['ret_reg_fee'];
                else if($usertype == "distributor") $amount = $webdata['dist_reg_fee'];
                else $amount = 999;

// --- QR Generation ---
$qrapiUrl = "$tng_gatewaye_url/qr_verification?apikey=$tng_gatewaye_apikey&amount=$amount";

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $qrapiUrl,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_FOLLOWLOCATION => true,
]);
echo $response = curl_exec($curl);
curl_close($curl);

$qrData = json_decode($response, true);

if ($qrData && $qrData['sampleCode'] == '200') {
    $qrImageUrl = $qrData['qr_url']; // QR ka image ya URL
    echo "<div style='text-align:center;'>
            <h4>Pay ₹$amount to activate your account</h4>
            <img src='$qrImageUrl' style='width:250px;height:250px;'><br><br>
            <input type='text' id='utr' placeholder='Enter UTR here' style='padding:10px;width:250px;'><br><br>
            <button onclick='submitUTR()' style='padding:10px 20px;'>Submit UTR</button>
          </div>";

    echo "<script>
        function submitUTR(){
            var utr = document.getElementById('utr').value;
            if(utr==''){
                Swal.fire('Error','Please enter UTR','error');
                return;
            }
            // AJAX call to same page to verify UTR
            $.post('', {utr: utr, mobileno: '$mobileno'}, function(data){
                $('body').append(data); // ye data me SweetAlert aa jaayega
            });
        }
    </script>";
} else {
    $qrError = $qrData['error'] ?? 'Unknown error during QR generation.';
    echo "<script>
            Swal.fire({
                icon: 'error',
                title: 'QR Generation Failed',
                text: '$qrError',
                confirmButtonColor: '#d33'
            });
          </script>";
}

// --- UTR Verification ---
if(!empty($_POST['utr']) && !empty($_POST['mobileno'])){
    $utr = mysqli_real_escape_string($ahk_conn,$_POST['utr']);
    $mobileno = mysqli_real_escape_string($ahk_conn,$_POST['mobileno']);

    $apiUrl = "$tng_gatewaye_url/bharatpaygateway_verification?apikey=$tng_gatewaye_apikey&utr=$utr";
    $curl = curl_init();
    curl_setopt_array($curl, [
        CURLOPT_URL => $apiUrl,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
    ]);
    $response = curl_exec($curl);
    curl_close($curl);

    $txnData = json_decode($response,true);

    if($txnData && $txnData['sampleCode']=='200'){
        // Prevent duplicate UTR
        $check = mysqli_query($ahk_conn, "SELECT * FROM wallet WHERE BANKTXNID='$utr'");
        if(mysqli_num_rows($check)>0){
            echo "<script>Swal.fire('Error','This UTR has already been used.','error');</script>";
        } else {
            $payerName = $txnData['payerName'];
            $txnAmount = $txnData['amount'];
            $datetime = date("Y-m-d H:i:s");

            // Insert txn for record keeping (optional)
            mysqli_query($ahk_conn, "INSERT INTO wallet (phone,BANKTXNID,amount,RESPMSG,PAYMENTMODE,status,txn_date)
                VALUES('$mobileno','$utr','$txnAmount','$payerName','UPI','success','$datetime')");

            // Update only status = 1
            mysqli_query($ahk_conn, "UPDATE users SET status='1' WHERE phone='$mobileno'");

            echo "<script>
                Swal.fire({
                    icon:'success',
                    title:'Payment Successful!',
                    html:'Your account is now activated!<br>UTR: $utr<br>Payer: $payerName',
                    confirmButtonColor:'#3085d6',
                    confirmButtonText:'Login Now'
                }).then((result)=>{
                    if(result.isConfirmed){
                        window.location.href='login.php';
                    }
                });
            </script>";
        }
    } else {
        $utrError = $txnData['error'] ?? 'Unknown error during UTR verification.';
        echo "<script>Swal.fire('Error','UTR Verification Failed: $utrError','error');</script>";
    }
}
?>
