<?php
require_once("../layouts/members/head.php");
 if ($user_data['rationto_uid_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['rationto_uid_find_all_fee'];
    $old_balance = $user_data['balance'];
    $new_balance = $old_balance - $amount;
    
if ($old_balance >= $amount) {
    $rationNumber = $_POST['rationNumber'];
    
  if (!empty($rationNumber)) {
    $order_id = order_txn_id();
    $request = [
        'rationNumber' => $rationNumber,
        'order_id' => $order_id
    ];

    $responseApi = ration2uid_find_allstate_api_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'       => "RATION UID FIND REQUEST",
         'type'          => "Debit",
         'account_number'=> $rationNumber,
         'app_type'      => "RATION UID FIND REQUEST",
         'amount'        => $amount,
         'main_amount'   => $amount,
         'old_balance'   => $old_balance,
         'new_balance'   => $new_balance,
         'txn_id'        => $order_id,
         'ref_id'        => $rationNumber,
         'description'   => "Rs.{$amount} Has Been Debit From Wallet for RATION UID FIND By Ration 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(
        'rationNumber'=> $rationNumber,
        'name'     => '',
        'dob'      => '',
        'gender'   => '',
        'uid'      => '',
        'order_id' => $order_id,
        'amount'   => $amount,
        'username' => $user_data['username'],
    );

    $insData = [
        'order_id'      => $order_id,
        'username'      => $user_data['username'],
        'name'          => $rationNumber,
        'idNumber'      => $rationNumber,
        'service'       => "RationUidFind_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 Ration UID Find request Please update immediately.\n\n";
     $whamessage .= "Order ID: *$order_id*\Ration: *$rationNumber*\n";
     $whamessage .= "Best Regards,\n_*{$site_data['brand']}*_";
     send_sms($site_data['mobile'], $whamessage);

    if ($insertId) {
         awal_alert_msg("Applied Successful Wait for 5 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');
} 

}
?>
<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="number" name="rationNumber" placeholder="Enter Ration Number" maxlength="25" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" onkeypress="if(this.value.length==25) return false;"required>
                  </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['rationto_uid_find_all_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>

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