<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL,WordPress.NamingConventions.PrefixAllGlobals -- Popup list uses a plugin-owned table and template-scope variables.

if (!defined('ABSPATH'))
  exit; // Exit if accessed directly

// use Admin\PopupManager\Class_instant_popup_builder_manager;
require_once(plugin_dir_path(dirname(__FILE__)) . 'PopupManager/class-instant-popup-builder-manager.php');
global $wpdb;
$instant_popup_builder_table_name = $wpdb->prefix . 'instant_popup_builder';
$escaped_table_name = esc_sql($instant_popup_builder_table_name);
$instant_popup_builder_popup_types = Class_instant_popup_builder_manager::get_active_popup();
$instant_popup_builder_is_active = Class_instant_popup_builder_manager::get_active_popup();
// pagination

$paged = isset($_GET['pages']) ? intval($_GET['pages']) : 1;
// Use screen options for per-page display, default to 10 instead of 3
$instant_popup_builder_item_per_page = Instant_Popup_Builder_Admin::ipb_get_popups_per_page();

// Table name is safely escaped with esc_sql() - no user input values to prepare
$instant_popup_builder_popups = $wpdb->get_results("SELECT * FROM `{$escaped_table_name}`");
$instant_popup_builder_total = count($instant_popup_builder_popups);
$instant_popup_builder_total_pages = ceil($instant_popup_builder_total / $instant_popup_builder_item_per_page);
$instant_popup_builder_offset = ($paged - 1) * $instant_popup_builder_item_per_page;
$instant_popup_builder_rows = $wpdb->get_results($wpdb->prepare(
  "SELECT * FROM `{$escaped_table_name}` ORDER BY date DESC LIMIT %d OFFSET %d",
  $instant_popup_builder_item_per_page,
  $instant_popup_builder_offset
), ARRAY_A);

// Total cout of all popups
// Verify user has permission to manage popups
if (!current_user_can('manage_options')) {
    wp_die('You do not have sufficient permissions to access this page.');
}

$instant_popup_builder_row_pub = count($wpdb->get_results($wpdb->prepare("SELECT * from {$wpdb->prefix}instant_popup_builder where status=%s", 'publish'), ARRAY_A));
$instant_popup_builder_row_draft = count($wpdb->get_results($wpdb->prepare("SELECT * from {$wpdb->prefix}instant_popup_builder where status=%s", 'draft'), ARRAY_A));
$instant_popup_builder_row_trash = count($wpdb->get_results($wpdb->prepare("SELECT * from {$wpdb->prefix}instant_popup_builder where status=%s", 'trash'), ARRAY_A));

// Process duplicate action with capability check and nonce verification
if (isset($_GET['dup']) && !empty($_GET['dup']) && current_user_can('manage_options')) {
  $id = intval($_GET['dup']);
  $instant_popup_builder_table = $wpdb->prefix . 'instant_popup_builder';
  $escaped_table = esc_sql($instant_popup_builder_table);

  // Fetch the row
  $instant_popup_builder_row = $wpdb->get_row($wpdb->prepare("SELECT * FROM `{$escaped_table}` WHERE id = %d", $id), ARRAY_A);

  if ($instant_popup_builder_row) {

    unset($instant_popup_builder_row['id']);   // Remove the ID for a new row insertion
    $instant_popup_builder_row['title'] = $instant_popup_builder_row['title'] . ' (Copy)';
    $instant_popup_builder_row['views'] = '0';  // Reset views
    $instant_popup_builder_currentDate = new DateTime();
    $instant_popup_builder_cur_date = $instant_popup_builder_currentDate->format('Y-m-d H:i:s');
    $instant_popup_builder_row['date'] = $instant_popup_builder_cur_date;

    // Insert new row
    $instant_popup_builder_inserted = $wpdb->insert($instant_popup_builder_table, $instant_popup_builder_row);
  }
}
// Process publish action with capability check
if (isset($_GET['pub']) && !empty($_GET['pub']) && current_user_can('manage_options')) {
  $id = intval($_GET['pub']);
  if ($id > 0) {
    $instant_popup_builder_data = ['status' => 'publish', 'class' => 'yes'];
    $instant_popup_builder_where = ['id' => $id];
    $result = $wpdb->update($instant_popup_builder_table_name, $instant_popup_builder_data, $instant_popup_builder_where);
    if (false === $result && defined('WP_DEBUG') && WP_DEBUG) {
    }
  }
}

