<?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; } ?>
<?php
    // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
    $copuloo_opened_item = array();
    $copuloo_list_items = array();
    $copuloo_addresses_page = 1;
    $copuloo_limit = 10;
    $copuloo_offset = 0;
    if (isset($_GET['addressespage']) && is_numeric($_GET['addressespage']) && $_GET['addressespage'] > 1) {
        $copuloo_addresses_page = (int) $_GET['addressespage'];
        $copuloo_offset = ($copuloo_addresses_page - 1) * $copuloo_limit;
    }
    if (isset($_GET['addressidentity'])) { $copuloo_opened_item = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_addresses WHERE id = %s AND user = %d LIMIT 1", sanitize_text_field(wp_unslash($_GET['addressidentity'])), wp_get_current_user()->ID)); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery
    $copuloo_list_items = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_addresses WHERE user = %d LIMIT %d OFFSET %d", wp_get_current_user()->ID,$copuloo_limit,$copuloo_offset)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
    ?>

<div class="content d-flex flex-column flex-column-fluid" id="content">
  <div class="container-xxl" id="content_container">

    <?php if (isset($_GET['error1'])) { echo wp_kses_post(copuloo_main_danger("Error Creating Address", "There was an error creating an address.")); } ?>
    <?php if (isset($_GET['error2'])) { echo wp_kses_post(copuloo_main_danger("Error Updating Address", "There was an error updating the address.")); } ?>
    <?php if (isset($_GET['error3'])) { echo wp_kses_post(copuloo_main_danger("Error Removing Address", "There was an error removing the address.")); } ?>
    <div class="card mb-8">
      <div class="card-body flex-column p-5">
        <div class="d-flex align-items-center h-lg-300px p-5 p-lg-15">
          <div class="d-flex flex-column align-items-start justift-content-center flex-equal me-5">
            <div class="d-flex flex-wrap flex-sm-nowrap">
              <div class="d-flex flex-center flex-shrink-0 bg-light rounded w-100px h-100px w-lg-150px h-lg-150px me-7 mb-4">
                <div class="d-flex justify-content-center align-items-center p-10">
                    <span class="menu-bullet">
                        <span class="fas fa-home text-dark display-1"></span>
                    </span>
                </div>
              </div>
              <div class="flex-grow-1">
                <div class="d-flex justify-content-between align-items-start flex-wrap mb-2">
                  <div class="d-flex flex-column">
                    <div class="d-flex align-items-center mb-1">
                      <a class="text-gray-800 fs-2 fw-bold me-3">Phone Number Addresses</a>
                    </div>
                    <div class="d-flex flex-wrap fw-semibold mb-4 fs-5 text-gray-400">When requesting phone numbers, some countries require that a phone number have a local address saved. Here you can create and manage your local addresses for your phone numbers. Keep in mind that some phone numbers require local addresses such as the city or town the phone number is designed to operate in, while others may require any address.</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="card-rounded bg-light d-flex flex-stack flex-wrap p-5">
          <ul class="nav flex-wrap border-transparent fw-bold">
            <li class="nav-item my-1">
              <a class="btn btn-color-gray-600 btn-active-secondary btn-active-color-primary fw-bolder fs-8 fs-lg-base nav-link px-3 px-lg-8 mx-1 text-uppercase" href="<?php echo esc_url(wp_nonce_url($copulooDashboardUrl.'&dashboardpage=profile', 'Copuloo', 'user_nonce')); ?>">Profile</a>
            </li>
            <li class="nav-item my-1">
              <a class="btn btn-color-gray-600 btn-active-secondary btn-active-color-primary fw-bolder fs-8 fs-lg-base nav-link px-3 px-lg-8 mx-1 text-uppercase active" href="<?php echo esc_url(wp_nonce_url($copulooDashboardUrl.'&dashboardpage=addresses', 'Copuloo', 'user_nonce')); ?>">Addresses</a>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <div class="col-12 mb-6">
      <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"><?php if(!isset($_GET['addressidentity'])) { echo 'Your Addresses'; } else { echo esc_html($copuloo_opened_item[0]->friendly_name); } ?></h3>
          <div class="card-toolbar">
          <button type="button" class="btn border btn-sm btn-active-light-primary me-3" data-bs-toggle="modal" data-bs-target="#modal_1">Create</button>
          <?php 
          if (!isset($_GET['addressidentity'])) {
            if ($copuloo_addresses_page > 1)
            {
              echo '<a href="' . esc_url(admin_url('admin.php?page=copuloo_dashboard')) . '&dashboardpage=addresses&user_nonce='.esc_attr(sanitize_text_field(wp_unslash($_GET['user_nonce']))).'&addressespage=' . esc_html($copuloo_addresses_page - 1) .'" class="btn btn-light btn-sm me-3">';
              echo '<span class="menu-bullet">';
              echo '<span class="fa fa-arrow-left"></span>';
              echo '</span>';
              echo '</a>';
            }
            echo '<span class="btn btn-bg-primary btn-sm me-3 text-white">'.esc_html($copuloo_addresses_page).'</span>';
            if (isset($copuloo_list_items) && count($copuloo_list_items) == 10)
            {
              echo '<a href="' . esc_url(admin_url('admin.php?page=copuloo_dashboard')) . '&dashboardpage=addresses&user_nonce='.esc_attr(sanitize_text_field(wp_unslash($_GET['user_nonce']))).'&addressespage=' . esc_html($copuloo_addresses_page + 1) .'" class="btn btn-light btn-sm me-3">';
              echo '<span class="menu-bullet">';
              echo '<span class="fa fa-arrow-right"></span>';
              echo '</span>';
              echo '</a>';
            }
          }
          ?>
          </div>
        </div>
        <div class="card-body">
          <div class="tab-content">
            <div class="tab-pane fade active show" id="" role="tabpanel">
              <?php
              if (!isset($_GET['addressidentity']) && $copuloo_list_items != null)
              {
                echo '<div class="table-responsive">';
                echo '<table class="table table-hover table-rounded table-striped border border-gray-300 border-dashed gy-7 gs-7">';
                echo '<tr class="text-start text-muted fw-bold fs-7 text-uppercase gs-0">';
                echo '<th class="min-w-125px"><div class="dt-column-header"><span class="dt-column-title">Friendly Name</span></div></th>';
                echo '<th class="min-w-125px"><div class="dt-column-header"><span class="dt-column-title">Country</span></div></th>';
                echo '<th class="min-w-125px"><div class="dt-column-header"><span class="dt-column-title">Address</span></div></th>';
                echo '<th class="text-end min-w-100px dt-orderable-none"><div class="dt-column-header"><span class="dt-column-title">Action</span></div></th>';
                echo '</tr>';
                echo '<tbody class="text-gray-600 fw-semibold">';
                foreach ($copuloo_list_items as $copuloo_record)
                {
                  echo '<tr><td class="align-middle">'.esc_html($copuloo_record->friendly_name).'</td>';
                  echo '<td class="align-middle">'.esc_html($copuloo_record->country).'</td>';
                  echo '<td class="align-middle">'.esc_html($copuloo_record->line1).' '.esc_html($copuloo_record->line1).' '.esc_html($copuloo_record->city).', '.esc_html($copuloo_record->state).' '.esc_html($copuloo_record->zip).'</td>';
                  echo '<td class="text-end"><a href="'.esc_url(wp_nonce_url($copulooDashboardUrl, 'Copuloo', 'user_nonce')).'&dashboardpage=addresses&addressidentity='.esc_html($copuloo_record->id).'" class="btn border btn-sm btn-active-light-primary">Edit</a></td></tr>';
                }
                echo '</tbody>';
                echo '</table>';
                echo '</div>';
              }
              else if (isset($_GET['addressidentity']))
              {
                echo '<form action="'.esc_url( admin_url("admin-post.php") ).'" method="post" class="form">';
                echo '<input type="hidden" name="action" value="copuloo_update_address"></input>';
                echo '<input type="hidden" name="addressidentity" value="'.esc_html($copuloo_opened_item[0]->id).'"></input>';
                echo '<input type="hidden" name="twilio_address_sid" value="'.esc_html($copuloo_opened_item[0]->twilio_address_sid).'"></input>';
                echo esc_html(wp_nonce_field( 'Copuloo', 'user_nonce' ));
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">Friendly Name</label>';
                echo '<div class="col-lg-8">';
                echo '<input required type="text" maxlength="64" value="'.esc_html($copuloo_opened_item[0]->friendly_name).'" class="form-control form-control form-control-solid" name="friendly" placeholder="Friendly Name">';
                echo '</div>';
                echo '</div>';
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">Customer</label>';
                echo '<div class="col-lg-8">';
                echo '<input required type="text" value="'.esc_html($copuloo_opened_item[0]->customer).'" class="form-control form-control form-control-solid" name="customer" placeholder="Customer or business name">';
                echo '</div>';
                echo '</div>';
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">Country (Cannot be changed)</label>';
                echo '<div class="col-lg-8">';
                echo '<input disabled type="text" value="'.esc_html($copuloo_opened_item[0]->country).'" class="form-control form-control form-control-solid" placeholder="Country">';
                echo '</div>';
                echo '</div>';
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">Address Line 1</label>';
                echo '<div class="col-lg-8">';
                echo '<input required type="text" maxlength="100" value="'.esc_html($copuloo_opened_item[0]->line1).'" class="form-control form-control form-control-solid" name="line1" placeholder="Address Line 1">';
                echo '</div>';
                echo '</div>';
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">Address Line 2</label>';
                echo '<div class="col-lg-8">';
                echo '<input type="text" maxlength="100" value="'.esc_html($copuloo_opened_item[0]->line2).'" class="form-control form-control form-control-solid" name="line2" placeholder="Address Line 2">';
                echo '</div>';
                echo '</div>';
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">City</label>';
                echo '<div class="col-lg-8">';
                echo '<input required type="text" maxlength="100" value="'.esc_html($copuloo_opened_item[0]->city).'" class="form-control form-control form-control-solid" name="city" placeholder="City">';
                echo '</div>';
                echo '</div>';
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">State</label>';
                echo '<div class="col-lg-8">';
                echo '<input required type="text" maxlength="100" value="'.esc_html($copuloo_opened_item[0]->state).'" class="form-control form-control form-control-solid" name="state" placeholder="State">';
                echo '</div>';
                echo '</div>';
                echo '<div class="row mb-6">';
                echo '<label class="col-lg-4 col-form-label fw-semibold fs-6">Zip Code</label>';
                echo '<div class="col-lg-8">';
                echo '<input required type="text" maxlength="100" value="'.esc_html($copuloo_opened_item[0]->zip).'" class="form-control form-control form-control-solid" name="zip" placeholder="Zip Code">';
                echo '</div>';
                echo '</div>';
                echo '<div class="separator mb-6"></div>';
                echo '<div class="d-flex justify-content-end">';
                echo '<button type="button" class="btn btn-danger me-3" data-bs-toggle="modal" data-bs-target="#remove_address">Remove</button>';
                echo '<button type="submit" class="btn btn-primary">Save</button>';
                echo '</div>';
                echo '</form>';
              }
              ?>
            </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_create_address"></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">Create an Address</h1>
            <div class="text-muted fw-semibold fs-5">This address will be saved on the addresses section and can be assigned to any phone number with an address requirement.</div>
          </div>

          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">Country</label>
            <div class="col-lg-8">
              <select required name="countrycode" aria-label="Select a Country Code" data-placeholder="Select A Country" 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>
          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">Customer or business name</label>
            <div class="col-lg-8">
              <input required type="text" maxlength="100" value="" class="form-control form-control form-control-solid" name="customer" placeholder="Name">
            </div>
          </div>
          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">Friendly Name</label>
            <div class="col-lg-8">
              <input required type="text" maxlength="64" value="" class="form-control form-control form-control-solid" name="friendly" placeholder="Friendly Name">
            </div>
          </div>
          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">Address Line 1</label>
            <div class="col-lg-8">
              <input required type="text" maxlength="100" value="" class="form-control form-control form-control-solid" name="line1" placeholder="Address Line 1">
            </div>
          </div>
          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">Address Line 2</label>
            <div class="col-lg-8">
              <input type="text" maxlength="100" value="" class="form-control form-control form-control-solid" name="line2" placeholder="Address Line 2">
            </div>
          </div>
          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">City</label>
            <div class="col-lg-8">
              <input required type="text" maxlength="100" value="" class="form-control form-control form-control-solid" name="city" placeholder="City">
            </div>
          </div>
          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">State</label>
            <div class="col-lg-8">
              <input required type="text" maxlength="100" value="" class="form-control form-control form-control-solid" name="state" placeholder="State">
            </div>
          </div>
          <div class="row mb-6">
            <label class="col-lg-4 col-form-label fw-semibold fs-6">Zip Code</label>
            <div class="col-lg-8">
              <input required type="text" maxlength="100" value="" class="form-control form-control form-control-solid" name="zip" placeholder="Zip Code">
            </div>
          </div>
          <div class="text-muted fw-semibold fs-5">The information above must be accurate. Twilio will process the above information as identity verification.</div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
            <button type='submit' class='btn btn-primary'>Create</button>
        </div>
      </div>
    </div>
  </div>
</form>

<div class="modal fade" tabindex="-1" id="remove_address">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header pb-0 border-0 d-flex justify-content-end">
        <div class="btn btn-icon btn-sm btn-active-light-primary ms-2" data-bs-dismiss="modal" aria-label="Close">
          <i class="fs-1">
            <span class="fas fa-times"></span>
          </i>
        </div>
      </div>
      <div class="modal-body">
        <div class="text-center mb-5">
          <h1 class="d-flex justify-content-center align-items-center mb-3">Remove Address?</h1>
          <div class="text-muted fw-semibold fs-5">This action cannot be undon and the address will be deleted forever.</div>
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
        <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_remove_address"></input>
          <input type="hidden" name="addressidentity" value="<?php echo esc_html($copuloo_opened_item[0]->id); ?>">
          <input type="hidden" name="twilio_address_sid" value="<?php echo esc_html($copuloo_opened_item[0]->twilio_address_sid); ?>"></input>
          </input>
          <button type="submit" class="btn btn-danger">Remove</button>
        </form>
      </div>
    </div>
  </div>
</div>