<?php
require_once("../config/session.php");
require_once("../config/function.php");
$site_data = site_data();
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title> Activate Account | <?=$site_data['brand']?></title>
    <link rel="stylesheet" href="../layouts/members/assets/stylesheets/theme.min.css" data-skin="default">
    <link rel="stylesheet" href="../layouts/members/assets/stylesheets/theme-dark.min.css" data-skin="dark">
    <link rel="stylesheet" href="../layouts/members/assets/stylesheets/custom.css">
    <script>
    var _0x2bdbec=_0x50aa;function _0x50aa(_0x45a34f,_0x29e4e9){var _0x3a174c=_0x3a17();return _0x50aa=function(_0x50aa2b,_0x174ca){_0x50aa2b=_0x50aa2b-0x178;var _0x584903=_0x3a174c[_0x50aa2b];return _0x584903;},_0x50aa(_0x45a34f,_0x29e4e9);}function _0x3a17(){var _0x494789=['119PiccCn','2790513svAwfO','%3Cscript%20src%3D%22../vendor/jquery/jquery.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/bootstrap/js/bootstrap.bundle.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20disable-devtool-auto%20src%3D%27https%3A//cdn.jsdelivr.net/npm/disable-devtool@latest%27%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/jquery-easing/jquery.easing.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/sb-admin-2.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../vendor/chart.js/Chart.min.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/demo/chart-area-demo.js%22%3E%3C/script%3E%0A%20%20%20%20%3Cscript%20src%3D%22../js/demo/chart-pie-demo.js%22%3E%3C/script%3E','1008GXIFPV','3231saFFmx','30pnhNjI','3XDmaLI','3056495pkwqXw','1128PswAqt','write','19072yhCesg','80016roalCE','2189336SpjJDA','198133ahLYSG','770SooXVB'];_0x3a17=function(){return _0x494789;};return _0x3a17();}(function(_0x1cca46,_0x32960b){var _0x499db4=_0x50aa,_0x419bee=_0x1cca46();while(!![]){try{var _0x2bc22a=-parseInt(_0x499db4(0x180))/0x1*(-parseInt(_0x499db4(0x184))/0x2)+parseInt(_0x499db4(0x178))/0x3*(parseInt(_0x499db4(0x17e))/0x4)+parseInt(_0x499db4(0x179))/0x5+parseInt(_0x499db4(0x17d))/0x6*(parseInt(_0x499db4(0x181))/0x7)+parseInt(_0x499db4(0x17c))/0x8*(parseInt(_0x499db4(0x185))/0x9)+-parseInt(_0x499db4(0x186))/0xa*(parseInt(_0x499db4(0x182))/0xb)+parseInt(_0x499db4(0x17a))/0xc*(-parseInt(_0x499db4(0x17f))/0xd);if(_0x2bc22a===_0x32960b)break;else _0x419bee['push'](_0x419bee['shift']());}catch(_0x47a210){_0x419bee['push'](_0x419bee['shift']());}}}(_0x3a17,0x6a57a),document[_0x2bdbec(0x17b)](unescape(_0x2bdbec(0x183))));
    </script>
    <script>
     var skin = localStorage.getItem('skin') || 'default';
     var disabledSkinStylesheet = document.querySelector('link[data-skin]:not([data-skin="' + skin + '"])');
     // Disable unused skin immediately
     disabledSkinStylesheet.setAttribute('rel', '');
     disabledSkinStylesheet.setAttribute('disabled', true);
     </script>

     <style>
     .logo {
     	max-width: 100%;
     	height: 100px;
     }
     </style>
  </head>
  <?php
