<?php
include('../includes/session.php');
include('../includes/config.php');
include('../template/ahkweb/header.php');

$_P=mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT * FROM pricing WHERE service_name='nsdl_new_pan_fee'"));
$_A=mysqli_fetch_assoc(mysqli_query($ahk_conn,"SELECT * FROM pricing WHERE service_name='nsdl_new_pan_activation_charge'"));
$__f=$_P['price']??0;
$__a=$_A['price']??0;
$_s=$udata['nsdl_status']??'inactive';
$_b=$udata['branch_code']??'';

if(isset($_POST['activate_service'])){
    $_w=$udata['balance'];
    if($_w<$__a){
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>Swal.fire({icon:"error",title:"Low Balance!",text:"₹'.$__a.' required to activate.",timer:3000,timerProgressBar:true}).then(()=>{window.location="wallet.php";});</script>';
        exit;
    }
    $_b="P".$udata['phone'];
    mysqli_query($ahk_conn,"UPDATE users SET balance=balance-$__a, nsdl_status='active', branch_code='$_b' WHERE phone='{$udata['phone']}'");
    mysqli_query($ahk_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES('{$udata['phone']}','$__a','".($_w-$__a)."','NSDL Activation','1','Debit')");
    echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>Swal.fire({icon:"success",title:"Service Activated!",text:"Branch: '.$_b.'",timer:3000,timerProgressBar:true}).then(()=>{window.location="";});</script>';
    exit;
}

if($_SERVER['REQUEST_METHOD']=="POST" && isset($_POST['name']) && !isset($_POST['activate_service'])){
    if($_s!=='active'){
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>Swal.fire({icon:"warning",title:"Service Inactive!",text:"Activate NSDL service first.",timer:3000,timerProgressBar:true});</script>';
        exit;
    }
    $_w=$udata['balance'];
    if($_w<$__f){
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>Swal.fire({icon:"error",title:"Low Balance!",text:"Recharge wallet.",timer:3000,timerProgressBar:true}).then(()=>{window.location="wallet.php";});</script>';
        exit;
    }
    $_N=mysqli_real_escape_string($ahk_conn,$_POST['name']);
    $_G=$_POST['gender'];
    $_M=$_POST['mobile'];
    $_E=$_POST['email'];
    $_AM=$_POST['application_mode'];
    $_AT=$_POST['application_type'];
    $_PO=uniqid("NSDL");
    $_R = (isset($_SERVER['HTTPS']) ? "https://" : "http://") . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['PHP_SELF']), '/\\') . "/nsdl_pan_apply.php";
    $_U="$tng_apiurl/api/nsdl-api/v1/nsdl_new_pan_apply_verification?p_order_id=$_PO&apikey=$tng_apikey&name=".urlencode($_N)."&gender=$_G&mobile=$_M&email=$_E&application_mode=$_AM&application_type=$_AT&branch_code=$_b&redirect_url=$_R";

    $_C=curl_init();
    curl_setopt_array($_C,[CURLOPT_URL=>$_U,CURLOPT_RETURNTRANSFER=>true,CURLOPT_TIMEOUT=>30,CURLOPT_FOLLOWLOCATION=>true]);
    $_RES=curl_exec($_C);
    curl_close($_C);
    $_D=json_decode($_RES,true);

    if(isset($_D['sampleCode'])&&$_D['sampleCode']=="200"){
        mysqli_query($ahk_conn,"UPDATE users SET balance=balance-$__f WHERE phone='{$udata['phone']}'");
        mysqli_query($ahk_conn,"INSERT INTO wallethistory(userid,amount,balance,purpose,status,type) VALUES('{$udata['phone']}','$__f','".($_w-$__f)."','NSDL PAN Apply','1','Debit')");
        $_O=$_D['data']['p_order_id'];
        $_RED=$_D['data']['redirect_url'];
        $_DATE=date("Y-m-d H:i:s");
        mysqli_query($ahk_conn,"INSERT INTO nsdl_requests(name,mobile,email,gender,application_type,application_mode,phone,p_order_id,status,date) VALUES('$_N','$_M','$_E','$_G','$_AT','$_AM','{$udata['phone']}','$_O','Pending','$_DATE')");
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>Swal.fire({icon:"success",title:"Submitted!",text:"Redirecting...",timer:2000,timerProgressBar:true}).then(()=>{window.location.href="'.$_RED.'";});</script>';
    }else{
        $_MSG=$_D['error']??"Error!";
        echo '<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>Swal.fire({icon:"error",title:"Failed!",text:"'.$_MSG.'",timer:4000,timerProgressBar:true});</script>';
    }
}
?>

