<?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="d-flex flex-wrap flex-stack pb-7">
    <div class="d-flex flex-wrap align-items-center my-1">
      <div class="d-flex align-items-center position-relative my-1">
        <form action="<?php echo esc_url(admin_url('admin.php?page=copuloo_dashboard')); ?>" method="get" class="form">
          <input type="hidden" name="page" value="copuloo_dashboard"></input>
          <input type="hidden" name="dashboardpage" value="contacts"></input>
          <input id="listOrBlock" type="hidden" name="list"></input>
          <input type="hidden" name="user_nonce" value="<?php echo esc_attr(sanitize_text_field(wp_unslash($_GET['user_nonce']))); ?>"></input>
              <div class="d-flex align-items-center position-relative">
                <i class="fs-3 text-gray-500 position-absolute top-50 ms-5 translate-middle-y"><span class="fas fa-search"></span></i>
                <input autocomplete="off" value="<?php echo esc_attr(sanitize_text_field(wp_unslash($_GET['search'] ?? ''))); ?>" type="search" placeholder="Search Contacts" class="ps-13 form-control form-control form-control-solid bg-light border-secondary" name="search">
              </div>
        </form>
      </div>
    </div>
    <div class="d-flex flex-wrap my-1">
      <ul class="nav nav-pills me-6 mb-2 mb-sm-0" role="tablist">
        <li class="nav-item m-0" role="presentation">
          <a onclick="document.getElementById('listOrBlock').name = 'list';" class="btn btn-sm btn-icon btn-light btn-color-muted btn-active-primary me-3 <?php if (isset($_GET['list']) || !isset($_GET['block'])) { echo 'active'; } ?>" data-bs-toggle="tab" href="#contacts_list" aria-selected="true" role="tab">
            <i class="fs-2"><span class="fas fa-list"></span></i>
          </a>
        </li>
        <li class="nav-item m-0" role="presentation">
          <a onclick="document.getElementById('listOrBlock').name = 'block';" class="btn btn-sm btn-icon btn-light btn-color-muted btn-active-primary <?php if (isset($_GET['block'])) { echo 'active'; } ?>" data-bs-toggle="tab" href="#contacts_block" aria-selected="false" role="tab" tabindex="-1">
            <i class="fs-2"><span class="fas fa-th-large"></span></i>
          </a>
        </li>
      </ul>
    </div>
  </div>

  <div class="tab-content">
    <div id="contacts_list" class="tab-pane fade <?php if (isset($_GET['list']) || !isset($_GET['block'])) { echo 'active show'; } ?>" role="tabpanel">
      <div class="card card-flush">
        <div class="card-body pt-0">
          <div class="table-responsive">
            <div id="project_users_table_wrapper" class="dataTables_wrapper dt-bootstrap4 no-footer">
              <div class="table-responsive">
                <table id="project_users_table" class="table table-row-bordered table-row-dashed gy-4 align-middle fw-bold dataTable no-footer">
                <thead class="fs-7 text-gray-400 text-uppercase">
                  <tr>
                    <th class="min-w-250px sorting" tabindex="0" rowspan="1" colspan="1" style="width: 0px;">Contact</th>
                    <th class="min-w-150px sorting" tabindex="0" rowspan="1" colspan="1" style="width: 0px;">Company</th>
                    <th class="min-w-180px sorting" tabindex="0" rowspan="1" colspan="1" style="width: 0px;">Status</th>
                    <th class="min-w-50px text-end sorting_disabled" rowspan="1" colspan="1" aria-label="Details" style="width: 0px;">Details</th>
                  </tr>
                </thead>
                <tbody class="fs-6">
                  <?php
                    $copuloo_table = $wpdb->prefix . 'copuloo_contacts';
                    $copuloo_user_id = get_current_user_id();
                    $search = isset($_GET['search']) ? '%' . $wpdb->esc_like(sanitize_text_field(wp_unslash($_GET['search']))) . '%' : '';

                    // Handle search
                    if (strlen($search) > 2) {
                        // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
                        $copuloo_opened_item = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_contacts WHERE user = %d AND name LIKE %s LIMIT 25",$copuloo_user_id,$search)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                    } else {
                      // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
                      $copuloo_opened_item = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_contacts WHERE user = %d LIMIT %d, %d",$copuloo_user_id,$copuloo_limit_offset,$copuloo_limit_count)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                    }
                  ?>
                  <?php if (!empty($copuloo_opened_item)): ?>
                  <?php foreach ($copuloo_opened_item as $copuloo_item): ?>
                    <?php
                      $copuloo_bgicon = 'light-primary';
                      $copuloo_texticon = 'primary';
                      switch ((int) $copuloo_item->icon) {
                        case 2: $copuloo_bgicon = 'light-success'; $copuloo_texticon = 'success'; break;
                        case 3: $copuloo_bgicon = 'light-info'; $copuloo_texticon = 'info'; break;
                        case 4: $copuloo_bgicon = 'light-danger'; $copuloo_texticon = 'danger'; break;
                        case 5: $copuloo_bgicon = 'light-warning'; $copuloo_texticon = 'warning'; break;
                        case 6: $copuloo_bgicon = 'secondary'; $copuloo_texticon = 'dark'; break;
                      }

                      $copuloo_contactUrl = esc_url(add_query_arg([
                        'dashboardpage' => 'contacts',
                        'contact' => $copuloo_item->id,
                        'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
                      ], $copulooDashboardUrl));
                    ?>
                    <tr>
                      <td>
                        <div class="d-flex align-items-center">
                          <div class="symbol symbol-40px symbol-circle me-5">
                            <span class="symbol-label bg-<?php echo esc_attr($copuloo_bgicon); ?> text-<?php echo esc_attr($copuloo_texticon); ?> fs-6 fw-bolder">
                              <?php echo esc_html(ucfirst(substr($copuloo_item->name, 0, 1))); ?>
                            </span>
                          </div>
                          <div class="d-flex flex-column justify-content-center">
                            <a href="<?php echo esc_url($copuloo_contactUrl); ?>" class="mb-1 text-gray-800 text-hover-primary">
                              <?php echo esc_html($copuloo_item->name); ?>
                            </a>
                            <div class="fw-semibold fs-6 text-gray-400"><?php echo esc_html(copuloo_formatNumber($copuloo_item->phone)); ?></div>
                          </div>
                        </div>
                      </td>
                      <td><?php echo esc_html($copuloo_item->company); ?></td>
                      <td>
                        <?php if ($copuloo_item->blocked == 1): ?>
                          <span class="badge badge-light-danger fw-bold px-4 py-3">Blocked</span>
                        <?php elseif (!empty($copuloo_item->status)): ?>
                          <span class="badge badge-light-<?php echo esc_attr($copuloo_item->statuscolor ?? 'primary'); ?> fw-bold px-4 py-3">
                            <?php echo esc_html($copuloo_item->status); ?>
                          </span>
                        <?php else: ?>
                          <span class="badge badge-light-success fw-bold px-4 py-3">Normal</span>
                        <?php endif; ?>
                      </td>
                      <td class="text-end">
                        <a href="<?php echo esc_url($copuloo_contactUrl); ?>" class="btn btn-light btn-sm">View</a>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php else: ?>
                  <tr>
                    <td>
                      <div class="d-flex align-items-center">
                        <div class="d-flex flex-column justify-content-center">
                          <p class="mb-1 text-gray-800">No Contacts</p>
                          <div class="fw-semibold fs-6 text-gray-400">Contacts will appear here</div>
                        </div>
                      </div>
                    </td>
                    <td>-</td>
                    <td>-</td>
                    <td class="text-end">-</td>
                  </tr>
                <?php endif; ?>
              </tbody>
            </table>
          </div>
        </div>
      </div>
      <div class="separator mb-6"></div>
      <div class="d-flex align-items-center justify-content-center justify-content-md-end">
        <?php if ($copuloo_resultsPage > 1 && strlen($search) <= 2): ?>
        <?php
          $copuloo_prevUrl = esc_url(add_query_arg([
            'dashboardpage' => 'contacts',
            'resultsPage'   => $copuloo_resultsPage - 1,
            'list'          => '',
            'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
          ], $copulooDashboardUrl));
        ?>
        <a href="<?php echo esc_url($copuloo_prevUrl); ?>" class="btn btn-light btn-sm me-3">
          <span class="menu-bullet">
            <span class="fa fa-arrow-left"></span>
          </span>
        </a>
      <?php endif; ?>

      <span class="btn btn-bg-primary btn-sm me-3 text-white"><?php echo esc_html($copuloo_resultsPage); ?></span>

      <?php if (isset($copuloo_opened_item) && ($copuloo_resultsPage * 12) < $copuloo_numberOfContacts && strlen($search) <= 2): ?>
        <?php
          $copuloo_nextUrl = add_query_arg([
            'dashboardpage' => 'contacts',
            'resultsPage'   => $copuloo_resultsPage + 1,
            'list'          => '',
            'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
          ], $copulooDashboardUrl);
        ?>
        <a href="<?php echo esc_url($copuloo_nextUrl); ?>" class="btn btn-light btn-sm me-3">
          <span class="menu-bullet">
            <span class="fa fa-arrow-right"></span>
          </span>
        </a>
      <?php endif; ?>
      </div>
      </div>
      </div>
    </div>
    <div id="contacts_block" class="tab-pane fade <?php if (isset($_GET['block'])) { echo 'active show'; } ?>" role="tabpanel">
      <div class="row g-6 g-xl-9">
        <?php
          if (!empty($copuloo_opened_item)) {
              foreach ($copuloo_opened_item as $copuloo_item) {
                  $copuloo_bgicon = "light-primary";
                  $copuloo_texticon = "primary";

                  switch ($copuloo_item->icon) {
                      case 2: $copuloo_bgicon = "light-success"; $copuloo_texticon = "success"; break;
                      case 3: $copuloo_bgicon = "light-info"; $copuloo_texticon = "info"; break;
                      case 4: $copuloo_bgicon = "light-danger"; $copuloo_texticon = "danger"; break;
                      case 5: $copuloo_bgicon = "light-warning"; $copuloo_texticon = "warning"; break;
                      case 6: $copuloo_bgicon = "secondary"; $copuloo_texticon = "dark"; break;
                  }

                  echo '<div class="col-md-6 col-xxl-4"><div class="card"><div class="card-body d-flex flex-center flex-column pt-12 p-9">';
                  echo '<div class="symbol symbol-65px symbol-circle mb-5"><span class="symbol-label fs-2x fw-semibold text-' . esc_attr($copuloo_texticon) . ' bg-' . esc_attr($copuloo_bgicon) . '">' . esc_html(ucfirst(substr($copuloo_item->name, 0, 1))) . '</span></div>';
                  echo '<a href="' . esc_url(wp_nonce_url($copulooDashboardUrl.'&dashboardpage=contacts&contact='.$copuloo_item->id, 'Copuloo', 'user_nonce')) . '" class="fs-4 text-gray-800 text-hover-primary fw-bold mb-0">' . esc_html($copuloo_item->name) . '</a>';
                  echo '<div class="fw-semibold text-gray-400 mb-6">' . esc_html(copuloo_formatNumber($copuloo_item->phone)) . '</div>';

                  if ($copuloo_item->blocked == 1) {
                      echo '<span class="badge badge-light-danger fw-bold px-4 py-3">Blocked</span>';
                  } elseif (!empty($copuloo_item->status)) {
                      $copuloo_status_color = !empty($copuloo_item->statuscolor) ? esc_attr($copuloo_item->statuscolor) : 'primary';
                      echo '<span class="badge badge-light-' . esc_html($copuloo_status_color) . ' fw-bold px-4 py-3">' . esc_html($copuloo_item->status) . '</span>';
                  } else {
                      echo '<span class="badge badge-light-success fw-bold px-4 py-3">Normal</span>';
                  }

                  echo '</div></div></div>';
              }
          } else {
              echo '<div class="col-md-6 col-xxl-4"><div class="card"><div class="card-body d-flex flex-center flex-column pt-12 p-9">';
              echo '<p class="fs-4 text-gray-800 fw-bold mb-0">No Contacts</p><div class="fw-semibold text-gray-400 mb-6">Contacts will appear here</div>';
              echo '</div></div></div>';
          }
        ?>
      </div>
        <div class="d-flex align-items-center justify-content-center justify-content-md-end pt-10">
          <?php if ($copuloo_resultsPage > 1 && strlen($search) <= 2): ?>
            <a href="<?php echo esc_url(add_query_arg([
                'dashboardpage' => 'contacts',
                'resultsPage' => $copuloo_resultsPage - 1,
                'block' => '',
                'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
            ], $copulooDashboardUrl)); ?>" class="btn btn-secondary btn-sm me-3">
                <span class="menu-bullet">
                    <span class="fa fa-arrow-left"></span>
                </span>
            </a>
          <?php endif; ?>
          <span class="btn btn-bg-primary btn-sm me-3 text-white"><?php echo esc_html($copuloo_resultsPage); ?></span>
          <?php if (isset($copuloo_opened_item) && ($copuloo_resultsPage * 12) < $copuloo_numberOfContacts && strlen($search) <= 2): ?>
            <a href="<?php echo esc_url(add_query_arg([
                'dashboardpage' => 'contacts',
                'resultsPage' => $copuloo_resultsPage + 1,
                'block' => '',
                'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
            ], $copulooDashboardUrl)); ?>" class="btn btn-secondary btn-sm me-3">
                <span class="menu-bullet">
                    <span class="fa fa-arrow-right"></span>
                </span>
            </a>
          <?php endif; ?>
        </div>
    </div>
</div>
