<?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="messages"></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 Messages" 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;">Message</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
                // Check to see if user wants to search or not - Requires mysql 8.0 or higher
                $dialbunny_user_id = get_current_user_id();
                $dialbunny_managed_number = $dialbunny_phone_details[0]->managed_number;
                $search = isset($_GET['search']) ? '%' . $wpdb->esc_like(sanitize_text_field(wp_unslash($_GET['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 *, ROW_NUMBER() OVER (PARTITION BY from_number, to_number ORDER BY created_at DESC) AS rn FROM {$wpdb->prefix}dialbunny_messages WHERE user = %d AND (from_number = %s OR to_number = %s) AND message LIKE %s LIMIT 25", $dialbunny_user_id, $dialbunny_managed_number, $dialbunny_managed_number, $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 (SELECT *, ROW_NUMBER() OVER (PARTITION BY LEAST(from_number, to_number), GREATEST(from_number, to_number) ORDER BY created_at DESC) AS rn FROM {$wpdb->prefix}dialbunny_messages WHERE user = %d AND (from_number = %s OR to_number = %s)) AS ranked_messages WHERE rn = 1 ORDER BY created_at DESC LIMIT %d,%d", $dialbunny_user_id, $dialbunny_managed_number,$dialbunny_managed_number,$dialbunny_limit_offset,$dialbunny_limit_count)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                }
                  // check to see if the user has a managed number
                  if (isset($dialbunny_phone_details[0]->managed_number) && isset($dialbunny_phone_details[0]->managed_number_code))
                  {
                    foreach ($dialbunny_opened_item as $dialbunny_item)
                    {
                      // Check to see if contact exists
                      $dialbunny_phoneNumberCountryCode;
                      $dialbunny_phoneNumber;
                      if ($dialbunny_phone_details[0]->managed_number_code == $dialbunny_item->from_countrycode && $dialbunny_phone_details[0]->managed_number == $dialbunny_item->from_number) { $dialbunny_phoneNumberCountryCode = $dialbunny_item->to_countrycode; $dialbunny_phoneNumber = $dialbunny_item->to_number; }
                      else { $dialbunny_phoneNumberCountryCode = $dialbunny_item->from_countrycode; $dialbunny_phoneNumber = $dialbunny_item->from_number; }
                      // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
                      $dialbunny_contact = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dialbunny_contacts WHERE user = %d AND countrycode = %s AND phone = %s LIMIT 1",wp_get_current_user()->ID,$dialbunny_phoneNumberCountryCode,$dialbunny_phoneNumber)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                      if ($dialbunny_contact == null)
                      {
                        $dialbunny_displayName = dialbunny_formatNumber($dialbunny_phoneNumber);
                        if ($dialbunny_item->from_number == $dialbunny_phone_details[0]->managed_number && strlen($search) > 2) { $dialbunny_displayName = 'You'; }
                        echo '<tr>';
                        echo '<td><div class="d-flex align-items-center">';
                        echo    '<div class="symbol symbol-40px symbol-circle me-5">';
                        echo      '<span class="symbol-label bg-secondary text-secondary fs-6 fw-bolder"></span>';
                        echo    '</div>';
                        echo '<div class="d-flex flex-column justify-content-center"><a href="'.esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=messages&phone='.esc_html($dialbunny_phoneNumber).'&countrycode='.esc_html($dialbunny_phoneNumberCountryCode), 'DialBunny', 'user_nonce')).'" class="mb-1 text-gray-800 text-hover-primary">'.esc_html($dialbunny_displayName).'</a><div class="fw-semibold fs-6 text-gray-400">Not in contacts</div></div></div></td>';
                        echo '<td>'.esc_html(mb_strimwidth($dialbunny_item->message, 0, 25, "...")).'</td>';
                        if ($dialbunny_item->reading == 0) { echo '<td><span class="badge badge-light-primary fw-bold px-4 py-3">Unread</span></td>'; }
                        else { echo '<td><span class="badge badge-light-success fw-bold px-4 py-3">Read</span></td>'; }
                        echo '<td class="text-end"><a href="'.esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=messages&phone='.esc_html($dialbunny_phoneNumber).'&countrycode='.esc_html($dialbunny_phoneNumberCountryCode), 'DialBunny', 'user_nonce')).'" class="btn btn-light btn-sm">View</a></td>';
                        echo '</tr>';
                      }
                      else
                      {
                        $dialbunny_displayName = $dialbunny_contact[0]->name;
                        if ($dialbunny_item->from_number == $dialbunny_phone_details[0]->managed_number && strlen($search) > 2) { $dialbunny_displayName = 'You'; }
                        $dialbunny_bgicon = "light-primary";
                        $dialbunny_texticon = "primary";
                        if ($dialbunny_contact[0]->icon == 2) { $dialbunny_bgicon = "light-success"; $dialbunny_texticon = "success"; }
                        if ($dialbunny_contact[0]->icon == 3) { $dialbunny_bgicon = "light-info"; $dialbunny_texticon = "info"; }
                        if ($dialbunny_contact[0]->icon == 4) { $dialbunny_bgicon = "light-danger"; $dialbunny_texticon = "danger"; }
                        if ($dialbunny_contact[0]->icon == 5) { $dialbunny_bgicon = "light-warning"; $dialbunny_texticon = "warning"; }
                        if ($dialbunny_contact[0]->icon == 6) { $dialbunny_bgicon = "secondary"; $dialbunny_texticon = "dark"; }
                        echo '<tr>';
                        echo '<td><div class="d-flex align-items-center">';
                        echo    '<div class="symbol symbol-40px symbol-circle me-5">';
                        echo      '<span class="symbol-label bg-'.esc_html($dialbunny_bgicon).' text-'.esc_html($dialbunny_texticon).' fs-6 fw-bolder">'.esc_html(ucfirst(substr($dialbunny_contact[0]->name, 0, 1))).'</span>';
                        echo    '</div>';
                        echo '<div class="d-flex flex-column justify-content-center"><a href="'.esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=messages&phone='.esc_html($dialbunny_phoneNumber).'&countrycode='.esc_html($dialbunny_phoneNumberCountryCode), 'DialBunny', 'user_nonce')).'" class="mb-1 text-gray-800 text-hover-primary">'.esc_html($dialbunny_displayName).'</a><div class="fw-semibold fs-6 text-gray-400">'.esc_html(dialbunny_formatNumber($dialbunny_phoneNumber)).'</div></div></div></td>';
                        echo '<td>'.esc_html(mb_strimwidth($dialbunny_item->message, 0, 25, "...")).'</td>';
                        if ($dialbunny_item->reading == 0) { echo '<td><span class="badge badge-light-primary fw-bold px-4 py-3">Unread</span></td>'; }
                        else { echo '<td><span class="badge badge-light-success fw-bold px-4 py-3">Read</span></td>'; }
                        echo '<td class="text-end"><a href="'.esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=messages&phone='.esc_html($dialbunny_phoneNumber).'&countrycode='.esc_html($dialbunny_phoneNumberCountryCode), 'DialBunny', 'user_nonce')).'" class="btn btn-light btn-sm">View</a></td>';
                        echo '</tr>';
                      }
                    }
                    if ($dialbunny_opened_item == null)
                    {
                      echo '<tr>';
                      echo '<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 Messages</p><div class="fw-semibold fs-6 text-gray-400">Messages will appear here</div></div></div></td>';
                      echo '<td>-</td>';
                      echo '<td>-</td>';
                      echo '<td class="text-end">-</td>';
                      echo '</tr>';
                    }
                  }
                  else
                  {
                    echo '<tr>';
                    echo '<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 Messages</p><div class="fw-semibold fs-6 text-gray-400">Messages will appear here</div></div></div></td>';
                    echo '<td>-</td>';
                    echo '<td>-</td>';
                    echo '<td class="text-end">-</td>';
                    echo '</tr>';
                  }
                ?>
              </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)
        {
          echo '<a href="' . esc_url(wp_nonce_url($dialbunnyDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($dialbunny_resultsPage - 1), 'DialBunny', 'user_nonce')) .'&list" 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>';
        }
        ?>
        <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) < $dialbunny_numberOfMessages && strlen($search) <= 2)
        {
          echo '<a href="' . esc_url(wp_nonce_url($dialbunnyDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($dialbunny_resultsPage + 1), 'DialBunny', 'user_nonce')) .'&list" 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>
  </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
      // check to see if the user has a managed number
      if (isset($dialbunny_phone_details[0]->managed_number) && isset($dialbunny_phone_details[0]->managed_number_code))
      {
          // Foreach message
          foreach ($dialbunny_opened_item as $dialbunny_item)
          {
            // Check to see if contact exists and make sure the from number does not equal the managed number
            $dialbunny_phoneNumberCountryCode;
            $dialbunny_phoneNumber;
            if ($dialbunny_phone_details[0]->managed_number_code == $dialbunny_item->from_countrycode && $dialbunny_phone_details[0]->managed_number == $dialbunny_item->from_number) { $dialbunny_phoneNumberCountryCode = $dialbunny_item->to_countrycode; $dialbunny_phoneNumber = $dialbunny_item->to_number; }
            else { $dialbunny_phoneNumberCountryCode = $dialbunny_item->from_countrycode; $dialbunny_phoneNumber = $dialbunny_item->from_number; }
            // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
            $dialbunny_contact = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dialbunny_contacts WHERE user = %d AND countrycode = %s AND phone = %s LIMIT 1",wp_get_current_user()->ID,$dialbunny_phoneNumberCountryCode,$dialbunny_phoneNumber)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            if ($dialbunny_contact == null)
            {
              $dialbunny_displayName = dialbunny_formatNumber($dialbunny_phoneNumber);
              if ($dialbunny_item->from_number == $dialbunny_phone_details[0]->managed_number && strlen($search) > 2) { $dialbunny_displayName = 'You'; }
              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-secondary bg-secondary"></span></div>';
              echo '<a href="'.esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=messages&phone='.esc_html($dialbunny_phoneNumber).'&countrycode='.esc_html($dialbunny_phoneNumberCountryCode), 'DialBunny', 'user_nonce')).'" class="fs-4 text-gray-800 text-hover-primary fw-bold mb-0">'.esc_html($dialbunny_displayName).'</a><div class="fw-semibold text-gray-400 mb-6">Not in contacts</div>';
              if ($dialbunny_item->reading == 0) { echo '<span class="badge badge-light-primary fw-bold px-4 py-3 mb-2">Unread</span>'; }
              else { echo '<span class="badge badge-light-success fw-bold px-4 py-3 mb-2">Read</span>'; }
              echo '<div class="p-5 badge badge-light-secondary text-gray-900 fw-semibold mw-lg-400px text-start" data-element="message-text">'.esc_html(mb_strimwidth($dialbunny_item->message, 0, 25, "...")).'</div>';
              echo '</div></div></div>';
            }
            else
            {
              $dialbunny_displayName = $dialbunny_contact[0]->name;
              if ($dialbunny_item->from_number == $dialbunny_phone_details[0]->managed_number && strlen($search) > 2) { $dialbunny_displayName = 'You'; }
              $dialbunny_bgicon = "light-primary";
              $dialbunny_texticon = "primary";
              if ($dialbunny_contact[0]->icon == 2) { $dialbunny_bgicon = "light-success"; $dialbunny_texticon = "success"; }
              if ($dialbunny_contact[0]->icon == 3) { $dialbunny_bgicon = "light-info"; $dialbunny_texticon = "info"; }
              if ($dialbunny_contact[0]->icon == 4) { $dialbunny_bgicon = "light-danger"; $dialbunny_texticon = "danger"; }
              if ($dialbunny_contact[0]->icon == 5) { $dialbunny_bgicon = "light-warning"; $dialbunny_texticon = "warning"; }
              if ($dialbunny_contact[0]->icon == 6) { $dialbunny_bgicon = "secondary"; $dialbunny_texticon = "dark"; }
              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_html($dialbunny_texticon).' bg-'.esc_html($dialbunny_bgicon).'">'.esc_html(ucfirst(substr($dialbunny_contact[0]->name, 0, 1))).'</span></div>';
              echo '<a href="'.esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=messages&phone='.esc_html($dialbunny_phoneNumber).'&countrycode='.esc_html($dialbunny_phoneNumberCountryCode), 'DialBunny', 'user_nonce')).'" class="fs-4 text-gray-800 text-hover-primary fw-bold mb-0">'.esc_html($dialbunny_displayName).'</a><div class="fw-semibold text-gray-400 mb-6">'.esc_html(dialbunny_formatNumber($dialbunny_phoneNumber)).'</div>';
              if ($dialbunny_item->reading == 0) { echo '<span class="badge badge-light-primary fw-bold px-4 py-3 mb-2">Unread</span>'; }
              else { echo '<span class="badge badge-light-success fw-bold px-4 py-3 mb-2">Read</span>'; }
              echo '<div class="p-5 badge badge-light-secondary text-gray-900 fw-semibold mw-lg-400px text-start" data-element="message-text">'.esc_html(mb_strimwidth($dialbunny_item->message, 0, 25, "...")).'</div>';
              echo '</div></div></div>';
            }
          }
          if ($dialbunny_opened_item == null)
          {
            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 Messages</p><div class="fw-semibold text-gray-400 mb-6">Messages will appear here</div>';
            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 Messages</p><div class="fw-semibold text-gray-400 mb-6">Messages 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)
        {
          echo '<a href="' . esc_url(wp_nonce_url($dialbunnyDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($dialbunny_resultsPage - 1), 'DialBunny', 'user_nonce')) .'&block" class="btn btn-secondary btn-sm me-3">';
          echo '<span class="menu-bullet">';
          echo '<span class="fa fa-arrow-left"></span>';
          echo '</span>';
          echo '</a>';
        }
        ?>
        <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) < $dialbunny_numberOfMessages && strlen($search) <= 2)
        {
          echo '<a href="' . esc_url(wp_nonce_url($dialbunnyDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($dialbunny_resultsPage + 1), 'DialBunny', 'user_nonce')) .'&block" class="btn btn-secondary btn-sm me-3">';
          echo '<span class="menu-bullet">';
          echo '<span class="fa fa-arrow-right"></span>';
          echo '</span>';
          echo '</a>';
        }
        ?>
      </div>
  </div>
</div>
