<?php
if (!class_exists('WP_List_Table')) {
    require_once ABSPATH . 'wp-admin/includes/class-wp-list-table.php';
}

class Pzy_Subscribers_List_Table extends WP_List_Table
{

    public function __construct()
    {
        parent::__construct([
            'singular' => __('خبرنامه', 'pezeshkyar'), // Singular name of the listed records
            'plural' => __('خبرنامه', 'pezeshkyar'), // Plural name of the listed records
            'ajax' => false // Does this table support ajax?
        ]);
    }

    /**
     * Retrieve subscribers data from the database.
     *
     * @return array Array of all the subscribers.
     */
    public static function get_subscribers($per_page = 10, $page_number = 1,$search='')
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'pzy_newsletter_subscribers';

        $sql = "SELECT * FROM $table_name";

        if (!empty($search)) {
            $sql .= $wpdb->prepare(" WHERE contact LIKE %s", '%' . $wpdb->esc_like($search) . '%');
        }

        if (!empty($_REQUEST['orderby'])) {
            $sql .= ' ORDER BY ' . esc_sql($_REQUEST['orderby']);
            $sql .= !empty($_REQUEST['order']) ? ' ' . esc_sql($_REQUEST['order']) : ' ASC';
        } else {
            $sql .= ' ORDER BY id DESC';
        }


        $sql .= " LIMIT $per_page";

        $sql .= ' OFFSET ' . ($page_number - 1) * $per_page;

        return $wpdb->get_results($sql, 'ARRAY_A');
    }

    /**
     * Retrieve the total number of subscribers.
     *
     * @return int Total number of subscribers.
     */
    public static function record_count()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'pzy_newsletter_subscribers';

        $sql = "SELECT COUNT(*) FROM $table_name";

        if (!empty($search)) {
            $sql .= $wpdb->prepare(" WHERE contact LIKE %s", '%' . $wpdb->esc_like($search) . '%', );
        }

        return $wpdb->get_var($sql);
    }

    /** Text displayed when no subscriber data is available */
    public function no_items()
    {
        _e('No subscribers available.', 'pezeshkyar');
    }

    /**
     * Render a column when no column specific method exists.
     *
     * @param array $item A singular item (one full row's worth of data).
     * @param string $column_name The name/slug of the column to be processed.
     *
     * @return mixed
     */
    public function column_default($item, $column_name)
    {
        switch ($column_name) {
            case 'contact':
            case 'subscribed_at':
            case 'active':
                return $item[$column_name];
            default:
                return print_r($item, true); // Show the whole array for troubleshooting purposes
        }
    }

    /**
     * Render the bulk edit checkbox.
     *
     * @param array $item A singular item (one full row's worth of data).
     *
     * @return string
     */
    function column_cb($item)
    {
        return sprintf('<input type="checkbox" name="bulk-delete[]" value="%s" />', $item['id']);
    }

    /**
     * Method for name column.
     *
     * @param array $item An array of DB data.
     *
     * @return string
     */
    function column_contact($item)
    {
        $delete_nonce = wp_create_nonce('delete_subscriber');

        $title = '<strong>' . $item['contact'] . '</strong>';

        $actions = [
            'delete' => sprintf('<a href="?page=%s&action=%s&subscriber=%s&_wpnonce=%s">Delete</a>', esc_attr($_REQUEST['page']), 'delete', absint($item['id']), $delete_nonce)
        ];

        return $title . $this->row_actions($actions);
    }

    function column_subscribed_at($item)
    {
        $date = (new DateTime($item['subscribed_at'], new DateTimeZone('UTC')))->setTimezone(wp_timezone());

        $date_string = $date->format('Y-m-d H:i:s');

        if (pzy_is_active_jalali()){
            $date_string = gregorian_to_jalali($date->format('Y'), $date->format('m'), $date->format('d'),'/');
        }

        return $date_string;
    }

    function column_active($item)
    {
        return $item['active'] ? __('فعال','pezeshkyar') : __('غیرفعال','pezeshkyar');
    }

    /**
     *  Associative array of columns.
     *
     * @return array
     */
    function get_columns()
    {
        $columns = [
            'cb' => '<input type="checkbox" />', // Render a checkbox instead of text
            'contact' => __('شماره تماس/ ایمیل', 'pezeshkyar'),
            'subscribed_at' => __('تاریخ عضویت', 'pezeshkyar'),
            'active' => __('وضعیت', 'pezeshkyar')
        ];

        return $columns;
    }

    /**
     * Columns to make sortable.
     *
     * @return array
     */
    public function get_sortable_columns()
    {
        $sortable_columns = [
            'contact' => ['contact', true],
            'subscribed_at' => ['subscribed_at', true],
            'active' => ['active', true]
        ];

        return $sortable_columns;
    }

    /**
     * Handles data query and filter, sorting, and pagination.
     */
    public function prepare_items()
    {
        $columns = $this->get_columns();
        $hidden = array();
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = array($columns, $hidden, $sortable, 'contact');

        /** Process bulk action */
        $this->process_bulk_action();

        $per_page = $this->get_items_per_page('subscribers_per_page', 10);
        $current_page = $this->get_pagenum();
        $total_items = self::record_count();

        $this->set_pagination_args([
            'total_items' => $total_items, // Total items.
            'per_page' => $per_page     // Items per page.
        ]);

        $search = isset($_REQUEST['s']) ? trim($_REQUEST['s']) : '';
        $this->items = self::get_subscribers($per_page, $current_page,$search);
    }

    /**
     * Process bulk actions.
     */
    public function process_bulk_action()
    {
// Detect when a bulk action is being triggered...
        if ('delete' === $this->current_action()) {
// In our file that handles the request, verify the nonce.
            $nonce = esc_attr($_REQUEST['_wpnonce']);

            if (!wp_verify_nonce($nonce, 'delete_subscriber')) {
                die('Go get a life script kiddies');
            } else {
                self::delete_subscriber(absint($_GET['subscriber']));

                wp_redirect(esc_url(add_query_arg()));
                exit;
            }
        }

// If the delete bulk action is triggered.
        if ((isset($_POST['action']) && $_POST['action'] == 'bulk-delete') || (isset($_POST['action2']) && $_POST['action2'] == 'bulk-delete')) {
            $delete_ids = esc_sql($_POST['bulk-delete']);

// Loop over the array of record IDs and delete them.
            foreach ($delete_ids as $id) {
                self::delete_subscriber($id);
            }

            wp_redirect(esc_url(add_query_arg()));
            exit;
        }
    }

    /**
     * Delete a subscriber record.
     *
     * @param int $id subscriber ID.
     */
    public static function delete_subscriber($id)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'pzy_newsletter_subscribers';

        $wpdb->delete($table_name, ['id' => $id], ['%d']);
    }
}
