<?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="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
                $copuloo_user_id = get_current_user_id();
                $copuloo_managed_number = $copuloo_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.
                  $copuloo_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}copuloo_messages WHERE user = %d AND (from_number = %s OR to_number = %s) AND message LIKE %s LIMIT 25", $copuloo_user_id, $copuloo_managed_number, $copuloo_managed_number, $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 (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}copuloo_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", $copuloo_user_id, $copuloo_managed_number,$copuloo_managed_number,$copuloo_limit_offset,$copuloo_limit_count)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                }
                  // check to see if the user has a managed number
                  if (isset($copuloo_phone_details[0]->managed_number) && isset($copuloo_phone_details[0]->managed_number_code))
                  {
                    foreach ($copuloo_opened_item as $copuloo_item)
                    {
                      // Check to see if contact exists
                      $copuloo_phoneNumberCountryCode;
                      $copuloo_phoneNumber;
                      if ($copuloo_phone_details[0]->managed_number_code == $copuloo_item->from_countrycode && $copuloo_phone_details[0]->managed_number == $copuloo_item->from_number) { $copuloo_phoneNumberCountryCode = $copuloo_item->to_countrycode; $copuloo_phoneNumber = $copuloo_item->to_number; }
                      else { $copuloo_phoneNumberCountryCode = $copuloo_item->from_countrycode; $copuloo_phoneNumber = $copuloo_item->from_number; }
                      // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
                      $copuloo_contact = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_contacts WHERE user = %d AND countrycode = %s AND phone = %s LIMIT 1",wp_get_current_user()->ID,$copuloo_phoneNumberCountryCode,$copuloo_phoneNumber)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
                      if ($copuloo_contact == null)
                      {
                        $copuloo_displayName = copuloo_formatNumber($copuloo_phoneNumber);
                        if ($copuloo_item->from_number == $copuloo_phone_details[0]->managed_number && strlen($search) > 2) { $copuloo_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($copulooDashboardUrl.'&dashboardpage=messages&phone='.esc_html($copuloo_phoneNumber).'&countrycode='.esc_html($copuloo_phoneNumberCountryCode), 'Copuloo', 'user_nonce')).'" class="mb-1 text-gray-800 text-hover-primary">'.esc_html($copuloo_displayName).'</a><div class="fw-semibold fs-6 text-gray-400">Not in contacts</div></div></div></td>';
                        echo '<td>'.esc_html(mb_strimwidth($copuloo_item->message, 0, 25, "...")).'</td>';
                        if ($copuloo_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($copulooDashboardUrl.'&dashboardpage=messages&phone='.esc_html($copuloo_phoneNumber).'&countrycode='.esc_html($copuloo_phoneNumberCountryCode), 'Copuloo', 'user_nonce')).'" class="btn btn-light btn-sm">View</a></td>';
                        echo '</tr>';
                      }
                      else
                      {
                        $copuloo_displayName = $copuloo_contact[0]->name;
                        if ($copuloo_item->from_number == $copuloo_phone_details[0]->managed_number && strlen($search) > 2) { $copuloo_displayName = 'You'; }
                        $copuloo_bgicon = "light-primary";
                        $copuloo_texticon = "primary";
                        if ($copuloo_contact[0]->icon == 2) { $copuloo_bgicon = "light-success"; $copuloo_texticon = "success"; }
                        if ($copuloo_contact[0]->icon == 3) { $copuloo_bgicon = "light-info"; $copuloo_texticon = "info"; }
                        if ($copuloo_contact[0]->icon == 4) { $copuloo_bgicon = "light-danger"; $copuloo_texticon = "danger"; }
                        if ($copuloo_contact[0]->icon == 5) { $copuloo_bgicon = "light-warning"; $copuloo_texticon = "warning"; }
                        if ($copuloo_contact[0]->icon == 6) { $copuloo_bgicon = "secondary"; $copuloo_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($copuloo_bgicon).' text-'.esc_html($copuloo_texticon).' fs-6 fw-bolder">'.esc_html(ucfirst(substr($copuloo_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($copulooDashboardUrl.'&dashboardpage=messages&phone='.esc_html($copuloo_phoneNumber).'&countrycode='.esc_html($copuloo_phoneNumberCountryCode), 'Copuloo', 'user_nonce')).'" class="mb-1 text-gray-800 text-hover-primary">'.esc_html($copuloo_displayName).'</a><div class="fw-semibold fs-6 text-gray-400">'.esc_html(copuloo_formatNumber($copuloo_phoneNumber)).'</div></div></div></td>';
                        echo '<td>'.esc_html(mb_strimwidth($copuloo_item->message, 0, 25, "...")).'</td>';
                        if ($copuloo_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($copulooDashboardUrl.'&dashboardpage=messages&phone='.esc_html($copuloo_phoneNumber).'&countrycode='.esc_html($copuloo_phoneNumberCountryCode), 'Copuloo', 'user_nonce')).'" class="btn btn-light btn-sm">View</a></td>';
                        echo '</tr>';
                      }
                    }
                    if ($copuloo_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 ($copuloo_resultsPage > 1 && strlen($search) <= 2)
        {
          echo '<a href="' . esc_url(wp_nonce_url($copulooDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($copuloo_resultsPage - 1), 'Copuloo', '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($copuloo_resultsPage); ?></span>
        <?php if (isset($copuloo_opened_item) && ($copuloo_resultsPage * 12) < $copuloo_numberOfMessages && strlen($search) <= 2)
        {
          echo '<a href="' . esc_url(wp_nonce_url($copulooDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($copuloo_resultsPage + 1), 'Copuloo', '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($copuloo_phone_details[0]->managed_number) && isset($copuloo_phone_details[0]->managed_number_code))
      {
          // Foreach message
          foreach ($copuloo_opened_item as $copuloo_item)
          {
            // Check to see if contact exists and make sure the from number does not equal the managed number
            $copuloo_phoneNumberCountryCode;
            $copuloo_phoneNumber;
            if ($copuloo_phone_details[0]->managed_number_code == $copuloo_item->from_countrycode && $copuloo_phone_details[0]->managed_number == $copuloo_item->from_number) { $copuloo_phoneNumberCountryCode = $copuloo_item->to_countrycode; $copuloo_phoneNumber = $copuloo_item->to_number; }
            else { $copuloo_phoneNumberCountryCode = $copuloo_item->from_countrycode; $copuloo_phoneNumber = $copuloo_item->from_number; }
            // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
            $copuloo_contact = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}copuloo_contacts WHERE user = %d AND countrycode = %s AND phone = %s LIMIT 1",wp_get_current_user()->ID,$copuloo_phoneNumberCountryCode,$copuloo_phoneNumber)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
            if ($copuloo_contact == null)
            {
              $copuloo_displayName = copuloo_formatNumber($copuloo_phoneNumber);
              if ($copuloo_item->from_number == $copuloo_phone_details[0]->managed_number && strlen($search) > 2) { $copuloo_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($copulooDashboardUrl.'&dashboardpage=messages&phone='.esc_html($copuloo_phoneNumber).'&countrycode='.esc_html($copuloo_phoneNumberCountryCode), 'Copuloo', 'user_nonce')).'" class="fs-4 text-gray-800 text-hover-primary fw-bold mb-0">'.esc_html($copuloo_displayName).'</a><div class="fw-semibold text-gray-400 mb-6">Not in contacts</div>';
              if ($copuloo_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($copuloo_item->message, 0, 25, "...")).'</div>';
              echo '</div></div></div>';
            }
            else
            {
              $copuloo_displayName = $copuloo_contact[0]->name;
              if ($copuloo_item->from_number == $copuloo_phone_details[0]->managed_number && strlen($search) > 2) { $copuloo_displayName = 'You'; }
              $copuloo_bgicon = "light-primary";
              $copuloo_texticon = "primary";
              if ($copuloo_contact[0]->icon == 2) { $copuloo_bgicon = "light-success"; $copuloo_texticon = "success"; }
              if ($copuloo_contact[0]->icon == 3) { $copuloo_bgicon = "light-info"; $copuloo_texticon = "info"; }
              if ($copuloo_contact[0]->icon == 4) { $copuloo_bgicon = "light-danger"; $copuloo_texticon = "danger"; }
              if ($copuloo_contact[0]->icon == 5) { $copuloo_bgicon = "light-warning"; $copuloo_texticon = "warning"; }
              if ($copuloo_contact[0]->icon == 6) { $copuloo_bgicon = "secondary"; $copuloo_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($copuloo_texticon).' bg-'.esc_html($copuloo_bgicon).'">'.esc_html(ucfirst(substr($copuloo_contact[0]->name, 0, 1))).'</span></div>';
              echo '<a href="'.esc_url(wp_nonce_url($copulooDashboardUrl.'&dashboardpage=messages&phone='.esc_html($copuloo_phoneNumber).'&countrycode='.esc_html($copuloo_phoneNumberCountryCode), 'Copuloo', 'user_nonce')).'" class="fs-4 text-gray-800 text-hover-primary fw-bold mb-0">'.esc_html($copuloo_displayName).'</a><div class="fw-semibold text-gray-400 mb-6">'.esc_html(copuloo_formatNumber($copuloo_phoneNumber)).'</div>';
              if ($copuloo_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($copuloo_item->message, 0, 25, "...")).'</div>';
              echo '</div></div></div>';
            }
          }
          if ($copuloo_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 ($copuloo_resultsPage > 1 && strlen($search) <= 2)
        {
          echo '<a href="' . esc_url(wp_nonce_url($copulooDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($copuloo_resultsPage - 1), 'Copuloo', '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($copuloo_resultsPage); ?></span>
        <?php if (isset($copuloo_opened_item) && ($copuloo_resultsPage * 12) < $copuloo_numberOfMessages && strlen($search) <= 2)
        {
          echo '<a href="' . esc_url(wp_nonce_url($copulooDashboardUrl . '&dashboardpage=messages&resultsPage=' . esc_html($copuloo_resultsPage + 1), 'Copuloo', '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>
