<?php if ( ! defined( 'ABSPATH' ) ) exit; ?>
<?php if ( !isset($_GET['user_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['user_nonce'])), 'DialBunny') ) { 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=dialbunny_dashboard')); ?>" method="get" class="form">
          <input type="hidden" name="page" value="dialbunny_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
                    $dialbunny_table = $wpdb->prefix . 'dialbunny_contacts';
                    $dialbunny_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.
                        $dialbunny_opened_item = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dialbunny_contacts WHERE user = %d AND name LIKE %s LIMIT 25",$dialbunny_user_id,$search)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                    } else {
                      // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
                      $dialbunny_opened_item = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dialbunny_contacts WHERE user = %d LIMIT %d, %d",$dialbunny_user_id,$dialbunny_limit_offset,$dialbunny_limit_count)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                    }
                  ?>
                  <?php if (!empty($dialbunny_opened_item)): ?>
                  <?php foreach ($dialbunny_opened_item as $dialbunny_item): ?>
                    <?php
                      $dialbunny_bgicon = 'light-primary';
                      $dialbunny_texticon = 'primary';
                      switch ((int) $dialbunny_item->icon) {
                        case 2: $dialbunny_bgicon = 'light-success'; $dialbunny_texticon = 'success'; break;
                        case 3: $dialbunny_bgicon = 'light-info'; $dialbunny_texticon = 'info'; break;
                        case 4: $dialbunny_bgicon = 'light-danger'; $dialbunny_texticon = 'danger'; break;
                        case 5: $dialbunny_bgicon = 'light-warning'; $dialbunny_texticon = 'warning'; break;
                        case 6: $dialbunny_bgicon = 'secondary'; $dialbunny_texticon = 'dark'; break;
                      }

                      $dialbunny_contactUrl = esc_url(add_query_arg([
                        'dashboardpage' => 'contacts',
                        'contact' => $dialbunny_item->id,
                        'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
                      ], $dialbunnyDashboardUrl));
                    ?>
                    <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($dialbunny_bgicon); ?> text-<?php echo esc_attr($dialbunny_texticon); ?> fs-6 fw-bolder">
                              <?php echo esc_html(ucfirst(substr($dialbunny_item->name, 0, 1))); ?>
                            </span>
                          </div>
                          <div class="d-flex flex-column justify-content-center">
                            <a href="<?php echo esc_url($dialbunny_contactUrl); ?>" class="mb-1 text-gray-800 text-hover-primary">
                              <?php echo esc_html($dialbunny_item->name); ?>
                            </a>
                            <div class="fw-semibold fs-6 text-gray-400"><?php echo esc_html(dialbunny_formatNumber($dialbunny_item->phone)); ?></div>
                          </div>
                        </div>
                      </td>
                      <td><?php echo esc_html($dialbunny_item->company); ?></td>
                      <td>
                        <?php if ($dialbunny_item->blocked == 1): ?>
                          <span class="badge badge-light-danger fw-bold px-4 py-3">Blocked</span>
                        <?php elseif (!empty($dialbunny_item->status)): ?>
                          <span class="badge badge-light-<?php echo esc_attr($dialbunny_item->statuscolor ?? 'primary'); ?> fw-bold px-4 py-3">
                            <?php echo esc_html($dialbunny_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($dialbunny_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 ($dialbunny_resultsPage > 1 && strlen($search) <= 2): ?>
        <?php
          $dialbunny_prevUrl = esc_url(add_query_arg([
            'dashboardpage' => 'contacts',
            'resultsPage'   => $dialbunny_resultsPage - 1,
            'list'          => '',
            'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
          ], $dialbunnyDashboardUrl));
        ?>
        <a href="<?php echo esc_url($dialbunny_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($dialbunny_resultsPage); ?></span>

      <?php if (isset($dialbunny_opened_item) && ($dialbunny_resultsPage * 12) < $numberOfContacts && strlen($search) <= 2): ?>
        <?php
          $dialbunny_nextUrl = add_query_arg([
            'dashboardpage' => 'contacts',
            'resultsPage'   => $dialbunny_resultsPage + 1,
            'list'          => '',
            'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
          ], $dialbunnyDashboardUrl);
        ?>
        <a href="<?php echo esc_url($dialbunny_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($dialbunny_opened_item)) {
              foreach ($dialbunny_opened_item as $dialbunny_item) {
                  $dialbunny_bgicon = "light-primary";
                  $dialbunny_texticon = "primary";

                  switch ($dialbunny_item->icon) {
                      case 2: $dialbunny_bgicon = "light-success"; $dialbunny_texticon = "success"; break;
                      case 3: $dialbunny_bgicon = "light-info"; $dialbunny_texticon = "info"; break;
                      case 4: $dialbunny_bgicon = "light-danger"; $dialbunny_texticon = "danger"; break;
                      case 5: $dialbunny_bgicon = "light-warning"; $dialbunny_texticon = "warning"; break;
                      case 6: $dialbunny_bgicon = "secondary"; $dialbunny_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($dialbunny_texticon) . ' bg-' . esc_attr($dialbunny_bgicon) . '">' . esc_html(ucfirst(substr($dialbunny_item->name, 0, 1))) . '</span></div>';
                  echo '<a href="' . esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=contacts&contact='.$dialbunny_item->id, 'DialBunny', 'user_nonce')) . '" class="fs-4 text-gray-800 text-hover-primary fw-bold mb-0">' . esc_html($dialbunny_item->name) . '</a>';
                  echo '<div class="fw-semibold text-gray-400 mb-6">' . esc_html(dialbunny_formatNumber($dialbunny_item->phone)) . '</div>';

                  if ($dialbunny_item->blocked == 1) {
                      echo '<span class="badge badge-light-danger fw-bold px-4 py-3">Blocked</span>';
                  } elseif (!empty($dialbunny_item->status)) {
                      $dialbunny_status_color = !empty($dialbunny_item->statuscolor) ? esc_attr($dialbunny_item->statuscolor) : 'primary';
                      echo '<span class="badge badge-light-' . esc_html($dialbunny_status_color) . ' fw-bold px-4 py-3">' . esc_html($dialbunny_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 ($dialbunny_resultsPage > 1 && strlen($search) <= 2): ?>
            <a href="<?php echo esc_url(add_query_arg([
                'dashboardpage' => 'contacts',
                'resultsPage' => $dialbunny_resultsPage - 1,
                'block' => '',
                'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
            ], $dialbunnyDashboardUrl)); ?>" 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($dialbunny_resultsPage); ?></span>
          <?php if (isset($dialbunny_opened_item) && ($dialbunny_resultsPage * 12) < $numberOfContacts && strlen($search) <= 2): ?>
            <a href="<?php echo esc_url(add_query_arg([
                'dashboardpage' => 'contacts',
                'resultsPage' => $dialbunny_resultsPage + 1,
                'block' => '',
                'user_nonce'    => sanitize_text_field(wp_unslash($_GET['user_nonce']))
            ], $dialbunnyDashboardUrl)); ?>" 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>