// Process restore action with capability check
if (isset($_GET['res']) && !empty($_GET['res']) && current_user_can('manage_options')) {
  $id = intval($_GET['res']);
  if ($id > 0) {
    $instant_popup_builder_data = ['status' => 'publish', 'class' => 'yes'];
    $instant_popup_builder_where = ['id' => $id];
    $result = $wpdb->update($instant_popup_builder_table_name, $instant_popup_builder_data, $instant_popup_builder_where);
    if (false === $result && defined('WP_DEBUG') && WP_DEBUG) {
    }
  }
}
// Process delete action with capability check
if (isset($_GET['delete']) && !empty($_GET['delete']) && current_user_can('manage_options')) {
  $id = intval($_GET['delete']);
  if ($id > 0) {
    $instant_popup_builder_where = ['id' => $id];
    $instant_popup_builder_format = ['%d'];
    $result = $wpdb->delete($instant_popup_builder_table_name, $instant_popup_builder_where, $instant_popup_builder_format);
    if (false === $result && defined('WP_DEBUG') && WP_DEBUG) {
    }
  }
}
// Process draft action with capability check
if (isset($_GET['draft']) && !empty($_GET['draft']) && current_user_can('manage_options')) {
  $id = intval($_GET['draft']);
  if ($id > 0) {
    $instant_popup_builder_data = ['status' => 'draft'];
    $instant_popup_builder_where = ['id' => $id];
    $result = $wpdb->update($instant_popup_builder_table_name, $instant_popup_builder_data, $instant_popup_builder_where);
    if (false === $result && defined('WP_DEBUG') && WP_DEBUG) {
    }
  }
}

$Instant_admin = new Instant_Popup_Builder_Admin();

if (isset($_POST['instant_popup_builder_search_']) && isset($_POST['instant_popup_builder_search']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['instant_popup_builder_search'])), 'instant_popup_builder_search_action')) {
  $instant_popup_builder_keyword = isset($_POST['search_popup']) && !empty($_POST['search_popup']) ? sanitize_text_field(wp_unslash($_POST['search_popup'])) : '';
  $instant_popup_builder_rows = $Instant_admin->ipb_search_query_popup($instant_popup_builder_keyword);
}

if ( isset( $_POST['bulk_val'], $_POST['instant_popup_builder_bulk'] ) && wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['instant_popup_builder_bulk'] ) ),'instant_popup_builder_bulk_action')) {
  $instant_popup_builder_keyword = isset($_POST['bulk_val']) && !empty($_POST['bulk_val']) ? sanitize_text_field(wp_unslash($_POST['bulk_val'])) : '';

  if ($instant_popup_builder_keyword == 'all') {

    $instant_popup_builder_rows = $wpdb->get_results($wpdb->prepare(
      "SELECT * FROM `{$escaped_table_name}` ORDER BY date DESC LIMIT %d OFFSET %d",
      $instant_popup_builder_item_per_page,
      $instant_popup_builder_offset
    ), ARRAY_A);
  } else {

    $instant_popup_builder_rows = $Instant_admin->ipb_bulk_query_popup($instant_popup_builder_keyword);
  }
}

$instant_popup_builder_page_url = esc_url(menu_page_url('instant-popup-builder', false));

