<?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="content d-flex flex-column flex-column-fluid" id="content">
    <div class="container-xxl" id="content_container">
      <?php
      $dialbunny_details   = $wpdb->prefix . 'dialbunny_phone_details';
      $dialbunny_messages  = $wpdb->prefix . 'dialbunny_messages';
      $dialbunny_contacts  = $wpdb->prefix . 'dialbunny_contacts';
      $dialbunny_current_user_id = wp_get_current_user()->ID;
      // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
      $dialbunny_phone_details = $wpdb->get_results($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dialbunny_phone_details WHERE user = %d LIMIT 1", $dialbunny_current_user_id)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
      $dialbunny_numberOfMessages = 0;
      $dialbunny_numberOfUnread = 0;
      if (!empty($dialbunny_phone_details[0]->managed_number)) {
          $dialbunny_managed_number = $dialbunny_phone_details[0]->managed_number;
          // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
          $dialbunny_numberOfMessages = $wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT LEAST(from_number, to_number), GREATEST(from_number, to_number)) FROM {$wpdb->prefix}dialbunny_messages WHERE user = %d AND (from_number = %s OR to_number = %s)",$dialbunny_current_user_id,$dialbunny_managed_number,$dialbunny_managed_number)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
          // Direct database query used below – $wpdb->prepare() is always used to prevent SQL injection.
          $dialbunny_numberOfUnread = $wpdb->get_var($wpdb->prepare("SELECT COUNT(DISTINCT LEAST(from_number, to_number), GREATEST(from_number, to_number)) FROM {$wpdb->prefix}dialbunny_messages WHERE user = %d AND (from_number = %s OR to_number = %s) AND reading = '0'",$dialbunny_current_user_id,$dialbunny_managed_number,$dialbunny_managed_number)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
      }
      $dialbunny_resultsPage = 1;
      $dialbunny_limit = '12';
      $dialbunny_limit_offset = 0;
      $dialbunny_limit_count = 12;
      // Handle pagination
      if (isset($_GET['resultsPage']) && is_numeric($_GET['resultsPage']) && intval($_GET['resultsPage']) > 1) {
          $dialbunny_resultsPage = intval($_GET['resultsPage']);
          $dialbunny_limit_offset = ($dialbunny_resultsPage - 1) * $dialbunny_limit_count;
      }
      ?>
      <?php if (isset($_GET['errorsending'])) { echo wp_kses_post(dialbunny_main_danger("Error Sending Message", "Your message could not be sent.")); }  ?>

      <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="fa fa-commenting 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">Text Messages</a>
											</div>
											<div class="d-flex flex-wrap fw-semibold mb-4 fs-5 text-gray-400">Incoming & outgoing text messages will show up here.</div>
										</div>
									</div>
									<div class="d-flex flex-wrap justify-content-start">
										<div class="d-flex flex-wrap">
											<div class="border border-gray-300 border-dashed rounded min-w-125px py-3 px-4 me-6 mb-3">
												<div class="d-flex align-items-center">
                          <i class="fs-1 me-2">
                            <span class="fas fa-comments"></span>
                          </i>
													<div class="fs-4 fw-bold"><?php echo esc_html($dialbunny_numberOfMessages); ?></div>
												</div>
												<div class="fw-semibold fs-6 text-gray-400"><?php if ($dialbunny_numberOfMessages < 2) { echo 'Conversation'; } else { echo 'Conversations'; } ?></div>
											</div>
											<div class="border border-gray-300 border-dashed rounded min-w-125px py-3 px-4 me-6 mb-3">
												<div class="d-flex align-items-center">
                          <i class="fs-1 text-primary me-2">
                            <span class="fas fa-commenting"></span>
                          </i>
													<div class="fs-4 fw-bold counted"><?php echo esc_html($dialbunny_numberOfUnread); ?></div>
												</div>
												<div class="fw-semibold fs-6 text-gray-400">Unread</div>
											</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($dialbunnyDashboardUrl.'&dashboardpage=contacts', 'DialBunny', 'user_nonce')); ?>">Contacts</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($dialbunnyDashboardUrl.'&dashboardpage=messages', 'DialBunny', 'user_nonce')); ?>">Messages</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" href="<?php echo esc_url(wp_nonce_url($dialbunnyDashboardUrl.'&dashboardpage=calendar', 'DialBunny', 'user_nonce')); ?>">Timetable</a>
              </li>
						</ul>
						<a href="#" data-bs-toggle="modal" data-bs-target="#new_message" class="btn btn-primary fw-bold fs-8 fs-lg-base">New Message</a>
					</div>
				</div>
			</div>
      <?php
        if (isset($_GET['phone']) && isset($_GET['countrycode']))
        {
          $dialbunny_current_user_id = get_current_user_id();
          $dialbunny_phone           = sanitize_text_field(wp_unslash($_GET['phone'] ?? ''));
          $dialbunny_countrycode     = '+' . preg_replace('/[^0-9]/', '', sanitize_text_field(wp_unslash($_GET['countrycode'] ?? '')));
          $dialbunny_managed_number  = $dialbunny_phone_details[0]->managed_number ?? '';
          // 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_messages WHERE user = %d AND (to_number = %s OR to_number = %s) AND (from_number = %s OR from_number = %s) ORDER BY created_at DESC LIMIT 40",$dialbunny_current_user_id,$dialbunny_phone,$dialbunny_managed_number,$dialbunny_managed_number,$dialbunny_phone)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
          // 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",$dialbunny_current_user_id,$dialbunny_countrycode,$dialbunny_phone)); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
          if ($dialbunny_opened_item != null) { include('view.php'); }
          else { include('default.php'); }
        }
        else { include('default.php'); }
      ?>
    </div>
