<?php
if (isset($_GET["vend"]) && $_GET["vend"] == "kyc") {
  ?>
  <div class="bg bg-secondary-gradient text-white font-bold p-3 kyc-info">
    Hello! Verifying your account is mandatory to keep our services safe.
    <br>
    <small class="p-1 mt-1 text-warning">Your personal information is secure and used only for verification to lift
      transaction limits.</small>
  </div>

  <div class="p-5 shadow rounded">

    <?php
    global $wpdb;

    $raptor_table = $wpdb->prefix . 'vtupress_raptor_settings';
    $r_settings = $wpdb->get_row("SELECT * FROM $raptor_table LIMIT 1");

    if (!$r_settings) {
      wp_send_json_error(['message' => 'KYC Configuration Missing']);
    }

    $id = get_current_user_id();
    $users = new Users();

    $userData = $users->getUser($id, true, true);
    $id = $userData["id"];

    $table_name = $wpdb->prefix . "vtupress_kyc";
    $kyc_data = $wpdb->get_results("SELECT * FROM $table_name WHERE user_id = $id ORDER BY id DESC LIMIT 1");

    // Also fetch from users table for consistent status
    $user_kyc_status = $userData["kyc_status"];
    if ($user_kyc_status == 'unverified' || $user_kyc_status == null && !empty($kyc_data)) {
      $user_kyc_status = $kyc_data[0]->status;
    }

    if ($kyc_data == NULL || strtolower($user_kyc_status) == "retry" || $user_kyc_status == null) {

      $fn = $userData["first_name"];
      $ln = $userData["last_name"];
      ?>
      <form id="kycForm" enctype="multipart/form-data">
        <label for="name">Full Name</label>
        <input type="text" placeholder="Full Name" id="name" name="name" class="name form-control mb-3"
          value="<?php echo esc_attr($fn . ' ' . $ln); ?>" readonly>

        <label for="method">Method Of Verification</label>
        <select class="method form-control mb-3" id="method" name="method">
          <option value=""> --SELECT--</option>
          <option value="bvn"> BVN </option>
          <option value="nin"> National ID Card (NIN) </option>
          <option value="voters"> Voters Card </option>
          <option value="drive"> Driving License </option>
          <option value="pass"> International Passport </option>
        </select>

        <div id="method-fields" class="d-none">
          <!-- BVN/NIN Fields -->
          <div class="bvn_value_div d-none">
            <label for="bvn_value">Enter Value: </label>
            <input class="form-control bvn_value mb-2" type="number" name="bvn_value" id="bvn_value" />
            <div class="alert alert-info py-1">A charge of <?= $currency_symbol ?><span class="chargeAmt"></span> will be
              deducted.</div>
          </div>


          <!-- File Uploads -->
          <div class="photo_div d-none">
            <label for="uploadfile">Passport/Selfie Photograph</label>
            <input class="form-control mb-2" type="file" name="file" id="uploadfile" accept=".jpg,.jpeg,.png" />

            <label for="uploadfill">Document Photo</label>
            <input class="form-control mb-2" type="file" name="fill" id="uploadfill" accept=".jpg,.jpeg,.png" />
          </div>

          <button type="submit" class="btn btn-success text-white w-100 mt-3" id="submitKyc">Submit Verification</button>
          <small class="text-danger d-none" id="kycError">All fields are mandatory</small>
        </div>
      </form>

      <?php
    } elseif (strtolower($user_kyc_status) == "verified") {
      ?>
      <div class="bg bg-success text-white font-bold p-3 rounded">
        <h4><i class="fas fa-check-circle"></i> Account Verified!</h4>
        <p>Thank you for verifying your identity. Limits have been lifted.</p>
      </div>
      <?php
    } elseif (strtolower($user_kyc_status) == "review") {
      ?>
      <div class="bg bg-warning text-dark font-bold p-3 rounded">
        <h4><i class="fas fa-clock"></i> Account Under Review</h4>
        <p>We are reviewing your submission. Please check back later.</p>
      </div>
      <?php
    } elseif (strtolower($user_kyc_status) == "ban") {
      ?>
      <div class="bg bg-danger text-white font-bold p-3 rounded">
        <h4><i class="fas fa-ban"></i> Account Suspended</h4>
        <p>Your account has been suspended. Please contact support.</p>
      </div>
      <?php
    }
    ?>

  </div>

  <script>
    var charge = {
      'bvn': parseFloat(' <?php echo intval($r_settings->bvn_charge ?? 0); ?>'),
      'nin': parseFloat(' <?php echo intval($r_settings->nin_charge ?? 0); ?>')
    };
    jQuery(document).ready(function ($) {

      $('#method').change(function () {
        var val = $(this).val();
        if (val === '') {
          $('#method-fields').addClass('d-none');
          return;
        }

        $('#method-fields').removeClass('d-none');
        $('.kyc-error').addClass('d-none');

        $('.chargeAmt').text(charge[val] || 0);

        if (val === 'bvn' || val === 'nin') {
          $('.bvn_value_div').removeClass('d-none');
          $('.photo_div').addClass('d-none');
        } else {
          $('.bvn_value_div').addClass('d-none');
          $('.photo_div').removeClass('d-none');
        }
      });

      $('#kycForm').submit(function (e) {
        e.preventDefault();

        var method = $('#method').val();
        var name = $('#name').val();

        if (!method) {
          Swal.fire('Error', 'Please select a verification method', 'error');
          return;
        }

        Swal.fire({
          title: 'Processing...',
          text: 'Verifying details...',
          icon: 'info',
          allowOutsideClick: false,
          showConfirmButton: false,
          didOpen: () => { Swal.showLoading(); }
        });

        if (method === 'bvn' || method === 'nin') {
          // Use doAjax for text-based submission
          var val = $('#bvn_value').val();
          if (!val) {
            Swal.fire('Error', 'Please enter the value', 'error');
            return;
          }

          var obj = {
            action: 'vtupress_process_kyc',
            method: method,
            name: name,
            bvn_value: val
          };

          // Using doAjax as requested
          doAjax(vtupressInitPluginData.ajax_url, obj, 'post', 'json', function (response) {
            // Success Callback
            if (response.success) {
              Swal.fire('Success', response.data.message, 'success').then(() => {
                location.reload();
              });
            } else {
              Swal.fire('Failed', response.data.message || 'Verification Failed', 'error');
            }
          }, function (state) {
            // Process Callback (Loading)
            // Handled by Swal above, but doAjax might override?
            // doAjax uses standard showToast or dsuccess. 
            // We passed a custom success callback.
          }, function (msg) {
            // Error Callback
            Swal.fire('Error', msg, 'error');
          });

        } else {
          // Use $.ajax for File Uploads
          var formData = new FormData(this);
          formData.append('action', 'vtupress_process_kyc');
          formData.append('_nonce', vtupressobj.nonce); // Security if needed

          // Validate File Inputs
          if ($('#uploadfile')[0].files.length === 0 || $('#uploadfill')[0].files.length === 0) {
            Swal.fire('Error', 'Please upload both documents', 'error');
            return;
          }

          $.ajax({
            url: vtupressInitPluginData.ajax_url,
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
              if (response.success) {
                Swal.fire('Success', response.data.message, 'success').then(() => {
                  location.reload();
                });
              } else {
                Swal.fire('Failed', response.data.message || 'Submission Failed', 'error');
              }
            },
            error: function (jqXHR) {
              Swal.fire('Error', 'Server Error: ' + jqXHR.statusText, 'error');
            }
          });
        }
      });

    });
  </script>

  <?php
}
?>