// Determine if Smart Popup extension is active and enabled
if (!function_exists('is_plugin_active')) {
  include_once ABSPATH . 'wp-admin/includes/plugin.php';
}
$instant_popup_builder_smart_extension_active = function_exists('is_plugin_active') && is_plugin_active('instant-popup-smart-popup/instant-popup-smart-popup.php');
$instant_popup_builder_smart_license_ok = get_option('instant_popup_builder_smart', 'no') === 'yes';
$instant_popup_builder_smart_globally_enabled = intval(get_option('ipsp_smart_popup_enabled', 1)) === 1;
$instant_popup_builder_ipsp_is_active = $instant_popup_builder_smart_extension_active && $instant_popup_builder_smart_license_ok && $instant_popup_builder_smart_globally_enabled;
// var_dump($instant_popup_builder_rows);
$instant_popup_builder_current_slug = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : '';
if (isset($_GET['edit_id']) && !empty($_GET['edit_id'])) {

  $id = intval($_GET['edit_id']);
  // update_option('edit_id', $id);
  $instant_popup_builder_result = $wpdb->get_results($wpdb->prepare("SELECT * FROM  {$wpdb->prefix}instant_popup_builder WHERE id = %d", $id));

  // require_once plugin_dir_path(__FILE__) . 'edit-template/edit-popup-' . esc_attr($instant_popup_builder_result[0]->type) . '.php';

  if (isset($instant_popup_builder_result[0]->type)) {

    Class_instant_popup_builder_manager::edit_popup($instant_popup_builder_result[0]->type);
  }
} else {

?>
  <div class="instant_popup">
    <div class="wrapper">

      <div class="instant_popup_wrapper">
        <?php Instant_Popup_Builder_Admin::ipb_top_header(); ?>

        <div class="filter_wrapper tablenav top">
          <div class="popup_bulk_filter">
            <form action="" method="post" id="bulk_filter">
              <label class="screen-reader-text" for="bulk_val"><?php esc_html_e('Filter popups by status', 'instant-popup-builder'); ?></label>
              <select name="bulk_val" id="bulk_val" onchange="document.getElementById('bulk_filter').submit();">
                <option value="all" <?php echo isset($_POST['bulk_val']) && $_POST['bulk_val'] == 'all' ? 'selected' : '' ?>>All</option>
                <option value="yes" <?php echo isset($_POST['bulk_val']) && $_POST['bulk_val'] == 'yes' ? 'selected' : '' ?>>Active</option>
                <option value="no" <?php echo isset($_POST['bulk_val']) && $_POST['bulk_val'] == 'no' ? 'selected' : '' ?>>Inactive</option>
              </select>
              <?php wp_nonce_field('instant_popup_builder_bulk_action', 'instant_popup_builder_bulk'); ?>
            </form>
          </div>
          <div class="bulk_actions alignleft actions bulkactions">
            <label class="screen-reader-text" for="ipb_bulk_action"><?php esc_html_e('Select bulk action', 'instant-popup-builder'); ?></label>
            <select id="ipb_bulk_action">
              <option value="">Bulk actions</option>
              <option value="yes">Activate</option>
              <option value="no">Deactivate</option>
              <option value="delete-permenant">Delete</option>
            </select>
            <button type="button" id="popup_bulk_search_" class="button action">Apply</button>
          </div>
          <div class="search_wrapper">
            <form action="" method="post">
              <?php wp_nonce_field('instant_popup_builder_search_action', 'instant_popup_builder_search'); ?>
              <input type="hidden" name="instant_popup_builder_search_" value="1">
              <label class="screen-reader-text" for="search_popup"><?php esc_html_e('Search popups', 'instant-popup-builder'); ?></label>
              <input type="search" id="search_popup" class="regular-text" size="30" required name="search_popup" placeholder="Search popups" value="<?php echo isset($_POST['search_popup']) ? esc_attr(sanitize_text_field(wp_unslash($_POST['search_popup']))) : ''; ?>">
            </form>
          </div>
          <div class="ipb_actions_right">
            <a href="<?php echo esc_url(menu_page_url('add-new-instant-popup', false)); ?>" id="popup_btn" class="button button-primary"><i class="fa-solid fa-plus"></i> Add New Popup</a>
          </div>
        </div>
        <div class="popup_lists">
          <div class="popup_loader">
            <img src="<?php echo esc_url( plugin_dir_url( dirname(__FILE__) ) . 'image/loader.gif' ); ?>" alt="">
          </div>
          <table>
            <thead>
              <th><input type="checkbox" id="popu_all" aria-label="Select all"></th>
              <th>ID</th>
              <th>Title </th>
              <?php if ($instant_popup_builder_ipsp_is_active): ?>
              <th class="ipsp-smart-popup-col">Smart Popup</th>
              <?php endif; ?>
              <th>Type</th>
              <th>Views </th>
            </thead>
            <tbody>
              <?php
              if ($instant_popup_builder_rows) {
                foreach ($instant_popup_builder_rows as $instant_popup_builder_index => $instant_popup_builder_row): ?>
                  <tr>
                    <td><input type="checkbox" class="popu_check" value="<?php echo esc_attr($instant_popup_builder_row['id']); ?>" aria-label="Select popup"></td>
                    <td><?php echo esc_html($instant_popup_builder_index + 1); ?></td>
                    <td>
                      <?php echo esc_html($instant_popup_builder_row['title']); ?>

                      <div class="actions">
                        <a href="<?php echo esc_attr($instant_popup_builder_page_url . '&edit_id=' . $instant_popup_builder_row['id'] . '&type=' . $instant_popup_builder_row['type'] . ''); ?>" class="edit_btn ipb-icon" title="Edit" aria-label="Edit">
                          <i class="fa-solid fa-pen-to-square" aria-hidden="true"></i>
                        </a>
                        <a rel="modal:open" href="#popup_preview_<?php echo esc_attr($instant_popup_builder_row['id']); ?>" class="prev_btn ipb-icon" title="Preview" aria-label="Preview"
                          data-popup-type="<?php echo esc_attr(isset($instant_popup_builder_row['type']) ? $instant_popup_builder_row['type'] : ''); ?>"
                          data-popup-id="<?php echo esc_attr((string) $instant_popup_builder_row['id']); ?>">
                          <i class="fa-solid fa-eye" aria-hidden="true"></i>
                        </a>
                        <a href="<?php echo esc_url($instant_popup_builder_page_url . '&dup=' . $instant_popup_builder_row['id'] . ''); ?>" class="dup_btn ipb-icon" data-id="<?php echo esc_attr($instant_popup_builder_row['id']); ?>" title="Duplicate" aria-label="Duplicate">
                          <i class="fa-solid fa-copy" aria-hidden="true"></i>
                        </a>
                        <a href="<?php echo esc_url($instant_popup_builder_page_url . '&delete=' . $instant_popup_builder_row['id'] . ''); ?>" class="del_btn ipb-icon" title="Delete" aria-label="Delete">
                          <i class="fa-solid fa-trash" aria-hidden="true"></i>
                        </a>
                        <?php
                          $ipb_row_type = isset( $instant_popup_builder_row['type'] ) ? $instant_popup_builder_row['type'] : '';
                          $ipb_row_advance        = isset( $instant_popup_builder_row['advance'] ) ? $instant_popup_builder_row['advance'] : '';
                          $ipb_extension_required = $ipb_row_type !== '' && class_exists( 'Instant_Popup_Builder_Extension_Dependency', false ) && Instant_Popup_Builder_Extension_Dependency::is_extension_required_for_type( $ipb_row_type, $ipb_row_advance );
                          $ipb_extension_active   = $ipb_extension_required && Instant_Popup_Builder_Extension_Dependency::is_extension_active_for_type( $ipb_row_type, $ipb_row_advance );
                          $ipb_toggle_disabled    = $ipb_extension_required && ! $ipb_extension_active;
                          $ipb_effective_active   = $ipb_toggle_disabled ? false : ( $instant_popup_builder_row['class'] === 'yes' );
                          /* translators: %s: required extension display name. */
                          $ipb_tooltip            = $ipb_toggle_disabled ? sprintf( __( 'This popup requires the %s extension to be active.', 'instant-popup-builder' ), Instant_Popup_Builder_Extension_Dependency::get_extension_display_name_for_type( $ipb_row_type ) ) : '';
                        ?>
                        <div class="popup_active<?php echo $ipb_toggle_disabled ? ' ipb-toggle-extension-missing' : ''; ?>"<?php echo $ipb_tooltip !== '' ? ' title="' . esc_attr( $ipb_tooltip ) . '"' : ''; ?>>
                          <div class="input toggle switch ipb_tog">
                            <input type="checkbox" class="ipb_popup_active_toggle" name="popup_active_toggle" id="popup_active_toggle_<?php echo esc_attr( $instant_popup_builder_row['id'] ); ?>" <?php echo $ipb_effective_active ? 'checked' : ''; ?> <?php echo $ipb_toggle_disabled ? 'disabled' : ''; ?> data-id="<?php echo esc_attr($instant_popup_builder_row['id']); ?>"
                              value="<?php echo esc_attr( $ipb_effective_active ? 'yes' : '' ); ?>"
                              <?php echo $ipb_tooltip !== '' ? ' aria-label="' . esc_attr( $ipb_tooltip ) . '"' : ''; ?>>
                            <span class="slider round"></span>
                          </div>
                          <label for="popup_active_toggle_<?php echo esc_attr( $instant_popup_builder_row['id'] ); ?>"><?php echo $ipb_effective_active ? esc_html__( 'Active', 'instant-popup-builder' ) : esc_html__( 'Inactive', 'instant-popup-builder' ); ?></label>
                        </div>
                        <!-- modal for different popup -->
                        <div class="modal <?php echo $instant_popup_builder_row['type'] === 'spin_to_win' ? 'ipb-stw-preview-modal' : ''; ?>" style="width: 75%;padding:<?php echo $instant_popup_builder_row['type'] == 'video' || $instant_popup_builder_row['type'] == 'image' || $instant_popup_builder_row['type'] == 'subscription' ? '0px' : ''; ?> !important; " id="popup_preview_<?php echo esc_attr($instant_popup_builder_row['id']); ?>">

                          <?php Class_instant_popup_builder_manager::trigger_modal($instant_popup_builder_row['type'], $instant_popup_builder_row['id']); ?>
                        </div>
                      </div>
                    </td>
                    <?php if ($instant_popup_builder_ipsp_is_active): ?>
                      <td class="ipsp-smart-popup-cell">
                        <div class="ipsp-toggle-container">
                          <label class="ipsp-toggle-switch">
                            <input type="checkbox" class="ipsp-smart-popup-toggle" data-popup-id="<?php echo esc_attr($instant_popup_builder_row['id']); ?>" disabled>
                            <span class="ipsp-toggle-slider"></span>
                          </label>
                        </div>
                      </td>
                    <?php endif; ?>
                    <td>
                      <p class="popu_views"><?php echo esc_html(ucfirst($instant_popup_builder_row['type'])); ?></p>
                    </td>
                    <td><?php echo intval($instant_popup_builder_row['views']) ? esc_html($instant_popup_builder_row['views']) : 0; ?></td>
                  </tr>
                <?php endforeach;
              } else { ?>

                <tr>
                  <td colspan="<?php echo $instant_popup_builder_ipsp_is_active ? '6' : '5'; ?>" class="no-items" style="text-align: center; padding: 40px 20px; font-size: 16px; color: #666;">
                    <div style="display: inline-block;">
                      <i class="fa-solid fa-info-circle" style="margin-right: 8px; color: #007cba;"></i>
                      No Popups Found
                    </div>
                  </td>
                </tr>
              <?php } ?>
            </tbody>
          </table>
          <?php if ($instant_popup_builder_ipsp_is_active): ?>
            <?php
              // Smart Popup toggle behavior (only if Smart Popup extension is present and enabled)
              $instant_popup_builder_ipsp_nonce = wp_create_nonce('ipsp_nonce');
              $instant_popup_builder_ajax_url = admin_url('admin-ajax.php');
            ?>
            <script type="text/javascript">
            jQuery(document).ready(function($){
                var ajaxUrl = '<?php echo esc_js($instant_popup_builder_ajax_url); ?>';
                var nonce = '<?php echo esc_js($instant_popup_builder_ipsp_nonce); ?>';

                // Initialize each toggle by fetching its current status
                $('.ipsp-smart-popup-toggle').each(function(){
                    var $toggle = $(this);
                    var popupId = $toggle.data('popup-id');

                    $.post(ajaxUrl, {
                        action: 'ipsp_get_popup_smart_status',
                        popup_id: popupId,
                        nonce: nonce
                    }, function(response){
                        if(response && response.success && response.data){
                            $toggle.prop('checked', !!response.data.enabled);
                        }
                    }).always(function(){
                        $toggle.prop('disabled', false);
                    });
                });

                // Toggle handler
                $(document).on('change', '.ipsp-smart-popup-toggle', function(){
                    var $toggle = $(this);
                    var popupId = $toggle.data('popup-id');
                    var isEnabled = $toggle.is(':checked');
                    $toggle.prop('disabled', true);

                    $.post(ajaxUrl, {
                        action: 'ipsp_toggle_smart_popup',
                        popup_id: popupId,
                        enabled: isEnabled,
                        nonce: nonce
                    }, function(response){
                        if(!response || !response.success){
                            // Revert on failure
                            $toggle.prop('checked', !isEnabled);
                            alert('Failed to update Smart Popup status');
                        }
                    }).fail(function(){
                        $toggle.prop('checked', !isEnabled);
                        alert('Failed to update Smart Popup status');
                    }).always(function(){
                        $toggle.prop('disabled', false);
                    });
                });
            });
            </script>
          <?php endif; ?>
          <?php

          echo '<div class="pagination">';
          $pagination_links = paginate_links([
            'base'      => esc_url(add_query_arg('pages', '%#%')),
            'format'    => '',
            'prev_text' => '« Previous',
            'next_text' => 'Next »',
            'total'     => $instant_popup_builder_total_pages,
            'current'   => $paged,
          ]);
          echo ($pagination_links !== null && is_string($pagination_links)) ? wp_kses_post($pagination_links) : '';
          echo '</div>';
          ?>
        </div>
      </div>
    </div>
  </div>

<?php } ?>