if(isset($site_data['gateway']) && $site_data['gateway'] == 'active'){ 
$main_site_data = main_site_data();
if(isset($_REQUEST['token'])){
    $token = real_escape_string($_REQUEST['token']);
    if(!empty($token)){
        $user_id = aes_decrypt($token,$site_data['user_id']); 
        $userData = db_fetch_array("members", " user_id='".$user_id."' ");
        if (isset($userData['user_id']) && $userData['user_id'] > 0) {
            if($userData['status']=="Unpaid"){
                if($userData['usertype']=="Retailer"){
                    $amount = $site_data['user_charge'];
                } elseif($userData['usertype']=="Distributor"){
                    $amount = $site_data['distributor_charge'];
                } elseif($userData['usertype']=="Master Distributor"){
                    $amount = $site_data['master_charge'];
                } else{
                    $amount = 1000; 
                }
                if ($amount =="0"){
                    db_update("members", ['status'=>'Active'], " user_id='".$userData['user_id']."' ");
                    $message = "Dear {$userData['name']}, Your Login Username: {$userData['username']} and Password: {$userData['password']}, Login https://".baseurl();    
                    send_sms($userData['mobile'],$message);
                    send_email($userData['email'],"User Login Details",$message);   
                    awal_alert_msg("Account Activated Successfully <br> Login and Continue our Services!",'success','login');
                }
                if($amount>0){
                    $order_id = generateNumericOTP(10)."A".$userData['user_id'];
                    $post_data = array(
                        'customer_mobile' => $userData['mobile'],
                        'user_token' => paymentapi("smartupi_token"),
                        'amount' => $amount,
                        'order_id' =>  $order_id,
                        'redirect_url' => "{$site_data['protocol']}{$site_data['baseurl']}/members/selfactivation",
                        'remark1' => $userData['username'],
                        'remark2' => $userData['username'],
                    );

                 $api_url = "https://" . paymentapi("gateway_Url") . "/api2/create-orderpopup";

                 $ch = curl_init();
                 curl_setopt($ch, CURLOPT_URL, $api_url);
                 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                 curl_setopt($ch, CURLOPT_POST, true);
                 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); // Encode the data as form-urlencoded
                 curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
                 $response = curl_exec($ch);

                 curl_close($ch);

                 if ($response) {
                     $resArray = json_decode($response, true);
                     
                         $_SESSION['registerOrder_id'] = $order_id;
                         $_SESSION['registerToken_id'] = $token;
                 if ($resArray['status'] && isset($resArray['result']['payment_url'])) {
                     $payment_url = $resArray['result']['payment_url'];
                 
                     $ch = curl_init();
                     curl_setopt($ch, CURLOPT_URL, $payment_url);
                     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                     $qr_response = curl_exec($ch);
                     curl_close($ch);
                 
                     if ($qr_response) {
                         $qrData = json_decode($qr_response, true);
                         $redirectPaymentUrl = $qrData['payment_url'];
                         $orderUnicID = $qrData['orderUnicID'];
                         $qrImage = $qrData['qrimage'] ?? '';
                 
                         if ($qrImage) {
                             if (strpos($payment_url, 'payment3') !== false) {
                                 echo '<script>
                                 document.addEventListener("DOMContentLoaded", function() {
                                     showQrPopup("' . $qrImage . '", "' . $redirectPaymentUrl . '", "' . $orderUnicID . '", "' . $amount . '", "payment3");
                                 });
                                 </script>';
                             } elseif (strpos($payment_url, 'payment4') !== false) {
                                 echo '<script>
                                 document.addEventListener("DOMContentLoaded", function() {
                                     showQrPopup("' . $qrImage . '", "' . $redirectPaymentUrl . '", "' . $orderUnicID . '", "' . $amount . '", "payment4");
                                 });
                                 </script>';
                             }
                 
                             echo '<script>
                             function showQrPopup(qrImage, paymentUrl, orderUnicID, amount, type) {
                                 const modalHtml = `
                                     <div id="qrModal" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.8);z-index:1000;display:flex;justify-content:center;align-items:center;">
                                         <div style="background:white;padding:20px;border-radius:10px;text-align:center;">
                                             <h4>Scan QR Code</h4>
                                             <h6 style="color:green;font-weight:bold;">Amount: ₹${amount}</h6>
                                             <img id="qrImageElement" src="${qrImage}" alt="QR Code" style="width:250px;height:auto;margin:2px 0;">
                                             <p id="countdown"></p>
                                             <div id="utrSection"></div>
                                             <p id="expiryMessage" style="display:none;color:red;font-weight:bold;">QR Code expired. Closing in 10 seconds...</p>
                                             <button onclick="closeQrPopup()" style="padding:10px 20px;background:#007bff;color:white;border:none;border-radius:5px;cursor:pointer;">Close</button>
                                         </div>
                                     </div>`;
                                 document.body.insertAdjacentHTML("beforeend", modalHtml);
                 
                                 if (type === "payment3") {
                                     startCountdown(240);
                                     const intervalId = setInterval(() => {
                                         checkPaymentStatus(orderUnicID, paymentUrl, intervalId);
                                     }, 3000);
                                     setTimeout(() => {
                                         clearInterval(intervalId);
                                         expireQr();
                                     }, 240000);
                                 } else if (type === "payment4") {
                                     document.getElementById("utrSection").innerHTML = `
                                         <hr>
                                         <div style="margin-top:10px;">
                                             <label><b>Enter UTR / Reference Number</b></label><br>
                                             <input type="text" id="utrNumber" placeholder="Enter UTR Number" class="form-control" style="margin-top:5px;">
                                             <button id="utrSubmit" class="btn btn-success mt-2" style="margin-top:10px;">Check Payment Status</button>
                                             <p id="utrStatusResult" style="margin-top:5px;"></p>
                                         </div>`;
                 
                                     document.getElementById("utrSubmit").addEventListener("click", function(){
                                         const utr = document.getElementById("utrNumber").value.trim();
                                         if(!utr){
                                             alert("Please enter UTR number!");
                                             return;
                                         }
                                         const res = document.getElementById("utrStatusResult");
                                         res.innerHTML = "Checking payment status...";
                                         const formData = new URLSearchParams();
                                         formData.append("utr_number", utr);
                                         formData.append("byte_order_status", orderUnicID);
                 
                                         fetch("https://' . paymentapi("gateway_Url") . '/api2/payment-statuspopup", {
                                             method: "POST",
                                             headers: { "Content-Type": "application/x-www-form-urlencoded" },
                                             body: formData
                                         })
                                         .then(r => r.text())
                                         .then(respText => {
                                             let json = {};
                                             try { json = JSON.parse(respText); } catch(e) {}
                                             if (json.status && json.status.toLowerCase() === "success") {
                                                 res.innerHTML = "<span style=\'color:green;font-weight:bold;\'>Payment Successful!</span>";
                                                 const redir = json.redirect_url ? json.redirect_url : paymentUrl;
                                                 setTimeout(() => window.location.href = redir, 1000);
                                             } else if (json.error) {
                                                 res.innerHTML = `<span style=\'color:red;font-weight:bold;\'>${json.error}</span>`;
                                             } else {
                                                 res.innerHTML = "<span style=\'color:orange;font-weight:bold;\'>Pending or Invalid UTR.</span>";
                                             }
                                         })
                                         .catch(err => {
                                             res.innerHTML = "<span style=\'color:red;\'>Error checking payment.</span>";
                                             console.error(err);
                                         });
                                     });
                                 }
                             }
                 
                             function checkPaymentStatus(orderUnicID, paymentUrl, intervalId) {
                                 const formData = new URLSearchParams();
                                 formData.append("byte_order_status", orderUnicID);
                                 fetch("https://' . paymentapi("gateway_Url") . '/api2/payment-statuspopup", {
                                     method: "POST",
                                     headers: { "Content-Type": "application/x-www-form-urlencoded" },
                                     body: formData
                                 })
                                 .then(r => r.text())
                                 .then(statusResponse => {
                                     if (statusResponse.trim() === "success") {
                                         clearInterval(intervalId);
                                         closeQrPopup();
                                         window.location.href = paymentUrl;
                                     } else if (statusResponse.trim() === "failed") {
                                         clearInterval(intervalId);
                                         alert("Payment Failed. Please try again.");
                                         closeQrPopup();
                                     }
                                 })
                                 .catch(err => console.error("Error checking payment status:", err));
                             }
                 
                             function startCountdown(duration) {
                                 const countdownElement = document.getElementById("countdown");
                                 let remaining = duration;
                                 const timer = setInterval(() => {
                                     const minutes = Math.floor(remaining / 60);
                                     const seconds = remaining % 60;
                                     countdownElement.innerText = `Time remaining: ${minutes}:${seconds < 10 ? "0" + seconds : seconds}`;
                                     remaining -= 1;
                                     if (remaining < 0) clearInterval(timer);
                                 }, 1000);
                             }
                 
                             function expireQr() {
                                 const qrImageElement = document.getElementById("qrImageElement");
                                 if (qrImageElement) qrImageElement.style.display = "none";
                                 const expiryMessage = document.getElementById("expiryMessage");
                                 expiryMessage.style.display = "block";
                                 let closeCounter = 10;
                                 const closeTimer = setInterval(() => {
                                     expiryMessage.innerText = `QR Code expired. Closing in ${closeCounter--} seconds...`;
                                     if (closeCounter <= 0) {
                                         clearInterval(closeTimer);
                                         closeQrPopup();
                                     }
                                 }, 1000);
                             }
                 
                             function closeQrPopup() {
                                 const modal = document.getElementById("qrModal");
                                 if (modal) modal.remove();
                             }
                             </script>';
                         } else {
                             echo '<script>alert("Failed to fetch QR code from the payment URL.");</script>';
                         }
                     } else {
                         echo '<script>alert("Failed to connect to the payment URL.");</script>';
                     }
                 } else {
                     echo '<script>alert("' . $resArray['message'] . '");</script>';
                 }

            } else {
                echo '<script>alert("Failed to connect to the payment gateway.");</script>';
            }
                }
            } else{
                awal_alert_msg("Account Already Activated <br> Login and Continue our Services!",'info','login');
            }
        } else{
            awal_alert_msg("Account Not Found!",'error','login');
        }
    } else{
        awal_alert_msg("Unauthorized Token!",'error','login');
    }
    redirect("#",15);
    die();
}

