<?php

namespace Unlockafe_addons\Classes;

if (!defined('ABSPATH')) {
    exit();
}

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

class Gift_Card_List_Table extends \WP_List_Table {

    public function __construct() {
        parent::__construct([
            'singular' => __('Gift Card', 'unlock-addons-for-elementor'),
            'plural'   => __('Gift Cards', 'unlock-addons-for-elementor'),
            'ajax'     => false
        ]);
    }

    public function get_columns() {
        return [
            'cb'              => '<input type="checkbox" />',
            'code'            => __('Code', 'unlock-addons-for-elementor'),
            'balance'         => __('Balance', 'unlock-addons-for-elementor'),
            'recipient_email' => __('Recipient Email', 'unlock-addons-for-elementor'),
            'order_id'        => __('Order ID', 'unlock-addons-for-elementor'),
            'status'          => __('Status', 'unlock-addons-for-elementor'),
            'created_at'      => __('Created At', 'unlock-addons-for-elementor'),
            'expiry_date'     => __('Expiry Date', 'unlock-addons-for-elementor'),
        ];
    }

    protected function get_bulk_actions() {
        return [
            'bulk-delete' => __('Delete', 'unlock-addons-for-elementor'),
        ];
    }

    public function get_sortable_columns() {
        return [
            'balance'         => ['balance', false],
            'recipient_email' => ['recipient_email', false],
            'created_at'      => ['created_at', true],
            'expiry_date'     => ['expiry_date', false],
        ];
    }

    public function no_items() {
        _e('No gift cards found.', 'unlock-addons-for-elementor');
    }

    public function prepare_items() {
        $per_page = 20;
        $current_page = $this->get_pagenum();
        $total_items = $this->get_total_gift_cards();

        $this->set_pagination_args([
            'total_items' => $total_items,
            'per_page'    => $per_page
        ]);

        $columns = $this->get_columns();
        $hidden = [];
        $sortable = $this->get_sortable_columns();
        $this->_column_headers = [$columns, $hidden, $sortable];

        $this->items = $this->get_gift_card_data($per_page, $current_page);

        $this->search_box(__('Search'), 'gift-card-search');
    }

    private function get_gift_card_data($per_page, $current_page) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'unlockafe_store_credit';
        $sql = "SELECT * FROM {$table_name}";

        if (!empty($_REQUEST['s'])) {
            $search = sanitize_text_field($_REQUEST['s']);
            $search = '%' . $wpdb->esc_like($search) . '%';
            $sql .= $wpdb->prepare(" WHERE code LIKE %s OR recipient_email LIKE %s", $search, $search);
        }

        $orderby = !empty($_REQUEST['orderby']) ? sanitize_sql_orderby($_REQUEST['orderby']) : 'created_at';
        $order = !empty($_REQUEST['order']) && in_array(strtoupper($_REQUEST['order']), ['ASC', 'DESC']) ? $_REQUEST['order'] : 'DESC';
        $sql .= " ORDER BY {$orderby} {$order}";

        $offset = ($current_page - 1) * $per_page;
        $sql .= $wpdb->prepare(" LIMIT %d OFFSET %d", $per_page, $offset);

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

    private function get_total_gift_cards() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'unlockafe_store_credit';
        $sql = "SELECT COUNT(*) FROM {$table_name}";

        if (!empty($_REQUEST['s'])) {
            $search = sanitize_text_field($_REQUEST['s']);
            $search = '%' . $wpdb->esc_like($search) . '%';
            $sql .= $wpdb->prepare(" WHERE code LIKE %s OR recipient_email LIKE %s", $search, $search);
        }

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

    public function column_cb($item) {
        return sprintf('<input type="checkbox" name="gift_card[]" value="%s" />', $item['id']);
    }

    public function column_code($item) {
        $delete_nonce = wp_create_nonce('unlockafe_delete_gift_card');
        $actions = [
            'view_order' => sprintf('<a href="%s">%s</a>', get_edit_post_link($item['order_id']), __('View Order', 'unlock-addons-for-elementor')),
            'delete' => sprintf('<a href="?page=%s&action=%s&gift_card=%s&_wpnonce=%s">%s</a>', esc_attr($_REQUEST['page']), 'delete', absint($item['id']), $delete_nonce, __('Delete', 'unlock-addons-for-elementor')),
        ];
        return sprintf('%1$s %2$s', $item['code'], $this->row_actions($actions));
    }

    public function column_default($item, $column_name) {
        switch ($column_name) {
            case 'balance':
                return wc_price($item[$column_name]);
            case 'created_at':
            case 'expiry_date':
                return !empty($item[$column_name]) ? date_i18n(get_option('date_format'), strtotime($item[$column_name])) : '—';
            default:
                return esc_html($item[$column_name]);
        }
    }
}
