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

// फीस और सर्विस स्टेटस चेक
$baseFee = $udata['tng_pan_details'];
checkServiceStatus($udata,'tng_pan_details_status');

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

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

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

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

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

    /* 🚀 API CALL */
    // यह आपके api_helper के pan_verification_api_run फंक्शन को कॉल करेगा
    $resdata = pan_verification_api_run([
        'pan'     => $pan,
        'pantype' => $type
    ]);

    // API Nexus के नए Response के अनुसार Mapping
    $apiStatus   = isset($resdata['status']) ? (string)$resdata['status'] : '';
    $apiSuccess  = $resdata['success'] ?? false;
    $errorMsg    = $resdata['message'] ?? 'PAN details not found';

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

    /* ✅ SUCCESS FLOW */

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

    // 2. Commission Logic
    addCommission(
        $tng_conn, 
        $user, 
        $fee, 
        $udata['parent'] ?? null, 
        'PAN PREMIUM DETAILS'
    );

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

    /* 4. BASE64 JSON SAVE (Mapping from Nexus API) */
    $saveData = [
        'fullname'    => $resdata['name'] ?? 'N/A',
        'fathername'  => $resdata['fathername'] ?? 'N/A',
        'dob'         => $resdata['dob'] ?? 'N/A',
        'gender'      => $resdata['gender'] ?? 'N/A',
        'aadhaar'     => $resdata['maskedAadhaar'] ?? 'N/A',
        'linked'      => $resdata['aadhaarLinked'] ?? false,
        'app_no'      => $resdata['application_no'] ?? '',
        'pan'         => $resdata['panNumber'] ?? $pan
    ];

    $base64Json = base64_encode(
        json_encode($saveData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
    );

    // 5. Save in PDF Records
    $p_name = mysqli_real_escape_string($tng_conn, $saveData['fullname']);
    $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_PAN_DETAILS', 
          '$p_name', 
          '$user', 
          '$p_pan', 
          '$p_json', 
          NOW()
        )"
    );

    /* 6. FINAL RESPONSE */
    echo "<script>
        Swal.fire({
            icon:'success',
            title:'PAN VERIFIED',
            text:'Details of ".addslashes($p_name)." fetched successfully',
            timer:2500,
            showConfirmButton:false
        }).then(()=>window.location='all_history.php');
    </script>";
    exit;
}
?>

<style>
body { background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); min-height: 100vh; }
.glass { background: rgba(255, 255, 255, 0.95); border-radius: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.1); padding: 40px; border: 1px solid #fff; }
.title { font-weight: 800; color: #1a237e; letter-spacing: 1px; }
.back-btn { text-decoration: none; font-weight: 600; transition: 0.3s; }
.back-btn:hover { color: #0d47a1 !important; transform: translateX(-5px); display: inline-block; }
.form-control-lg { border-radius: 12px; font-size: 1rem; border: 2px solid #e0e0e0; }
.form-control-lg:focus { border-color: #3f51b5; box-shadow: none; }
#feeBox { background: #f1f8e9; border: none; text-align: center; color: #2e7d32 !important; }
</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-8">
                    <div class="glass">
                        <div class="mb-3">
                            <a href="javascript:history.back()" class="text-decoration-none fw-bold">
                                <i class="bi bi-arrow-left"></i> BACK
                            </a>
                        </div>

                        <h4 class="title text-center mb-4">🪪 PAN VERIFICATION</h4>

                        <form method="post" id="panForm">
                            <div class="mb-3">
                                <label class="fw-bold mb-1">PAN CARD NUMBER</label>
                                <input type="text" name="pan" maxlength="10" 
                                       class="form-control form-control-lg text-uppercase" 
                                       placeholder="ABCDE1234F" required>
                            </div>

                            <div class="mb-3">
                                <label class="fw-bold mb-1">SELECT SERVER</label>
                                <select name="pantype" id="serverType" class="form-select form-select-lg" required>
                                    <option value="">-- Choose Server --</option>
                                    <option value="server_1">Premium Server 1</option>
                                    <option value="server_2">Premium Server 2</option>
                                </select>
                            </div>

                            <div class="row mt-4 align-items-center">
                                <div class="col-6">
                                    <input id="feeBox" class="form-control" value="Fee: ₹ 0" readonly>
                                </div>
                                <div class="col-6 text-end">
                                    <button type="submit" id="submitBtn" class="btn btn-primary btn-lg w-100 rounded-pill shadow-sm" style="background:#1a237e; border:none;">
                                        VERIFY NOW
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
const charges = <?= json_encode($charges); ?>;
document.getElementById('serverType').addEventListener('change', function(){
    const fee = charges[this.value] || '0';
    document.getElementById('feeBox').value = 'Fee: ₹ ' + fee;
});

let isSubmitting = false;
document.getElementById('panForm').addEventListener('submit', function(e){
    if(isSubmitting) return;
    e.preventDefault();

    Swal.fire({
        title: 'Confirm Request?',
        text: 'Charges will be deducted from wallet.',
        icon: 'question',
        showCancelButton: true,
        confirmButtonColor: '#1a237e',
        confirmButtonText: 'Yes, Proceed'
    }).then((result) => {
        if (result.isConfirmed) {
            isSubmitting = true;
            document.getElementById('submitBtn').disabled = true;
            document.getElementById('submitBtn').innerHTML = 'Processing...';
            this.submit();
        }
    });
});
</script>

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