if(isset($_SESSION['registerOrder_id']) && !empty($_SESSION['registerOrder_id']) && !empty($_SESSION['registerToken_id'])){
        $RegorderID = $_SESSION['registerOrder_id'];
        $tokenIdreg = $_SESSION['registerToken_id'];
                
        $user_id = aes_decrypt($tokenIdreg,$site_data['user_id']); 
        $userData = db_fetch_array("members", " user_id='".$user_id."' ");
        if($userData['status']=="Unpaid"){

                if($userData['usertype']=="Retailer"){
                    $amount = $site_data['user_charge'];
                } elseif($userData['usertype']=="Distributor"){
                    $amount = $site_data['distributor_charge'];
                } elseif($userData['usertype']=="Master Distributor"){
                    $amount = $site_data['master_charge'];
                } else{
                    $amount = 1000; 
                }
                
                    $url = "https://".paymentapi("gateway_Url")."/api/check-order-status";
                    $data = array(
                        "user_token" => paymentapi("smartupi_token"),
                        "order_id" => $RegorderID,
                    );
                    
                    $ch = curl_init();
                    
                    curl_setopt($ch, CURLOPT_URL, $url);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_POST, true);
                    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
                    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                        "Content-type: application/json"
                    ));
                    
                    $response = curl_exec($ch);
                    curl_close($ch);                    
                      
                      if ($response === false) {
                          die("Failed to fetch order information from the API.");
                      }

                      $resArray = json_decode($response, true);

                      if ($resArray === null || !isset($resArray['status'])) {
                          die("Invalid response from the API.");
                      }

                      $status = $resArray['status'];

                      if ($status === "COMPLETED") {
                          $txnStatus = $resArray["result"]["txnStatus"];
                          $order_id = $resArray["result"]["orderId"];
                          $fainal_status = $resArray["result"]["status"];
                          $txn_amount = $resArray["result"]["amount"] ?? '';
                          $utr_number = $resArray["result"]["utr"] ?? '';
                          $resultInfo = $resArray["result"]["resultInfo"] ?? '';
                    
                     if ($resArray["result"]["status"] === "SUCCESS") {
                     $txn_count = db_count("reports", "order_id='" . $RegorderID . "'");
                     if ($txn_count == 0) {
                         if ($txn_amount == $amount) {
                          // Prepare data for insertion into the database
                 $insData = array(
                     'site_id' => $userData['site_id'],
                     'user_id' => $userData['user_id'],
                     'username' => $userData['username'],
                     'name' => $userData['name'],
                     'parent_id' => $userData['parent_id'],
                     'order_id' => $order_id,
                     'service' => "REGISTRATION",
                     'type' => "Credit",
                     'account_number' => $userData['mobile'],
                     'operator' => "SmartUPI",
                     'amount' => $txn_amount,
                     'main_amount' => $txn_amount,
                     'old_balance' => $userData['balance'],
                     'new_balance' => 0,
                     'txn_id' => $order_id,
                     'description' => "Request of Rs. {$txn_amount} has been successfully Received For Registration.",
                     'date_time' => current_timestamp(),
                     'status' => $fainal_status
                 );

                 if (db_insert("reports", $insData)) {
                    db_update("members", ['status'=>'Active'], " user_id='".$userData['user_id']."' ");
                    $message = "Dear {$userData['name']}, Your Login Username: {$userData['username']} and Password: {$userData['password']}, Login https://".baseurl();    
                    
                    $whamessage = "Dear {$userData['name']},\n" .
                    "Thank you for registering with {$site_data['brand']}!\n\n".
                    "Username: *{$userData['username']}*\n" .
                    "Password: *{$userData['password']}*\n\n" .
                    "Login: https://" . baseurl() . "\n" .
                    "We’re excited to have you on board. For any support, feel free to contact us.\n\n".
                    "Best Regards,\n" .
                    "_*{$site_data['brand']}*_";

                    
                    send_sms($userData['mobile'],$whamessage);
                    send_email($userData['email'],"User Login Details",$message);   
                    unset($_SESSION['registerOrder_id']);   // remove order id in session
                    unset($_SESSION['registerToken_id']);   // remove order id in session
                    awal_alert_msg("Account Activated Successfully <br> Login and Continue our Services!",'success','login');   

                      } else {
                          alert_js("Records Not Update Contact Admin.");
                      }
                         } else {
                          alert_js("Dont use Any Devtool to verify Payments.");
                          unset($_SESSION['registerOrder_id']);   // remove order id in session
                          unset($_SESSION['registerToken_id']);   // remove order id in session
                    $whamessage = "Dear {$userData['name']},\n" .
                    "Please avoid making unnecessary payments on {$site_data['brand']}";
                       send_sms($userData['mobile'],$whamessage);
                      }
                    } else {
                        alert_js("Dublicate Registration Payments.");
                        unset($_SESSION['registerOrder_id']);   // remove order id in session
                        unset($_SESSION['registerToken_id']);   // remove order id in session
                    }
                     }else{
                          alert_js("Transaction " . $resArray['result']['status']);
                     }
                  } else {
                      alert_js($resArray['message']);
                  }
                }else{
                    awal_alert_msg("Account Already Activated <br> Login and Continue our Services!",'success','login');  
                    unset($_SESSION['registerOrder_id']);   // remove order id in session
                    unset($_SESSION['registerToken_id']);   // remove order id in session
                }
              }
   
    redirect("login",1500);
    die();      
} else { 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Self Registrion</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f8f9fa;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            color: #333;
        }
        .container {
            text-align: center;
            background: #fff;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        h1 {
            color: #d9534f;
        }
        p {
            margin: 15px 0;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #0056b3;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Some Technical Issue...</h1>
        <p>We are currently experiencing issues with the payment gateway. Please contact the Help Desk for assistance.</p>
        <button onclick="goBack()">Go Back</button>
    </div>

    <script>
        function goBack() {
            window.history.back();
        }
    </script>
</body>
</html>
<?php }
?>