<?php
require_once("../layouts/members/head.php");
if ($user_data['farmer_services'] == "YES") {
if (in_array($user_data['usertype'], ['Master Distributor', 'Distributor', 'Retailer'])) {
?>
<div class="row">
    <div class="col-md-4 mb-2">
      <div class="card text-danger">
        <div class="card-header bg-primary text-white py-2">
          <div class="d-flex align-items-center">
            <span class="mr-auto"><?= file_name() ?></span>
             <button class="btn btn-dark btn-sm ml-auto" onclick="history.back()" > <i class="fas fa-arrow-left"></i> Back</button>
          </div>
        </div>
        <div class="p-3 text-dark">
          <?php
          $apiResponseData = null;

          if (isset($_POST['submit'])) {
              $uidNumber = strtoupper($_POST['uidNumber']);
              $language = strtoupper($_POST['language_Code']);

              if (!empty($uidNumber) && !empty($language)) {
                  $amount = $user_data['agriFarmer_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

                  if ($user_data['balance'] >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'uidNumber' => $uidNumber,
                          'language' => $language,
                      ];

                      $responseApi = farmeragri_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) {
                              
                              $printData = array(
                                  'farmerNumber' => isset($response['farmerNumber']) && !empty($response['farmerNumber']) ? $response['farmerNumber'] : $uidNumber,
                                  'name' => isset($response['name']) && !empty($response['name']) ? $response['name'] : 'NA',
                                  'fname' => isset($response['fname']) && !empty($response['fname']) ? $response['fname'] : 'NA',
                                  'gender' => isset($response['gender']) && !empty($response['gender']) ? $response['gender'] : '',
                                  'dob' => isset($response['dob']) && !empty($response['dob']) ? $response['dob'] : '',
                                  'mobileNumber' => isset($response['mobileNumber']) && !empty($response['mobileNumber']) ? $response['mobileNumber'] : '',
                                  'uid' => isset($response['uid']) && !empty($response['uid']) ? $response['uid'] : '',
                                  'centralId' => isset($response['centralId']) && !empty($response['centralId']) ? $response['centralId'] : '',
                                  'address' => isset($response['address']) && !empty($response['address']) ? $response['address'] : '',
                                  'nameLL' => isset($response['nameLL']) && !empty($response['nameLL']) ? $response['nameLL'] : '',
                                  'fnameLL' => isset($response['fnameLL']) && !empty($response['fnameLL']) ? $response['fnameLL'] : '',
                                  'addressLL' => isset($response['addressLL']) && !empty($response['addressLL']) ? $response['addressLL'] : '',
                                  'approvalStatus' => isset($response['approvalStatus']) && !empty($response['approvalStatus']) ? $response['approvalStatus'] : '',
                                  'enrollmentDate' => isset($response['enrollmentDate']) && !empty($response['enrollmentDate']) ? $response['enrollmentDate'] : '',
                                  'verifiedOn' => isset($response['verifiedOn']) && !empty($response['verifiedOn']) ? $response['verifiedOn'] : '',
                                  'image' => isset($response['image']) && !empty($response['image']) ? $response['image'] : '',
                                  'language' => isset($language) && !empty($language) ? $language : '',
                                  'username'      => $user_data['username'],
                              );
                              $name = isset($response['name']) && !empty($response['name']) ? $response['name'] : 'NA';
                              $farmerNumber = isset($response['farmerNumber']) && !empty($response['farmerNumber']) ? $response['farmerNumber'] : $uidNumber;
                              
                               $printDataJson = json_encode($printData, JSON_UNESCAPED_UNICODE);
                               $printDataUtf8 = mb_convert_encoding($printDataJson, 'UTF-8', 'UTF-8');
                               $encodedData = base64_encode($printDataUtf8);
                               
                               $Mremark = 'Name: ' . $name . " - Farmer Number: " .$farmerNumber;
                               $insData = [
                                   'order_id'      => $order_id,
                                   'username'      => $user_data['username'],
                                   'name'          => $name,
                                   'idNumber'      => $farmerNumber,
                                   'service'       => "Agri_Farmer_Certificate",
                                   'date_time'     => current_timestamp(),
                                   'printData'     => $encodedData,
                                   'photo'         => "",
                               ];

                               $insertIddata = db_insert("printRecords", $insData);
    
                               if ($insertIddata) {
                                   
                              $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'       => "Agri_Farmer_Certificate",
                                  'type'          => "Debit",
                                  'account_number'=> $response['farmerNumber'],
                                  'app_type'      => "Agri_Farmer_Certificate",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['farmerNumber'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Farmer Verification {$response['farmerNumber']} UID Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                 $fields = [
                                      'uid' => 'Uid No',
                                      'farmerNumber' => 'Farmer ID',
                                      'name'  => 'Name',
                                      'fname' => 'C/o',
                                      'centralId' => 'Central Id',
                                      'approvalStatus' => 'Status',
                                 ];

                                 $whamessage = "Dear {$user_data['name']},\nYour Request for Farmer Certificate By *{$uidNumber}* has been Complete.\n\n";

                                 foreach ($fields as $key => $label) {
                                     if (!empty($response[$key])) {
                                         $whamessage .= "*$label*: {$response[$key]}\n";
                                     }
                                 }
                                 $whamessage .= "\nBest Regards,\n_*{$site_data['brand']}.*_";
                                  send_sms($user_data['mobile'],$whamessage);
                              } else {
                                  awal_alert_msg("Insert Server Error!", 'error');
                              }
                              awal_alert_msg("Data Fetch Successful", '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("Insufficient Wallet Balance!", 'error');
                  }
              } else {
                  awal_alert_msg("Please Fill All Valid Details!", 'error');
              }
          }
          ?>
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Enter Aadhaar Number</label>
              <input type="text" name="uidNumber" placeholder="Enter Aadhar Number" minlength="12"  oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" onkeypress="if(this.value.length==12) return false;" required>
            </div>
            <div class="col-md-12 mb-3">
              <label for="language_Code" class="form-label">Select Language:</label>
              <select name="language_Code" id="language_Code" class="form-control" required>
                <option value="">Select Local Language</option>
              </select>
            </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> <?= $user_data['agriFarmer_fee']; ?>
              </button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
        <!-- Display Datatable Section -->
    <?php if (isset($response['status']) && $response['status'] == '100') {  ?>
<div class="col-md-8 mb-2">
  <div class="card text-danger">
    <div class="card-header bg-danger text-white py-2">
      <span class="mr-auto">Details Searching Complete UID No: <strong><?= $uidNumber ?? 'N/A'; ?></strong></span>
    </div>
    <div class="table-responsive">
      <table class="table table-bordered table-striped">
        <tbody>
          <?php if (!empty($response['uid'])): ?>
          <tr>
            <td><strong>UID Number</strong></td>
            <td><?= htmlspecialchars($response['uid']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (isset($response['farmerNumber'])): ?>
          <tr>
            <td><strong>Farmer ID</strong></td>
            <td><?= htmlspecialchars($response['farmerNumber']); ?></td>
          </tr>
          <?php endif; ?>
          
          <?php if (isset($response['approvalStatus'])): ?>
          <tr>
            <td><strong>Status</strong></td>
            <td><?= htmlspecialchars($response['approvalStatus']); ?></td>
          </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>
<?php } ?>
</div>
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const languages = [
      { code: "hi", name: "Hindi" },
      { code: "bn", name: "Bengali" },
      { code: "ta", name: "Tamil" },
      { code: "te", name: "Telugu" },
      { code: "mr", name: "Marathi" },
      { code: "gu", name: "Gujarati" },
      { code: "kn", name: "Kannada" },
      { code: "ml", name: "Malayalam" },
      { code: "pa", name: "Punjabi" },
      { code: "ur", name: "Urdu" },
      { code: "as", name: "Assamese" },
      { code: "or", name: "Odia" }
    ];

    const stateSelect = document.getElementById("language_Code");

    languages.forEach(function(language) {
      const option = document.createElement("option");
      option.value = language.code;
      option.textContent = language.name;
      stateSelect.appendChild(option);
    });
  });
</script>

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