<?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">DBT <?= 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'])) {
              $inputNumber = strtoupper($_POST['inputNumber']);
              $stateCode = strtoupper($_POST['state_code']);
              
              if (!empty($inputNumber) && !empty($stateCode)) {
                  $amount = $user_data['dbt_farmer_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

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

                      $responseApi = farmerDbt_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(
                                  'regNumber' => isset($response['regNumber']) && !empty($response['regNumber']) ? $response['regNumber'] : $inputNumber,
                                  'name' => isset($response['name']) && !empty($response['name']) ? $response['name'] : 'NA',
                                  'fatherHusband' => isset($response['fatherHusband']) && !empty($response['fatherHusband']) ? $response['fatherHusband'] : 'NA',
                                  'gender' => isset($response['gender']) && !empty($response['gender']) ? $response['gender'] : '',
                                  'dob' => isset($response['dob']) && !empty($response['dob']) ? $response['dob'] : '',
                                  'mobile' => isset($response['mobile']) && !empty($response['mobile']) ? $response['mobile'] : '',
                                  'uid' => isset($response['uid']) && !empty($response['uid']) ? $response['uid'] : '',
                                  'farmerType' => isset($response['farmerType']) && !empty($response['farmerType']) ? $response['farmerType'] : '',
                                  'cast' => isset($response['cast']) && !empty($response['cast']) ? $response['cast'] : '',
                                  'district' => isset($response['district']) && !empty($response['district']) ? $response['district'] : '',
                                  'block' => isset($response['block']) && !empty($response['block']) ? $response['block'] : '',
                                  'panchayat' => isset($response['panchayat']) && !empty($response['panchayat']) ? $response['panchayat'] : '',
                                  'village' => isset($response['village']) && !empty($response['village']) ? $response['village'] : '',
                                  'username'      => $user_data['username'],
                              );
                              $name = isset($response['name']) && !empty($response['name']) ? $response['name'] : 'NA';
                              $regNumber = isset($response['regNumber']) && !empty($response['regNumber']) ? $response['regNumber'] : $inputNumber;
                              
                               $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: " .$regNumber;
                               $insData = [
                                   'order_id'      => $order_id,
                                   'username'      => $user_data['username'],
                                   'name'          => $name,
                                   'idNumber'      => $regNumber,
                                   'service'       => "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'       => "Farmer_Certificate",
                                  'type'          => "Debit",
                                  'account_number'=> $response['regNumber'],
                                  'app_type'      => "Farmer_Certificate",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['regNumber'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Farmer Verification {$response['regNumber']} UID Number ",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                 $fields = [
                                      'uid' => 'Uid No',
                                      'regNumber' => 'Farmer ID',
                                      'name' => 'Name',
                                 ];

                                 $whamessage = "Dear {$user_data['name']},\nYour Request for Farmer Certificate By *{$inputNumber}* 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 for="state_code" class="form-label">Select State:</label>
              <select name="state_code" id="state_code" class="form-control" required>
                <option value="">Select State</option>
              </select>
            </div>
            <div class="col-md-12 mb-3">
              <label>Enter Farmer <sup style="color:red;">( Mobile/ Aadhar/ Registration Number )</sup></label>
              <input type="text" name="inputNumber" placeholder="Enter Any Mobile/ Aadhar/ Registration Number" minlength="10"  class="form-control" 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> <?= $user_data['dbt_farmer_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><?= $inputNumber ?? '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['regNumber'])): ?>
          <tr>
            <td><strong>Farmer ID</strong></td>
            <td><?= htmlspecialchars($response['regNumber']); ?></td>
          </tr>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

    <?php } ?>
</div>
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const states = [
    //   { code: "35", name: "ANDAMAN AND NICOBAR ISLANDS" },
    //   { code: "28", name: "ANDHRA PRADESH" },
    //   { code: "12", name: "ARUNACHAL PRADESH" },
    //   { code: "18", name: "ASSAM" },
      { code: "10", name: "BIHAR" },
    //   { code: "4", name: "CHANDIGARH" },
    //   { code: "22", name: "CHHATTISGARH" },
    //   { code: "26", name: "DADRA AND NAGAR HAVELI AND DAMAN AND DIU" },
    //   { code: "7", name: "DELHI" },
    //   { code: "30", name: "GOA" },
    //   { code: "24", name: "GUJARAT" },
    //   { code: "6", name: "HARYANA" },
    //   { code: "2", name: "HIMACHAL PRADESH" },
    //   { code: "1", name: "JAMMU AND KASHMIR" },
    //   { code: "20", name: "JHARKHAND" },
    //   { code: "29", name: "KARNATAKA" },
    //   { code: "32", name: "KERALA" },
    //   { code: "37", name: "LADAKH" },
    //   { code: "31", name: "LAKSHADWEEP" },
    //   { code: "23", name: "MADHYA PRADESH" },
    //   { code: "27", name: "MAHARASHTRA" },
    //   { code: "14", name: "MANIPUR" },
    //   { code: "17", name: "MEGHALAYA" },
    //   { code: "15", name: "MIZORAM" },
    //   { code: "13", name: "NAGALAND" },
    //   { code: "21", name: "ODISHA" },
    //   { code: "34", name: "PUDUCHERRY" },
    //   { code: "3", name: "PUNJAB" },
    //   { code: "8", name: "RAJASTHAN" },
    //   { code: "11", name: "SIKKIM" },
    //   { code: "33", name: "TAMIL NADU" },
    //   { code: "36", name: "TELANGANA" },
    //   { code: "16", name: "TRIPURA" },
    //   { code: "9", name: "UTTAR PRADESH" },
    //   { code: "5", name: "UTTARAKHAND" },
    //   { code: "19", name: "WEST BENGAL" }
    ];

    const stateSelect = document.getElementById("state_code"); // Your select id

    states.forEach(function(state) {
      const option = document.createElement("option");
      option.value = state.code;
      option.textContent = state.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");
?>
