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

/* ===== SERVICE & FEE SETTINGS ===== */
$fee = $udata['Pan_To_Aadhar_Find_a'];
checkServiceStatus($udata, 'Pan_To_Aadhar_Find_a_status');

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

    $pan    = strtoupper(trim($_POST['pan']));
    $user   = $udata['phone'];
    $wallet = $udata['balance'];

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

    /* 🚀 API CALL (FUNCTION) */
    // यह फंक्शन आपके api_helper में होना चाहिए जो ApiNexus को कॉल करे
    $resdata = pan_to_aadhar_verification_run([
        'pan' => $pan
    ]);

    // ApiNexus Response Mapping
    $apiStatus  = isset($resdata['status']) ? (string)$resdata['status'] : '';
    $errorMsg   = $resdata['message'] ?? 'PAN details not found';

    /* ❌ FAILED CASE (ApiNexus uses Status 100 for Success) */
    if ($apiStatus !== "100") {
        echo "<script>
            Swal.fire('Failed','".addslashes($errorMsg)."','error');
        </script>";
        exit;
    }

    /* ✅ SUCCESS FLOW */

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

    // 2. Add Commission
    addCommission(
        $tng_conn,
        $user,
        $fee,
        $udata['parent'] ?? null,
        'PAN TO AADHAAR FIND'
    );

    // 3. Wallet History Entry
    mysqli_query(
        $tng_conn,
        "INSERT INTO wallethistory 
        (userid, amount, balance, purpose, status, type) 
        VALUES(
          '$user', 
          '$fee', 
          '".($wallet - $fee)."', 
          'PAN TO AADHAAR FIND', 
          '1', 
          'Debit'
        )"
    );

    // 4. Encode Response for Database (Save Full API Data)
    $base64Json = base64_encode(
        json_encode($resdata, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
    );

    // 5. Save in PDF/Service Records
    // ApiNexus fields: 'name' and 'aadhaar_number'
    $p_name = mysqli_real_escape_string($tng_conn, $resdata['name'] ?? 'N/A');
    $p_pan  = mysqli_real_escape_string($tng_conn, $pan);
    $p_json = mysqli_real_escape_string($tng_conn, $base64Json);

    mysqli_query(
        $tng_conn,
        "INSERT INTO all_pdf_records 
        (service_name, name, username, number, pdf, date) 
        VALUES(
          'PAN_TO_AADHAAR_FIND', 
          '$p_name', 
          '$user', 
          '$p_pan', 
          '$p_json', 
          NOW()
        )"
    );

    /* 🎉 FINAL SUCCESS ALERT */
    echo "<script>
        Swal.fire({
            icon:'success',
            title:'AADHAAR FOUND',
            text:'Aadhaar: " . ($resdata['aadhaar_number'] ?? '') . "',
            timer:2500,
            showConfirmButton:false
        }).then(()=>window.location='all_history.php');
    </script>";
    exit;
}
?>

<style>
body { background: linear-gradient(135deg,#eef2ff,#fdf2f8); min-height: 100vh; }
.glass { background: #fff; border-radius: 22px; box-shadow: 0 25px 55px rgba(0,0,0,.14); padding: 36px; border: 1px solid rgba(255,255,255,0.18); }
.title { font-weight: 700; color: #312e81; letter-spacing: -0.5px; }
.form-control-lg { border-radius: 12px; border: 2px solid #eef2ff; font-weight: 600; }
.form-control-lg:focus { border-color: #312e81; box-shadow: none; }
.fee-badge { background: #ecfdf5; color: #059669; border: 1px solid #10b981; border-radius: 10px; text-align: center; font-weight: 800; }
.back-btn { text-decoration: none; font-weight: 600; transition: 0.3s; }
.back-btn:hover { transform: translateX(-5px); }
</style>

<div class="page-wrapper">
    <div class="page-content">
        <div class="container">
            <div class="row justify-content-center align-items-center" style="min-height:85vh;">
                <div class="col-lg-5 col-md-7 col-sm-10">
                    <div class="glass">
                        <div class="mb-4">
                            <a href="javascript:history.back()" class="back-btn text-primary">
                                <i class="bi bi-arrow-left-circle-fill"></i> Back to Services
                            </a>
                        </div>

                        <h4 class="title text-center mb-2">🪪 PAN → Aadhaar Find</h4>
                        <p class="text-center text-muted small mb-4">Instant Aadhaar Number Fetching via PAN</p>

                        <form method="post" id="panForm">
                            <div class="mb-4">
                                <label class="fw-bold text-dark mb-2">Enter PAN Number</label>
                                <input type="text" name="pan" maxlength="10" 
                                       class="form-control form-control-lg text-uppercase" 
                                       placeholder="ABCDE1234F" required>
                            </div>

                            <div class="row g-3 align-items-center">
                                <div class="col-6">
                                    <div class="fee-badge p-2">
                                        <small class="d-block text-uppercase" style="font-size: 10px;">Service Fee</small>
                                        ₹ <?= number_format($fee, 2) ?>
                                    </div>
                                </div>
                                <div class="col-6 text-end">
                                    <button type="submit" id="submitBtn" class="btn btn-primary btn-lg w-100 rounded-pill shadow">
                                        <i class="bi bi-search me-1"></i> Find Now
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
let isProcessing = false;
document.getElementById('panForm').addEventListener('submit', function(e) {
    if (isProcessing) return;
    e.preventDefault();

    Swal.fire({
        title: 'Confirm Request?',
        text: 'Fee of ₹<?= $fee ?> will be deducted.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#312e81',
        confirmButtonText: 'Yes, Proceed'
    }).then((result) => {
        if (result.isConfirmed) {
            isProcessing = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerHTML = '<span class="spinner-border spinner-border-sm"></span> Searching...';
            this.submit();
        }
    });
});
</script>

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