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

$baseFee = $udata['tng_pan_panfind_apply'];
checkServiceStatus($udata, 'tng_pan_panfind_apply_status');

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['aadhar'])) {

    $aadhar = trim($_POST['aadhar']);
    $user   = $udata['phone'];
    $fee    = $baseFee;
    $wallet = $udata['balance'];

    if ($wallet < $fee) {
        echo "<script>Swal.fire('Wallet Low','Please recharge','error').then(()=>window.location='wallet.php');</script>";
        exit;
    }

   
    $resdata = pan_find_apply_verificationapi_run([
        'aadhar' => $aadhar,
    ]);
    $sampleCode = $resdata['sampleCode'] ?? '';
    $application_no = $resdata['application_no'] ?? '';
    $panName = $resdata['pan'] ?? '';
    $errorMsg = $resdata['message'] ?? $resdata['error'] ?? 'Request Failed';

    
    if ($sampleCode != '200') {
        echo "<script>Swal.fire('Failed','".addslashes($errorMsg)."','error').then(()=>window.location='aadhar_to_pan_apply.php');</script>";
        exit;
    }

    
    mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone='$user'");
    addCommission($tng_conn, $user, $fee, $udata['parent'] ?? null, 'Aadhar To PAN Find');
    mysqli_query($tng_conn, "INSERT INTO wallethistory (userid,amount,balance,purpose,status,type) VALUES('$user','$fee','".($wallet - $fee)."','Aadhar To PAN Find','1','Debit')");

    $apiStatus = $resdata['status'] ?? 'Pending';
    $recordStatus = ($apiStatus == 'Success') ? 'Success' : 'Pending';

   
    $insert = "INSERT INTO aadhar_pan_history 
                (user_phone, aadhar_number, application_no, pan_name, status, request_data, response_data)
                VALUES (
                    '$user',
                    '$aadhar',
                    '".mysqli_real_escape_string($tng_conn, $application_no)."',
                    '".mysqli_real_escape_string($tng_conn, $panName)."',
                    '$recordStatus',
                    '".mysqli_real_escape_string($tng_conn, json_encode($_POST))."',
                    '".mysqli_real_escape_string($tng_conn, json_encode($resdata))."'
                )";
    mysqli_query($tng_conn, $insert);

    if ($recordStatus == 'Success') {
        echo "<script>Swal.fire({icon:'success',title:'".addslashes($errorMsg)."',text:'PAN Found: $panName',timer:2500,showConfirmButton:false}).then(()=>window.location='aadhar_pan_history.php');</script>";
    } else {
        echo "<script>Swal.fire({icon:'info',title:'Processing',text:'Request submitted. Check status later.',timer:3000}).then(()=>window.location='aadhar_pan_history.php');</script>";
    }
    exit;
}
?>

<style>
body{ background:linear-gradient(135deg,#eef2ff,#fdf2f8); }
.luxury-card{
    border-radius:22px;
    background:#fff;
    box-shadow:0 25px 55px rgba(0,0,0,.14);
    padding:36px;
}
.title{
    font-weight:700;
    color:#312e81;
}
</style>

<div class="page-wrapper">
<div class="page-content">
<div class="container d-flex justify-content-center align-items-center" style="min-height:80vh;">
    <div class="col-lg-5 col-md-7 col-sm-10">
        <div class="luxury-card">
            <a href="javascript:history.back()" class="text-primary mb-3 d-block">
                <i class="bi bi-arrow-left-circle"></i> Back
            </a>
             <h4 class="title text-center mb-2">🆔 AADHAR → PAN FIND</h4>
            <p class="text-center text-muted mb-4">Enter 12-digit Aadhaar number</p>
            
            <form method="post" id="panForm">
                <div class="mb-3">
                    <label class="fw-semibold">Aadhaar Number</label>
                    <input type="text" name="aadhar" maxlength="12" pattern="\d{12}"
                           class="form-control form-control-lg" placeholder="Enter 12-digit Aadhaar Number" required>
                </div>
                <div class="row mt-4 align-items-center">
                    <div class="col-6">
                        <input class="form-control fw-bold text-success" value="Fee â‚¹ <?= $baseFee ?>" readonly>
                    </div>
                    <div class="col-6 text-end">
                        <button type="submit" id="submitBtn" class="btn btn-primary px-4 rounded-pill">
<i class="fa fa-search"></i> Find PAN
</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let lock = false;
document.getElementById('panForm').addEventListener('submit', function(e){
    e.preventDefault();
    if(lock) return;
    Swal.fire({
        title:'Confirm Request?',
        text:'Fee â‚¹<?= $baseFee ?> will be deducted from your wallet.',
        icon:'question',
        showCancelButton:true,
        confirmButtonText:'Yes',
        cancelButtonText:'Cancel'
    }).then(r=>{
        if(r.isConfirmed){
            lock=true;
            document.getElementById('submitBtn').disabled=true;
            this.submit();
        }
    });
});
</script>

<?php include('../template/tngweb/footer.php'); ?>