<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<?php if ( !isset($_GET['user_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['user_nonce'])), 'Copuloo') ) { echo 'Sorry, we couldn\'t verify your request due to a security check failure.'; return; } ?>
<div class="content d-flex flex-column flex-column-fluid" id="content">
  <div class="container-xxl" id="content_container">
    <?php
    use Twilio\Rest\Client;
    $copuloo_keys = new CopulooKeysClass();
    $copuloo_sid = $copuloo_keys->TWILIO_SID();
    $copuloo_token = $copuloo_keys->TWILIO_TOKEN();
    $copuloo_client = null;
    $copuloo_data = [];
    $copuloo_errorMessage = false;
    //$copuloo_address_items = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_addresses WHERE user = %d limit 50", wp_get_current_user()->ID)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
    if (!empty($copuloo_sid) && !empty($copuloo_token)) {
        $copuloo_client = new Client($copuloo_sid, $copuloo_token);
    }
    // Address Requirements Filter
    $copuloo_searchData = [];
    if ( isset( $_GET['requirements'] ) ) {
    $copuloo_req = sanitize_text_field( wp_unslash( $_GET['requirements'] ) );
    switch ( $copuloo_req ) {
        case 'none':
            // Only show numbers that require NO address at all
            $copuloo_searchData['excludeAllAddressRequired'] = true;
            $copuloo_searchData['excludeLocalAddressRequired'] = false;
            $copuloo_searchData['excludeForeignAddressRequired'] = false;
            break;

        case 'local':
            // Hide numbers that require a LOCAL address (most restrictive)
            $copuloo_searchData['excludeLocalAddressRequired'] = true;
            break;

        case 'foreign':
            // Hide numbers that require a FOREIGN address
            $copuloo_searchData['excludeForeignAddressRequired'] = true;
            break;

        case 'any':
        default:
            break;
    }
}
if ( isset( $_GET['beta'] ) && sanitize_text_field( wp_unslash( $_GET['beta'] ) ) === 'none' ) {
    $copuloo_searchData['beta'] = false; // Exclude beta numbers
}
    if (!empty($_GET['areacode'])) {
        $copuloo_searchData['areaCode'] = sanitize_text_field(wp_unslash($_GET['areacode']));
    }

    if (!empty($_GET['contains'])) {
        $copuloo_searchData['contains'] = sanitize_text_field(wp_unslash($_GET['contains']));
    }
    if (!empty($_GET['countrycode']) && !empty($_GET['type']) && $copuloo_client) {
        $copuloo_countryCode = sanitize_text_field(wp_unslash($_GET['countrycode']));
        $type = sanitize_text_field(wp_unslash($_GET['type']));
        try {
            switch ($type) {
              case 'all':
                    $copuloo_local_data = $copuloo_client->availablePhoneNumbers($copuloo_countryCode)->local->read($copuloo_searchData, 5);
                    $copuloo_tollFree_data = $copuloo_client->availablePhoneNumbers($copuloo_countryCode)->tollFree->read($copuloo_searchData, 5);
                    $copuloo_mobile_data = $copuloo_client->availablePhoneNumbers($copuloo_countryCode)->mobile->read($copuloo_searchData, 5);
                    break;
                case 'local':
                    $copuloo_local_data = $copuloo_client->availablePhoneNumbers($copuloo_countryCode)->local->read($copuloo_searchData, 15);
                    break;
                case 'TollFree':
                    $copuloo_tollFree_data = $copuloo_client->availablePhoneNumbers($copuloo_countryCode)->tollFree->read($copuloo_searchData, 15);
                    break;
                case 'mobile':
                    $copuloo_mobile_data = $copuloo_client->availablePhoneNumbers($copuloo_countryCode)->mobile->read($copuloo_searchData, 15);
                    break;
            }
        } catch (Exception $e) {
            $copuloo_errorMessage = true;
        }
    }
    ?>
    <?php if (isset($_GET['addressrequired'])) { echo wp_kses_post(copuloo_main_danger("Address & Bundle Required", "A valid address and bundle is required to get the requested phone number. Go to Twilio and create a local address and bundle and then add the SID's when requesting the phone number again.")); }  ?>
    <?php if (isset($_GET['erroraddingnumber'])) { echo wp_kses_post(copuloo_main_danger("Phone Number Could Not Be Added", "An error has occurred and we could not process your request.")); }  ?>
    <?php if (!isset($copuloo_client)) { echo wp_kses_post(copuloo_main_danger("Twilio API Keys Not Setup", "Missing or incorrect twilio api credentials.")); }  ?>
    <form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post" class="form">
      <?php wp_nonce_field( 'Copuloo', 'user_nonce' ); ?>
      <input type="hidden" name="action" value="copuloo_search_numbers"></input>
      <div class="card mb-8">
        <div class="card-body">
          <div class="d-flex align-items-center">
            <div class="position-relative w-md-400px me-2">
              <select name="countrycode" data-placeholder="Select A Country Code" class="form-select form-select-solid form-select-lg fw-semibold mb-0 mb-lg-0">
                <?php
                $copuloo_selected_country = isset($_GET['countrycode']) ? sanitize_text_field(wp_unslash($_GET['countrycode'])) : 'US';
                foreach ($copuloo_countries_list as $copuloo_code => $copuloo_label) {
                    $copuloo_selected = selected($copuloo_selected_country, $copuloo_code, false);
                    echo '<option value="' . esc_attr($copuloo_code) . '" ' . esc_html($copuloo_selected) . '>' . esc_html($copuloo_label) . '</option>';
                }
                ?>
              </select>
            </div>
            <div class="d-flex align-items-center">
              <button type="submit" onclick="this.innerHTML='<span class=&quot;spinner-border spinner-border-sm&quot;></span> Searching...'; this.disabled=true; this.form.submit();" class="btn btn-primary me-5">Search</button>
            </div>
          </div>
          <div>
            <div class="separator separator-dashed mt-9 mb-6"></div>
            <div class="row g-8" data-select2-id="select2-data-123-mnoi">
              <div class="col-lg-3">
                <label class="fs-6 form-label fw-bold text-gray-900">
                  <span class="">Area Code</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="The area code of the phone numbers to read. Applies to only phone numbers in the US and Canada.">
                    <i class="fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <input type="number" value="<?php if (isset($_GET['areacode'])) { echo esc_html(sanitize_text_field(wp_unslash($_GET['areacode']))); } ?>" class="form-control form-control form-control-solid" name="areacode" placeholder="Area Code">
              </div>
              <div class="col-lg-3">
                <label class="fs-6 form-label fw-bold text-gray-900">
                  <span class="">Contains</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="The pattern on which to match phone numbers. Valid characters are *, 0-9, a-z, and A-Z. The * character matches any single digit. ">
                    <i class="fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <input type="text" value="<?php if (isset($_GET['contains'])) { echo esc_html(sanitize_text_field(wp_unslash($_GET['contains']))); } ?>" class="form-control form-control form-control-solid" name="contains" placeholder="Contains">
              </div>
              <div class="col-lg-6">
                <label class="fs-6 form-label fw-bold text-gray-900">
                  <span class="">Type</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="Local numbers are assigned to a specific geographical region. Toll-Free numbers allow people to call you without incurring any charges. Mobile numbers are assigned a particular range within the country's telephone numbering plan.">
                    <i class="fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <div class="nav-group nav-group-fluid">
                  <label>
                    <input type="radio" class="btn-check" name="type" value="all" <?php if (!isset($_GET['type']) || isset($_GET['type']) && sanitize_text_field(wp_unslash($_GET['type'])) == 'all' ) { echo 'checked="checked"'; } ?>>
                    <span class="btn btn-sm btn-color-muted btn-active btn-active-primary fw-bold px-4">All</span>
                  </label>
                  <label>
                    <input type="radio" class="btn-check" name="type" value="local" <?php if (isset($_GET['type']) && sanitize_text_field(wp_unslash($_GET['type'])) == 'local' ) { echo 'checked="checked"'; } ?>>
                    <span class="btn btn-sm btn-color-muted btn-active btn-active-primary fw-bold px-4">Local</span>
                  </label>
                  <label>
                    <input type="radio" class="btn-check" name="type" value="TollFree" <?php if (isset($_GET['type']) && sanitize_text_field(wp_unslash($_GET['type'])) == 'TollFree' ) { echo 'checked="checked"'; } ?>>
                    <span class="btn btn-sm btn-color-muted btn-active btn-active-primary fw-bold px-4">Toll-Free</span>
                  </label>
                  <label>
                    <input type="radio" class="btn-check" name="type" value="mobile" <?php if (isset($_GET['type']) && sanitize_text_field(wp_unslash($_GET['type'])) == 'mobile' ) { echo 'checked="checked"'; } ?>>
                    <span class="btn btn-sm btn-color-muted btn-active btn-active-primary fw-bold px-4">Mobile</span>
                  </label>
                </div>
              </div>
            </div>
            <div class="row g-8 mt-3">
              <div class="col-lg-3">
                <label class="fs-6 form-label fw-bold text-gray-900">
                  <span class="">Requirements</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="Some local authorities require you to provide an address before purchasing a phone number.">
                    <i class="fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <select name="addressrequirements" aria-label="Select" data-placeholder="Select" class="form-select form-select-solid form-select-lg fw-semibold mb-0 mb-lg-0">
                  <option name="addressrequirements" value="any" <?php if (!isset($_GET['requirements']) || isset($_GET['requirements']) && sanitize_text_field(wp_unslash($_GET['requirements'])) == 'any' ) { echo 'selected'; } ?>>Any</option>
                  <option name="addressrequirements" value="none" <?php if (isset($_GET['requirements']) && sanitize_text_field(wp_unslash($_GET['requirements'])) == 'none' ) { echo 'selected'; } ?>>None</option>
                  <option name="addressrequirements" value="local" <?php if (isset($_GET['requirements']) && sanitize_text_field(wp_unslash($_GET['requirements'])) == 'local' ) { echo 'selected'; } ?>>Exclude Local Address Requirements</option>
                  <option name="addressrequirements" value="foreign" <?php if (isset($_GET['requirements']) && sanitize_text_field(wp_unslash($_GET['requirements'])) == 'foreign' ) { echo 'selected'; } ?>>Exclude Foreign Address Requirements</option>
                </select>
              </div>
              <div class="col-lg-3">
                <label class="fs-6 form-label fw-bold text-gray-900">
                  <span class="">Beta Numbers</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="These are newly released phone numbers on Twilios platform.">
                    <i class="fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <select name="beta" aria-label="Select" data-placeholder="Select" class="form-select form-select-solid form-select-lg fw-semibold mb-0 mb-lg-0">
                  <option name="beta" value="any" <?php if (!isset($_GET['beta']) || isset($_GET['beta']) && sanitize_text_field(wp_unslash($_GET['beta'])) == 'any' ) { echo 'selected'; } ?>>Any</option>
                  <option name="beta" value="none" <?php if (isset($_GET['beta']) && sanitize_text_field(wp_unslash($_GET['beta'])) == 'none' ) { echo 'selected'; } ?>>Exclude Beta Numbers</option>
                </select>
              </div>
              <div class="col-lg-6">
                <label class="fs-6 form-label fw-bold text-gray-900">
                  <span class="">Capabilities</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="These are the capabilities of searchable phone numbers.">
                    <i class="fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <div class="nav-group nav-group-fluid p-4">
                      <input class="form-check-input" type="checkbox" checked><label class="form-check-label px-3" for="drop-remove">Voice</label></input>
                      <input class="form-check-input" type="checkbox" checked><label class="form-check-label px-3" for="drop-remove">SMS</label></input>
                      <input class="form-check-input" type="checkbox" checked><label class="form-check-label px-3" for="drop-remove">MMS</label></input>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </form>
    <div class="col-12">
      <div class="card h-xl-100" id="timeline_widget_2_card">
        <div class="card-header position-relative py-0 border-bottom-2">
          <h3 class="card-title">Available Phone Numbers</h3>
        </div>
        <div class="card-body">

          <div class="table-responsive"> <?php
                if (isset($_GET['countrycode']) && (!empty($copuloo_local_data) || !empty($copuloo_tollFree_data) || !empty($copuloo_mobile_data)))
                {
                  echo '<table class="table table-hover table-rounded table-striped border border-gray-300 border-dashed gy-7 gs-7">';
                  echo '<thead>';
                  echo '<tr class="fw-semibold fs-6 text-gray-800 border-bottom-2 border-gray-200">';
                    echo '<th>Number</th>';
                    echo '<th>Capabilities</th>';
                    echo '<th>Type</th>';
                    echo '<th>Local Regulatory Requirements</th>';
                    echo '<th></th>';
                  echo '</tr>';
                  echo '</thead>';
                  echo '<tbody>';
                  foreach ($copuloo_local_data as $copuloo_record)
                  {
                    echo '<tr class="align-middle">';
                      echo '<td class="col-3">' . esc_html($copuloo_record->friendlyName) . '<br>' . esc_html($copuloo_record->locality) . ' ' . esc_html($copuloo_record->region) . '</td>';

                      echo '<td class="col-2">';
                      if ($copuloo_record->capabilities->sms == 1) { echo '<span class="badge badge-success">SMS</span><br>'; } else { echo '<span class="badge badge-danger">SMS</span><br>'; }
                      if ($copuloo_record->capabilities->mms == 1) { echo '<span class="badge badge-success">MMS</span><br>'; } else { echo '<span class="badge badge-danger">MMS</span><br>'; }
                      if ($copuloo_record->capabilities->voice == 1) { echo '<span class="badge badge-success">VOICE</span>'; } else { echo '<span class="badge badge-danger">VOICE</span>'; }
                      echo '</td>';
                      echo '<td class="col-2">Local<br>';
                      if ($copuloo_record->beta == 1) { echo '<span class="badge badge-danger">Beta</span>'; }
                      echo '</td>';
                      echo '<td class="col-2"><span class="badge badge-dark">'. esc_html($copuloo_record->addressRequirements) .'</span></td>';
                      echo '<td class="col-2"><button type="button" onclick="document.getElementById(\'requestedNumber\').value = \'' . esc_html($copuloo_record->phoneNumber) . '\'; document.getElementById(\'requestedNumberUI\').innerHTML = \'' . esc_html($copuloo_record->phoneNumber) . '\';" class="btn border btn-sm btn-active-light-primary" data-bs-toggle="modal" data-bs-target="#modal_1">Get Number</button></td>';
                    echo '</tr>';
                  }
                  foreach ($copuloo_tollFree_data as $copuloo_record)
                  {
                    echo '<tr class="align-middle">';
                      echo '<td class="col-3">' . esc_html($copuloo_record->friendlyName) . '<br>' . esc_html($copuloo_record->locality) . ' ' . esc_html($copuloo_record->region) . '</td>';

                      echo '<td class="col-2">';
                      if ($copuloo_record->capabilities->sms == 1) { echo '<span class="badge badge-success">SMS</span><br>'; } else { echo '<span class="badge badge-danger">SMS</span><br>'; }
                      if ($copuloo_record->capabilities->mms == 1) { echo '<span class="badge badge-success">MMS</span><br>'; } else { echo '<span class="badge badge-danger">MMS</span><br>'; }
                      if ($copuloo_record->capabilities->voice == 1) { echo '<span class="badge badge-success">VOICE</span>'; } else { echo '<span class="badge badge-danger">VOICE</span>'; }
                      echo '</td>';
                      echo '<td class="col-2">Toll-Free<br>';
                      if ($copuloo_record->beta == 1) { echo '<span class="badge badge-danger">Beta</span>'; }
                      echo '</td>';
                      echo '<td class="col-2"><span class="badge badge-dark">'. esc_html($copuloo_record->addressRequirements) .'</span></td>';
                      echo '<td class="col-2"><button type="button" onclick="document.getElementById(\'requestedNumber\').value = \'' . esc_html($copuloo_record->phoneNumber) . '\'; document.getElementById(\'requestedNumberUI\').innerHTML = \'' . esc_html($copuloo_record->phoneNumber) . '\';" class="btn border btn-sm btn-active-light-primary" data-bs-toggle="modal" data-bs-target="#modal_1">Get Number</button></td>';
                    echo '</tr>';
                  }
                  foreach ($copuloo_mobile_data as $copuloo_record)
                  {
                    echo '<tr class="align-middle">';
                      echo '<td class="col-3">' . esc_html($copuloo_record->friendlyName) . '<br>' . esc_html($copuloo_record->locality) . ' ' . esc_html($copuloo_record->region) . '</td>';

                      echo '<td class="col-2">';
                      if ($copuloo_record->capabilities->sms == 1) { echo '<span class="badge badge-success">SMS</span><br>'; } else { echo '<span class="badge badge-danger">SMS</span><br>'; }
                      if ($copuloo_record->capabilities->mms == 1) { echo '<span class="badge badge-success">MMS</span><br>'; } else { echo '<span class="badge badge-danger">MMS</span><br>'; }
                      if ($copuloo_record->capabilities->voice == 1) { echo '<span class="badge badge-success">VOICE</span>'; } else { echo '<span class="badge badge-danger">VOICE</span>'; }
                      echo '</td>';
                      echo '<td class="col-2">Mobile<br>';
                      if ($copuloo_record->beta == 1) { echo '<span class="badge badge-danger">Beta</span>'; }
                      echo '</td>';
                      echo '<td class="col-2"><span class="badge badge-dark">'. esc_html($copuloo_record->addressRequirements) .'</span></td>';
                      echo '<td class="col-2"><button type="button" onclick="document.getElementById(\'requestedNumber\').value = \'' . esc_html($copuloo_record->phoneNumber) . '\'; document.getElementById(\'requestedNumberUI\').innerHTML = \'' . esc_html($copuloo_record->phoneNumber) . '\';" class="btn border btn-sm btn-active-light-primary" data-bs-toggle="modal" data-bs-target="#modal_1">Get Number</button></td>';
                    echo '</tr>';
                  }
                  echo '</tbody>';
                  echo '</table>';
                }
                else if (isset($_GET['countrycode']))
                {
                  echo '<div class="card border border-gray-300 border-dashed rounded p-6">
												<div class="card-header border-0 pt-15 pb-15">
													<h3 class="card-title align-items-start flex-column">
														<span class="card-label fw-bold text-gray-900">Sorry We Could\'nt Find Any Available Numbers</span>
														<span class="text-muted mt-1 fw-semibold fs-7">Use the search bar above to filter through phone numbers that meet your desired criteria.</span>
													</h3>
													<div class="card-toolbar"></div>
												</div>
											</div>';
                }
                else if (!isset($_GET['countrycode']))
                {
                  echo '<div class="card border border-gray-300 border-dashed rounded p-6">
												<div class="card-header border-0 pt-15 pb-15">
													<h3 class="card-title align-items-start flex-column">
														<span class="card-label fw-bold text-gray-900">Try Searching For A Number</span>
														<span class="text-muted mt-1 fw-semibold fs-7">Use the search bar above to filter through phone numbers that meet your desired criteria.</span>
													</h3>
													<div class="card-toolbar"></div>
												</div>
											</div>';
                }
                ?> </div>
        </div>
      </div>
    </div>
  </div>
</div>

<form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post" class="form">
<input type="hidden" name="action" value="copuloo_request_number"></input>
<?php wp_nonce_field( 'Copuloo', 'user_nonce' ); ?>
  <div class="modal fade" tabindex="-1" id="modal_1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header pb-0 border-0 justify-content-end">
          <div class="btn btn-sm btn-icon btn-active-color-primary" data-bs-dismiss="modal">
            <i class="fs-1">
              <span class="fas fa-times"></span>
            </i>
          </div>
        </div>
        <div class="modal-body">
          <div class="mb-13">
            <h1 id="requestedNumberUI" class="mb-3">Get Number</h1>
            <div class="text-muted fw-semibold fs-5">To get started, just click on "Get Number".</div>
          </div>

          <div class="stepper stepper-pills stepper-column d-flex flex-column flex-xl-row flex-row-fluid first mb-8">
            <div class="d-flex justify-content-center justify-content-xl-start flex-row-auto w-100 w-xl-300px">
              <div class="stepper-nav ps-lg-10">
                <div class="stepper-item pending">
                  <div class="stepper-wrapper">
                    <div class="stepper-icon w-40px h-40px">
                      <i class="stepper-check fs-2"></i>
                      <span class="stepper-number">1</span>
                    </div>
                    <div class="stepper-label">
                      <h3 class="stepper-title">Associated Costs</h3>
                      <div class="stepper-desc">Twilio charges fees for each phone number which can vary depending on the country of origin. It should also be noted that your Twilio account should be funded before requesting a number.</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="stepper stepper-pills stepper-column d-flex flex-column flex-xl-row flex-row-fluid first mb-8">
            <div class="d-flex justify-content-center justify-content-xl-start flex-row-auto w-100 w-xl-300px">
              <div class="stepper-nav ps-lg-10">
                <div class="stepper-item pending">
                  <div class="stepper-wrapper">
                    <div class="stepper-icon w-40px h-40px">
                      <i class="stepper-check fs-2"></i>
                      <span class="stepper-number">2</span>
                    </div>
                    <div class="stepper-label">
                      <h3 class="stepper-title">Regulatory Requirements</h3>
                      <div class="stepper-desc" id="addressRequirementText">Some phone numbers have local regulatory requirements. If the phone number you chose has these requirements then add your Twilio Bundle and Address SID below. You can find and create <a target="_blank" href="https://console.twilio.com/us1/develop/phone-numbers/regulatory-compliance/addresses">addresses here</a> and <a target="_blank" href="https://console.twilio.com/us1/develop/phone-numbers/regulatory-compliance/bundles">bundles here</a></div>
                      <input type="text" value="" class="form-control form-control form-control-solid mt-4" name="addressidentity" placeholder="Twilio Address SID">
                      <input type="text" value="" class="form-control form-control form-control-solid mt-4" name="bundleidentity" placeholder="Twilio Bundle SID">
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="stepper stepper-pills stepper-column d-flex flex-column flex-xl-row flex-row-fluid first mb-8">
            <div class="d-flex justify-content-center justify-content-xl-start flex-row-auto w-100 w-xl-300px">
              <div class="stepper-nav ps-lg-10">
                <div class="stepper-item pending">
                  <div class="stepper-wrapper">
                    <div class="stepper-icon w-40px h-40px">
                      <i class="stepper-check fs-2"></i>
                      <span class="stepper-number">3</span>
                    </div>
                    <div class="stepper-label">
                      <h3 class="stepper-title">Enjoy Your Number</h3>
                      <div class="stepper-desc">After requesting a number, it will be added to your account allowing you to start making calls almost immediately.</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
            <input type="hidden" name="number" id="requestedNumber"></input>
            <input type="hidden" name="location" id="requestedLocation"></input>
            <input type="hidden" name="type" id="requestedType"></input>
            <button type='submit' class='btn btn-primary'>Get Number</button>
        </div>
      </div>
    </div>
  </div>
</form>