</div>

<!-- New Message MODAL -->
<div class="modal fade" id="new_message" tabindex="-1" aria-hidden="true" style="display: none;">
			<div class="modal-dialog mw-650px">
				<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 scroll-y mx-5 mx-xl-18 pt-0 pb-15">
						<div class="text-center mb-13">
							<h1 class="mb-3">New Message</h1>
							<div class="text-muted fw-semibold fs-5">Send text messages to anyone with a phone number</div>
						</div>
            <form action="<?php echo esc_url( admin_url('admin-post.php') ); ?>" method="post" class="form">
              <?php wp_nonce_field( 'DialBunny', 'user_nonce' ); ?>
              <input type="hidden" name="action" value="dialbunny_send_text"></input>
              <div class="fv-row mb-7">
                <label class="fs-6 fw-semibold form-label mt-3">
                  <span class="required">Phone</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="Enter the recipient's phone number.">
                    <i class="text-gray-500 fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <div class="row">
                  <div class="col-lg-4 fv-row">
                    <?php
                    // Escaped inside the dialbunny_country_code() function
                    echo dialbunny_country_code("none", "countrycode"); // phpcs:ignore WordPress.Security.EscapeOutput ?>
                  </div>
                  <div class="col-lg-8 fv-row">
                    <input id="phoneNumber" type="number" maxlength="16" required class="form-control form-control-solid" name="phoneNumber">
                  </div>
                </div>
              </div>
              <div class="fv-row mb-7">
                <label class="fs-6 fw-semibold form-label mt-3">
                  <span class="required">Message</span>
                  <span class="ms-1" data-bs-toggle="tooltip" title="Enter the message that you want to send.">
                    <i class="text-gray-500 fs-6">
                      <span class="fas fa-info-circle"></span>
                    </i>
                  </span>
                </label>
                <textarea name="textMessage" class="form-control form-control-solid" required rows="5" maxlength="2500" name="notes"></textarea>
              </div>
              <div class="separator mb-6"></div>
              <div class="d-flex justify-content-end">
                <button type="submit" class="btn btn-primary">Send</button>
              </div>
            </form>
					</div>
				</div>
			</div>
		</div>
