<?php

defined("ABSPATH") || exit();

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

class Chit_Codes_List_Table extends WP_List_Table
{
    public function __construct()
    {
        parent::__construct([
            "singular" => "code",
            "plural" => "codes",
            "ajax" => false,
        ]);
    }

    public function get_columns()
    {
        return [
            "code" => __("Code", "chit-download-codes-for-woocommerce"),
            "product" => __("Product", "chit-download-codes-for-woocommerce"),
            "batch_id" => __("Batch", "chit-download-codes-for-woocommerce"),
            "status" => __("Status", "chit-download-codes-for-woocommerce"),
            "created_at" => __("Created", "chit-download-codes-for-woocommerce"),
            "activated_at" => __("Activated", "chit-download-codes-for-woocommerce"),
            "activated_by" => __("Activated by", "chit-download-codes-for-woocommerce"),
            "actions" => __("Actions", "chit-download-codes-for-woocommerce"),
        ];
    }

    public function get_sortable_columns()
    {
        return [
            "code" => ["code", false],
            "status" => ["status", false],
            "created_at" => ["created_at", true],
            "activated_at" => ["activated_at", false],
        ];
    }

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

        $orderby = isset($_GET["orderby"])
            ? sanitize_key($_GET["orderby"])
            : "created_at";
        $order = isset($_GET["order"]) && strtoupper(sanitize_text_field(wp_unslash($_GET["order"]))) === "ASC"
            ? "ASC"
            : "DESC";

        $args = [
            "per_page" => $per_page,
            "page" => $current_page,
            "orderby" => $orderby,
            "order" => $order,
            "status" => !empty($_GET["status"])
                ? sanitize_key($_GET["status"])
                : null,
            "product_id" => !empty($_GET["product_id"])
                ? (int) $_GET["product_id"]
                : null,
            "batch_id" => !empty($_GET["batch_id"])
                ? (int) $_GET["batch_id"]
                : null,
        ];

        $this->items = Chit_Codes::get_codes($args);
        $total = Chit_Codes::get_codes_count($args);

        $this->set_pagination_args([
            "total_items" => $total,
            "per_page" => $per_page,
            "total_pages" => (int) ceil($total / $per_page),
        ]);

        $this->_column_headers = [
            $this->get_columns(),
            [],
            $this->get_sortable_columns(),
        ];
    }

    public function column_default($item, $column_name)
    {
        return esc_html($item[$column_name] ?? "");
    }

    public function column_code($item)
    {
        return "<strong>" . esc_html($item["code"]) . "</strong>";
    }

    public function column_actions($item)
    {
        if ($item["status"] !== "unused") {
            return "&mdash;";
        }
        $revoke_url = wp_nonce_url(
            add_query_arg(
                [
                    "page" => "chit-view",
                    "action" => "revoke",
                    "code_id" => $item["id"],
                ],
                admin_url("admin.php")
            ),
            "chit_revoke_" . $item["id"]
        );
        return sprintf(
            '<a href="%s" class="button button-small button-link-delete" onclick="return confirm(\'%s\');">%s</a>',
            esc_url($revoke_url),
            esc_js(__("Revoke this code?", "chit-download-codes-for-woocommerce")),
            esc_html__("Revoke", "chit-download-codes-for-woocommerce")
        );
    }

    public function column_product($item)
    {
        $product = wc_get_product($item["product_id"]);
        if (!$product) {
            return "<em>" . esc_html__("(deleted)", "chit-download-codes-for-woocommerce") . "</em>";
        }
        return esc_html($product->get_name());
    }

    public function column_status($item)
    {
        $status = $item["status"];
        $colors = [
            "unused" => "#46b450",
            "activated" => "#0073aa",
            "revoked" => "#dc3232",
            "expired" => "#999",
        ];
        $color = $colors[$status] ?? "#666";
        return sprintf(
            '<span style="color: %s; font-weight: 600;">%s</span>',
            esc_attr($color),
            esc_html(ucfirst($status))
        );
    }

    public function column_batch_id($item)
    {
        if (empty($item["batch_id"])) {
            return "&mdash;";
        }
        $out = "#" . (int) $item["batch_id"];
        if (!empty($item["batch_note"])) {
            $out .=
                ' <span style="color: #666;">&mdash; ' .
                esc_html($item["batch_note"]) .
                "</span>";
        }
        return $out;
    }

    public function column_activated_at($item)
    {
        return $item["activated_at"]
            ? esc_html($item["activated_at"])
            : "&mdash;";
    }

    public function column_activated_by($item)
    {
        $label = Chit_Codes::activator_label($item);
        return $label !== "" ? esc_html($label) : "&mdash;";
    }

    public function no_items()
    {
        esc_html_e("No codes found.", "chit-download-codes-for-woocommerce");
    }

    protected function extra_tablenav($which)
    {
        if ($which !== "top") {
            return;
        }
        $current_status = sanitize_key(wp_unslash($_GET["status"] ?? ""));
        $current_batch = absint($_GET["batch_id"] ?? 0);
        $batches = Chit_Batches::get_batches(500, 0);
        ?>
        <div class="alignleft actions">
            <select name="status">
                <option value=""><?php esc_html_e(
                    "All statuses",
                    "chit-download-codes-for-woocommerce"
                ); ?></option>
                <?php foreach (
                    ["unused", "activated", "revoked", "expired"]
                    as $s
                ): ?>
                    <option value="<?php echo esc_attr(
                        $s
                    ); ?>" <?php selected($current_status, $s); ?>>
                        <?php echo esc_html(ucfirst($s)); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <select name="batch_id">
                <option value=""><?php esc_html_e(
                    "All batches",
                    "chit-download-codes-for-woocommerce"
                ); ?></option>
                <?php foreach ($batches as $batch):
                    $label = "#" . (int) $batch["id"];
                    if (!empty($batch["note"])) {
                        $label .= " — " . $batch["note"];
                    }
                    ?>
                    <option value="<?php echo esc_attr(
                        $batch["id"]
                    ); ?>" <?php selected(
    $current_batch,
    (int) $batch["id"]
); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <?php submit_button(
                esc_html__("Filter", "chit-download-codes-for-woocommerce"),
                "",
                "filter_action",
                false
            ); ?>

            <?php
            $export_args = [
                "page" => "chit-view",
                "action" => "export_codes",
            ];
            if ($current_status !== "") {
                $export_args["status"] = $current_status;
            }
            if ($current_batch > 0) {
                $export_args["batch_id"] = $current_batch;
            }
            $export_url = wp_nonce_url(
                add_query_arg($export_args, admin_url("admin.php")),
                "chit_export_codes"
            );
            ?>
            <a href="<?php echo esc_url(
                $export_url
            ); ?>" class="button" style="margin-left: 0.5em;">
                <?php esc_html_e("Export CSV", "chit-download-codes-for-woocommerce"); ?>
            </a>

            <?php
            $print_args = $export_args;
            $print_args["action"] = "print_pdf";
            $print_url = wp_nonce_url(
                add_query_arg($print_args, admin_url("admin.php")),
                "chit_print_pdf"
            );
            ?>
            <a href="<?php echo esc_url(
                $print_url
            ); ?>" class="button" target="_blank">
                <?php esc_html_e("Print PDF", "chit-download-codes-for-woocommerce"); ?>
            </a>
        </div>
        <?php
    }
}