<!-- HTML Obfuscated UI -->
<div class="content-wrap"><div class="main"><div class="page-wrapper"><div class="page-content"><div class="main-container"><div class="col-lg-12"><div class="card" style="margin:10px;padding:20px;box-shadow:1px 5px 5px 5px;"><div class="stat-widget-two"><div class="stat-content"><div class="container-fluid"><div class="row"><div class="col-lg-8"><div class="card"><div class="card-body"><div class="alert alert-info" role="alert">NSDL New PAN Apply</div>
<?php if($_s==='active'){ ?>
<div class="alert alert-success">✅ Active | Branch: <b><?php echo $_b;?></b></div>
<form method="POST" class="row g-3">
<div class="col-md-6"><label>Name</label><input type="text" name="name" placeholder="Enter Name" class="form-control" required></div>
<div class="col-md-6"><label>Gender</label><select name="gender" class="form-control" required><option value="M">Male</option><option value="F">Female</option><option value="T">Transgender</option></select></div>
<div class="col-md-6"><label>Mobile</label><input type="text" name="mobile" class="form-control" placeholder="Mobile" required></div>
<div class="col-md-6"><label>Email</label><input type="email" name="email" class="form-control" placeholder="Email" required></div>
<div class="col-md-6"><label>Application Type</label><select name="application_type" class="form-control" required><<option value="49A">PAN - Indian Citizen (Form 49A)</option>
                            <option value="CR">Changes or Correction in existing PAN</option></select></div>
<div class="col-md-6"><label>Application Mode</label><select name="application_mode" class="form-control" required><option value="EKYC">EKYC</option><option value="ESIGN">ESIGN</option></select></div>
<hr><div class="row mt-3"><div class="col-md-6"><input class="form-control" value="Charge ₹ <?php echo $__f;?>" readonly></div><div class="col-md-6 text-end"><button class="btn btn-success" name="submit"><i class="fa fa-check-circle"></i> Submit</button></div></div></form>
<?php }else{ ?>
<div class="card shadow-lg border-0 mx-auto" style="max-width:700px;border-radius:15px;"><div class="card-header text-center bg-info text-dark fw-bold" style="font-size:20px;border-radius:15px 15px 0 0;">NSDL New PAN</div>
<div class="card-body text-center"><div class="mb-4"><img src="https://bestfind.pro/template/ahkweb/assets/images/NSDL-Pan-center.webp" alt="NSDL" style="width:250px;max-width:100%;height:auto;border-radius:12px;box-shadow:0 4px 15px rgba(0,0,0,0.2);"></div>
<div class="alert alert-warning d-flex align-items-center justify-content-center" style="gap:20px;font-size:18px;border-radius:12px;padding:25px;"><span class="fw-semibold text-dark">🚫 Service <b>Inactive</b>. Activate first.</span></div>
<form method="POST" class="mt-4"><input type="hidden" name="activate_service" value="1"><button type="submit" class="btn btn-primary btn-lg px-5" style="border-radius:30px;font-size:18px;font-weight:bold;">🚀 Activate (₹<?php echo $__a;?>)</button></form></div></div>
<?php } ?>
</div></div></div></div></div></div></div></div></div></div></div>

<?php
if(isset($_GET['encrypted_data'])){
    $__E=urldecode($_GET['encrypted_data']);
    $__E=str_replace(" ","+",$__E);
    $__U="$tng_apiurl/api/nsdl-api/v1/nsdl_encrypted_status?apikey=$tng_apikey&encrypted_data=".urlencode($__E);
    $__C=curl_init($__U);
    curl_setopt($__C,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($__C,CURLOPT_TIMEOUT,15);
    $__R=curl_exec($__C);
    curl_close($__C);
    $__J=json_decode($__R,true);
    if(!empty($__J['status']) && $__J['status']==="true" && !empty($__J['data']['txn_status'])){
        $__PO=$__J['data']['p_order_id'];
        $__Q=mysqli_query($ahk_conn,"SELECT * FROM nsdl_requests WHERE p_order_id='$__PO' LIMIT 1");
        if($__Q && mysqli_num_rows($__Q)>0){
            $__ROW=mysqli_fetch_assoc($__Q);
            if($__ROW['status']==="Pending"){
                $__TX=$__J['data']['txn_status'];
                $__ACK=$__J['data']['ack_no']??'';
                $__ID=(int)$__ROW['id'];
                mysqli_query($ahk_conn,"UPDATE nsdl_requests SET status='$__TX', ack_no='$__ACK', encrypted_data='".mysqli_real_escape_string($ahk_conn,$__E)."' WHERE id='$__ID'");
            }
        }
    }
}
?>
<?php include('../template/ahkweb/footer.php'); ?>
<script src="../template/ahkweb/assets/js/bootstrap.bundle.min.js"></script>
<script src="../template/ahkweb/assets/plugins/simplebar/js/simplebar.min.js"></script>
<script src="../template/ahkweb/assets/plugins/metismenu/js/metisMenu.min.js"></script>
<script src="../template/ahkweb/assets/plugins/perfect-scrollbar/js/perfect-scrollbar.js"></script>
<script src="../template/ahkweb/assets/js/app.js"></script>
</html>
