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

/* ===== SERVICE & FEE SETTINGS ===== */
// डेटाबेस से फीस और सर्विस स्टेटस उठाना
$fee = $udata['pan_to_mask_uid_fee']; 
checkServiceStatus($udata, 'pan_to_mask_uid_fee_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 LOGIC */
    // SQL से API Key प्राप्त करना
    $tng_api_key = JkL_get('TheNextGenAPI', 'tng_apikey'); 
    
    // API URL तैयार करना (जैसा आपने फॉर्मेट दिया था)
    $apiUrl = "https://apinexus.co.in/api/v1/maskAadharVerification.php?apiKey=" . $tng_api_key . "&panNumber=" . urlencode($pan);

    // API को कॉल करना (blank page से बचने के लिए @ का प्रयोग और file_get_contents)
    $resJson = @file_get_contents($apiUrl);
    $resdata = json_decode($resJson, true) ?? [];

    // API रिस्पॉन्स पैरामीटर्स (आपके JSON फॉर्मेट के अनुसार)
    $statusMessage = isset($resdata['statusMessage']) ? $resdata['statusMessage'] : '';
    $message       = isset($resdata['message']) ? $resdata['message'] : 'API Server Error or Timeout';
    $maskAadhar    = isset($resdata['aadhar']) ? $resdata['aadhar'] : '';

    /* ❌ FAILED CASE */
    if ($statusMessage !== "success" || empty($maskAadhar)) {
        echo "<script>
            Swal.fire('Failed','".addslashes($message)."','error');
        </script>";
    } else {
        /* ✅ SUCCESS FLOW */
        
        // 1. Wallet से पैसे काटना
        $updateWallet = mysqli_query($tng_conn, "UPDATE users SET balance = balance - $fee WHERE phone = '$user'");

        if ($updateWallet) {
            // 2. कमीशन जोड़ना (यदि फंक्शन मौजूद है)
            if (function_exists('addCommission')) {
                addCommission($tng_conn, $user, $fee, $udata['parent'] ?? null, 'PAN TO MASK AADHAAR');
            }

            // 3. Wallet History में एंट्री
            $post_bal = $wallet - $fee;
            mysqli_query($tng_conn, "INSERT INTO wallethistory (userid, amount, balance, purpose, status, type) 
                VALUES ('$user', '$fee', '$post_bal', 'PAN TO MASK AADHAAR', '1', 'Debit')");

            // 4. Record Save करना (History के लिए)
            $base64Json = base64_encode(json_encode($resdata, JSON_UNESCAPED_UNICODE));
            $p_pan  = mysqli_real_escape_string($tng_conn, $pan);
            $p_json = mysqli_real_escape_string($tng_conn, $base64Json);
            $p_name = mysqli_real_escape_string($tng_conn, $maskAadhar);

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

            /* 🎉 SUCCESS ALERT */
            echo "<script>
                Swal.fire({
                    icon: 'success',
                    title: 'Data Fetched!',
                    text: 'Masked Aadhaar: $maskAadhar',
                    confirmButtonText: 'View History'
                }).then(() => {
                    window.location='all_history.php';
                });
            </script>";
            exit;
        } else {
            echo "<script>Swal.fire('Error','Database Update Failed','error');</script>";
        }
    }
}
?>

<div class="page-wrapper">
    <div class="page-content">
        <div class="container">
            <div class="row justify-content-center align-items-center" style="min-height:75vh;">
                <div class="col-md-5">
                    <div class="card border-top border-0 border-4 border-primary shadow-lg" style="border-radius: 15px;">
                        <div class="card-body p-5">
                            <div class="card-title d-flex align-items-center">
                                <div><i class="bx bxs-id-card me-2 font-22 text-primary"></i></div>
                                <h5 class="mb-0 text-primary fw-bold">PAN to Masked Aadhaar</h5>
                            </div>
                            <hr>
                            <p class="text-muted small">Enter PAN to get the linked Masked Aadhaar number instantly.</p>
                            
                            <form method="POST" id="maskForm" autocomplete="off">
                                <div class="col-12 mb-3">
                                    <label class="form-label fw-bold">PAN Number</label>
                                    <input type="text" name="pan" id="panInput" 
                                           class="form-control form-control-lg text-uppercase fw-bold" 
                                           placeholder="ABCDE1234F" maxlength="10" required>
                                </div>
                                
                                <div class="col-12 mb-4">
                                    <div class="p-3 bg-light rounded-3 text-success fw-bold text-center border">
                                        Charges: ₹<?php echo number_format($fee, 2); ?>
                                    </div>
                                </div>

                                <div class="col-12">
                                    <button type="submit" id="subBtn" class="btn btn-primary btn-lg w-100 radius-30 shadow-sm">
                                        <i class="bx bx-search-alt"></i> Get Aadhaar
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
document.getElementById('maskForm').addEventListener('submit', function(e) {
    const pan = document.getElementById('panInput').value.trim();
    const regex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/i;
    
    if(!regex.test(pan)) {
        e.preventDefault();
        Swal.fire('Invalid Format', 'Please enter a valid 10-digit PAN (e.g., GCRPR1524M)', 'error');
        return;
    }

    e.preventDefault();
    Swal.fire({
        title: 'Confirm Request?',
        text: "₹<?= number_format($fee, 2) ?> will be deducted from your wallet.",
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Yes, Submit'
    }).then((result) => {
        if (result.isConfirmed) {
            const btn = document.getElementById('subBtn');
            btn.disabled = true;
            btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span> Searching...';
            this.submit();
        }
    });
});
</script>

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