<?php
require_once("../layouts/members/head.php");
 if ($user_data['pan2uid_find_service'] == "YES") { 
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
  $getresult = true;
?>
<?php
if (isset($_POST['submit'])) {
    $order_id = order_txn_id();
    $amount = $user_data['pan2uid_find_fee'];
    $old_balance = $user_data['balance'];
    $new_balance = $old_balance - $amount;
    
if ($old_balance >= $amount) {
    $panNumber = $_POST['panNumber'];
    
  if (!empty($panNumber)) {
    $order_id = order_txn_id();
    $request = [
        'panNumber' => $panNumber,
        'order_id' => $order_id
    ];

    $responseApi = pantoUidfind_run($request);
    $response = json_decode($responseApi, true) ?? '';

    if (isset($response['status']) && $response['status'] == '100') {
    $updateSuccess = db_update("members", ["balance" => $new_balance], "user_id='{$user_data['user_id']}'");
    if ($updateSuccess) {
     $insData = [
         'site_id'       => $site_data['site_id'],
         'user_id'       => $user_data['user_id'],
         'username'      => $user_data['username'],
         'name'          => $user_data['name'],
         'operator'      => $user_data['usertype'],
         'parent_id'     => $user_data['parent_id'],
         'order_id'      => $order_id,
         'service'       => "PAN UID FIND REQUEST",
         'type'          => "Debit",
         'account_number'=> $panNumber,
         'app_type'      => "PAN UID FIND REQUEST",
         'amount'        => $amount,
         'main_amount'   => $amount,
         'old_balance'   => $old_balance,
         'new_balance'   => $new_balance,
         'txn_id'        => $order_id,
         'ref_id'        => $panNumber,
         'description'   => "Rs.{$amount} Has Been Debit From Wallet for PAN UID FIND By Pan Number",
         'date_time'     => current_timestamp(),
         'status'        => "Success"
     ];

     $insertIds = db_insert("reports", $insData);
     if ($insertIds) {
         //successful insert in records
      } else {
          awal_alert_msg("Insert Server Error!", 'error');
      }
    
    $printData = array(
        'panNumber'=> $panNumber,
        'name'     => '',
        'dob'      => '',
        'gender'   => '',
        'uid'      => '',
        'order_id' => $order_id,
        'amount'   => $amount,
        'username' => $user_data['username'],
    );

    $insData = [
        'order_id'      => $order_id,
        'username'      => $user_data['username'],
        'name'          => $panNumber,
        'idNumber'      => $panNumber,
        'service'       => "PanUidFind_Request",
        'date_time'     => current_timestamp(),
        'printData'     => base64_encode(str_replace("\\", "", json_encode($printData, JSON_UNESCAPED_UNICODE))),
        'photo'         => "",
        'status'         => "Process",
    ];

    $insertId = db_insert("printRecords", $insData);
    
     $whamessage = "Dear Admin,\nYou have received a Pan UID Find request Please update immediately.\n\n";
     $whamessage .= "Order ID: *$order_id*\Pan: *$panNumber*\n";
     $whamessage .= "Best Regards,\n_*{$site_data['brand']}*_";
     send_sms($site_data['mobile'], $whamessage);

    if ($insertId) {
         awal_alert_msg("Applied Successful Wait for 10 minutes", 'success');
        redirect('printRecord', 3000);
    } else {
         awal_alert_msg("Saving Data Error!", 'error');
     }
  } else {
      awal_alert_msg("Balance debited from wallet but not updated in the database. Please contact support!", 'error');
  }

 } else {
     awal_alert_msg($response['error'] ?? 'Server Down', 'error');
 }
} else {
    awal_alert_msg("Please Fill All Valid Details!", 'error');
}
} else {
   awal_alert_msg("Insufficient Wallet Balance!", 'error');
} 

}
?>
<style>
  .input-with-tooltip {
    position: relative;
  }

  .tooltip-icon {
    position: absolute;
    top: 50%;
    right: 10px;
    transform: translateY(-50%);
    color: orange;
    cursor: pointer;
    font-size: 18px;
  }

  .tooltip-icon::after {
    content: "Enter Pin, If you have applied LL in Non Aadhar Mode (Specially for State of Assam)";
    position: absolute;
    bottom: 100%;
    right: 0;
    background: #333;
    color: #fff;
    padding: 6px 10px;
    border-radius: 4px;
    font-size: 12px;
    display: none;
    z-index: 999;
    width: 250px; /* responsive width */
    white-space: normal;
    word-wrap: break-word;
  }

  .tooltip-icon:hover::after {
    display: block;
  }

  @media (max-width: 480px) {
    .tooltip-icon::after {
      width: 200px;
      font-size: 11px;
      right: auto;
      left: 0;
    }
  }
</style>
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="row">
        <div class="col-lg-4">
            <div class="card border">
                <div class="card-header text-white bg-primary">
                    <h6 class="mb-0"><?= file_name() ?></h6>
                </div><form method="post" action="" id="myForm" enctype="multipart/form-data">
                <div class="card-body">
                        <div class="mb-3">
                            <input type="text" class="form-control" id="panNumber" name="panNumber" maxlength="10" placeholder="ABCDE1234F" autocomplete="off" required>
                            <small id="panError" class="text-danger" style="display:none;">Invalid PAN Number. Format: ABCDE1234F</small>
                        </div>
                        <div class="col-md-12 mb-3 d-flex justify-content-between">
                          <button type="button" class="btn btn-secondary" ><i class="fas fa-inr"></i> <?php echo $user_data['pan2uid_find_fee'];?></button>
                          <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Apply Data <i class="fas fa-check-circle"></i></button>
                        </div>
                </div>
            </div>
        </div>
     </form>
    </div>
</div>
<script>
document.getElementById('panNumber').addEventListener('input', function () {
    let panInput = this.value.toUpperCase(); // Convert input to uppercase
    panInput = panInput.replace(/[^A-Z0-9]/g, ''); // Remove spaces and special characters
    this.value = panInput; // Set the sanitized input back to the field

    const panError = document.getElementById('panError');
    const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/; // PAN validation regex

    if (panRegex.test(panInput)) {
        panError.style.display = 'none'; // Hide error
        this.classList.remove('is-invalid'); // Remove invalid class
        this.classList.add('is-valid'); // Add valid class
    } else {
        panError.style.display = 'block'; // Show error
        this.classList.add('is-invalid'); // Add invalid class
        this.classList.remove('is-valid'); // Remove valid class
    }
});

</script>
<?php } else {
    require_once("404.php");
}
} else {
      awal_alert_msg('You Do Not Have Any Pan Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>