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

/* ===============================
   SERVICE CONFIG
================================ */
$baseFee = $udata['tng_pan_panfind'];
checkServiceStatus($udata,'tng_pan_panfind_status');

$charges = [
    'server_1' => $baseFee,
    'server_2' => $baseFee + 5
];

/* ===============================
   FORM SUBMIT
================================ */
if ($_SERVER['REQUEST_METHOD']==='POST'
    && !empty($_POST['aadhar'])
    && !empty($_POST['pantype'])
) {

    $aadhar = trim($_POST['aadhar']);
    $type   = $_POST['pantype'];
    $fee    = $charges[$type] ?? $baseFee;

    $user   = $udata['phone'];
    $wallet = $udata['balance'];

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

    /* ===============================
       API CALL
    ================================ */
    $resdata = pan_find_verificationapi_run([
        'aadhar' => $aadhar,
        'type'   => $type
    ]);

    $sampleCode = $resdata['sampleCode'] ?? '';
    $errorMsg   = $resdata['message'] ?? 'Request Failed';

    /* ❌ FAILED */
    if ($sampleCode !== "200" && $sampleCode !== "208") {
        echo "<script>
            Swal.fire('Failed','".addslashes($errorMsg)."','error');
        </script>";
        exit;
    }

    /* ===============================
       SUCCESS FLOW
    ================================ */

    // Wallet debit
    mysqli_query(
        $tng_conn,
        "UPDATE users SET balance = balance - $fee WHERE phone='$user'"
    );

    // Commission
    addCommission(
        $tng_conn,
        $user,
        $fee,
        $udata['parent'] ?? null,
        'Aadhar To PAN Find'
    );

    // Wallet history
    mysqli_query(
        $tng_conn,
        "INSERT INTO wallethistory
        (userid,amount,balance,purpose,status,type)
        VALUES(
            '$user',
            '$fee',
            '".($wallet-$fee)."',
            'Aadhar To PAN Find',
            '1',
            'Debit'
        )"
    );

    // Save API JSON (Base64)
    $jsonBase64 = base64_encode(json_encode($resdata));

    mysqli_query(
        $tng_conn,
        "INSERT INTO all_pdf_records
        (service_name,name,username,number,pdf,date)
        VALUES(
            'AADHAR_TO_PAN_FIND',
            '".mysqli_real_escape_string($tng_conn,$resdata['pan'] ?? 'NA')."',
            '$user',
            '$aadhar',
            '".mysqli_real_escape_string($tng_conn,$jsonBase64)."',
            NOW()
        )"
    );

    /* ✅ SUCCESS ALERT */
    echo "<script>
        Swal.fire({
            icon:'success',
            title:'Success',
            text:'PAN Find completed successfully',
            timer:2200,
            showConfirmButton:false
        }).then(()=>window.location='all_history.php');
    </script>";
    exit;
}
?>

<!-- ================= LUXURY UI ================= -->
<style>
body{
  background:linear-gradient(135deg,#eef2ff,#fdf2f8);
}
.glass{
  background:#fff;
  border-radius:22px;
  box-shadow:0 25px 55px rgba(0,0,0,.14);
  padding:36px;
}
.title{
  font-weight:700;
  color:#312e81;
}
.back-btn{
  text-decoration:none;
  font-weight:600;
}
</style>

<div class="page-wrapper">
<div class="page-content">
<div class="container">

<div class="row justify-content-center align-items-center" style="min-height:80vh;">
<div class="col-lg-5 col-md-7 col-sm-10">

<div class="glass">

<a href="javascript:history.back()" class="back-btn 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">
Find PAN details using secure sources
</p>

<form method="post" id="panForm">

<div class="mb-3">
<label class="fw-semibold">Aadhaar Number</label>
<input type="text"
name="aadhar"
maxlength="12"
class="form-control form-control-lg"
placeholder="Enter Aadhaar Number"
required>
</div>

<div class="mb-3">
<label class="fw-semibold">Select Server</label>
<select name="pantype"
id="serverType"
class="form-control form-control-lg"
required>
<option value="">Select Server</option>
<option value="server_1">Server 1</option>
<option value="server_2">Server 2</option>
</select>
</div>

<div class="row mt-4 align-items-center">
<div class="col-6">
<input id="feeBox"
class="form-control fw-bold text-success"
value="Fee ₹ -"
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>
</div>

<!-- ================= JS ================= -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
const charges = <?= json_encode($charges); ?>;

/* Fee Preview */
document.getElementById('serverType').addEventListener('change',function(){
    document.getElementById('feeBox').value =
        'Fee ₹ ' + (charges[this.value] ?? '-');
});

/* Double Submit Lock */
let lock=false;
document.getElementById('panForm').addEventListener('submit',function(e){
    e.preventDefault();
    if(lock) return;

    Swal.fire({
        title:'Confirm Request?',
        text:'Proceed with Aadhaar to PAN Find?',
        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'); ?>
