<?php
require_once("../layouts/members/head.php");
if ($user_data['voter_Mobile_Link_Service'] == "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
              if (isset($_POST['submit'])) {
                  $voterNumber = strtoupper(trim($_POST['voterNumber']));
                  if (!empty($voterNumber)) {
                      $amount = $user_data['voter_mobile_link_fee'];
                      if ($user_data['balance'] >= $amount) {
                          $request = [
                              'voterNumber' => $voterNumber,
                          ];
                          $responseApi = vcmserch_api_run($request);
                          $response = json_decode($responseApi, true) ?? '';
                          
                      if (isset($response['status']) && $response['status'] == '100') {
                          alert_msg("Data find success!", 'success', 0);
                      }else{
                          alert_msg($response['error'], 'danger');
                      }
                      } else {
                          awal_alert_msg("Insufficient Wallet Balance!", 'error');
                      }
                  } else {
                      awal_alert_msg("Voter Number cannot be empty!", 'error');
                  }
              }
          
          if (isset($_POST['submitotp'])) {
              $voterNumber = strtoupper($_POST['voterNumber'] ?? '');
              $mobileNumber = $_POST['mobileNumber'] ?? '';
              $otp = $_POST['otp'] ?? '';

              if (!empty($voterNumber) && !empty($mobileNumber) && !empty($otp)) {
                  $amount = $user_data['voter_mobile_link_fee'];
                  $old_balance = $user_data['balance'];
                  $new_balance = $old_balance - $amount;

                  if ($user_data['balance'] >= $amount) {
                      $order_id = order_txn_id();
                      $request = [
                          'voterNumber' => $voterNumber,
                          'mobileNo' => $mobileNumber,
                          'otp' => $otp,
                      ];

                      $responseApi = vcm_Verifyotp_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'       => "VOTERMOBILELINK",
                                  'type'          => "Debit",
                                  'account_number'=> $response['epicNo'],
                                  'app_type'      => "VOTERMOBILELINK",
                                  'amount'        => $amount,
                                  'main_amount'   => $amount,
                                  'old_balance'   => $old_balance,
                                  'new_balance'   => $new_balance,
                                  'txn_id'        => $order_id,
                                  'ref_id'        => $response['epicNo'],
                                  'description'   => "Rs.{$amount} Has Been Debit From Wallet for Mobile Link in SrNo: {$response['refrenceNo']} Voter Number",
                                  'date_time'     => current_timestamp(),
                                  'status'        => "Success"
                              ];

                              $insertId = db_insert("reports", $insData);
                              if ($insertId) {
                                 $fields = [
                                     'epicNo' => 'Voter No',
                                     'refrenceNo' => 'Sr No',
                                 ];

                                 $whamessage = "Dear {$user_data['name']},\nYour Request for Voter Number *{$voterNumber}* Mobile Link 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);
                                  awal_alert_msg($response['message'] ?? 'Mobile Linked Success!', 'success');
                              } else {
                                  awal_alert_msg("Insert Server 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');
              }
          }
          ?>
          <?php if (!isset($response['name']) || $response['name'] == '') { ?>
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Voter Number</label>
              <input type="text" name="voterNumber" placeholder="Enter Voter Number" maxlength="15" oninput="this.value = this.value.toUpperCase().replace(/\s+/g, '');" class="form-control" onkeypress="if(this.value.length==15) 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['voter_mobile_link_fee'];?></button>
              <button type="submit" name="submit" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
          
          <?php }else{ ?>
          <form action="" method="POST" class="row">
            <div class="col-md-12 mb-3">
              <label>Full Name</label>
              <input type="text" name="name" placeholder="Enter Full Name" class="form-control" readonly value="<?php echo $response['name'];?>" required>
              <input type="hidden" id="voterNumber" name="voterNumber" class="form-control" readonly value="<?php echo $response['epicno'];?>" required>
            </div>
            <div class="col-md-12 mb-3">
              <div class="row">
                <div class="col-md-8">
                  <label>New Mobile Number</label>
                  <input type="number" id="phoneNumber" name="mobileNumber" placeholder="<?php echo $response['mobileNumber'] ?? 'Enter Mobile Number'; ?>" maxlength="10" class="form-control" onkeypress="if(this.value.length==10) return false;" required>
                </div>
                <div class="col-md-4 d-flex align-items-end">
                  <button type="button" id="sendOtpButton" class="btn btn-danger w-100">Send OTP</button>
                </div>
              </div>
            </div>
            <div class="col-md-12 mb-3">
              <label>Secret Code</label>
              <input type="number" name="otp" placeholder="Enter 6 Digit OTP" maxlength="6" class="form-control" onkeypress="if(this.value.length==6) 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['voter_mobile_link_fee'];?></button>
              <button type="submit" name="submitotp" class="btn btn-primary" onclick="return confirm('Are you sure?');">Submit</button>
            </div>
          </form>
         <?php }?>
        </div>
      </div>
    </div>
    
<script>
    document.getElementById('sendOtpButton').addEventListener('click', function () {
    var phoneNumber = document.getElementById('phoneNumber').value;
    var voterNumber = document.getElementById('voterNumber').value;
    if (!phoneNumber || !voterNumber) {
        alert('Please fill in all required fields.');
        return;
    }
    var apiUrl = `https://<?php echo p4pointsapi("p4points_url"); ?>/api/v1/v-Addition/send-otp?nmobile=${encodeURIComponent(phoneNumber)}&epic=${encodeURIComponent(voterNumber)}`;
    fetch(apiUrl)
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not OK');
            }
            return response.json();
        })
        .then(data => {
            console.log('API response:', data); 
            if (data.error) {
                alert(data.error); 
            } else if (data.message) {
                alert(data.message); 
            } else {
                alert('Unexpected response from the server.');
            }
        })
        .catch(error => {
            console.error('Error:', error); 
            alert('An error occurred while sending OTP. Please try again later.');
        });
});
</script>
</div>
<?php
} else {
    require_once("404.php");
}
} else {
      awal_alert_msg('You Do Not Have Any Voter Service Active!', 'info', 'dashboard');
}
require_once("../layouts/members/foot.php");
?>
