<?php

defined( "ABSPATH" ) || exit;
class Chit_Admin_View {
    private $list_table;

    public function __construct() {
        add_action( "admin_init", [$this, "maybe_handle_revoke"] );
        add_action( "admin_init", [$this, "maybe_handle_export"] );
        add_action( "admin_init", [$this, "maybe_handle_print"] );
    }

    public function maybe_handle_print() {
        if ( !isset( $_GET["page"], $_GET["action"] ) || $_GET["page"] !== "chit-view" || $_GET["action"] !== "print_pdf" ) {
            return;
        }
        if ( !current_user_can( "manage_woocommerce" ) ) {
            wp_die( esc_html__( "No permission.", "chit-download-codes-for-woocommerce" ), 403 );
        }
        check_admin_referer( "chit_print_pdf" );
        $args = [
            "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 ),
            "per_page"   => 100000,
            "page"       => 1,
            "orderby"    => "id",
            "order"      => "ASC",
        ];
        $codes = Chit_Codes::get_codes( $args );
        $redeem_url = $this->get_redeem_url();
        $this->render_print_page( $codes, $redeem_url );
        exit;
    }

    private function render_print_page( array $codes, string $redeem_url, string $logo_url = "" ) : void {
        header( "Content-Type: text/html; charset=utf-8" );
        nocache_headers();
        $pages = array_chunk( $codes, 10 );
        wp_register_style(
            "chit-print-cards",
            plugins_url( "assets/css/print-cards.css", CHIT_FILE ),
            [],
            CHIT_VERSION
        );
        wp_enqueue_style( "chit-print-cards" );
        ?><!DOCTYPE html>
<html lang="<?php 
        echo esc_attr( get_bloginfo( "language" ) );
        ?>">
<head>
<meta charset="utf-8">
<title><?php 
        esc_html_e( "Print Chit Codes", "chit-download-codes-for-woocommerce" );
        ?></title>
<?php 
        wp_print_styles( "chit-print-cards" );
        ?>
</head>
<body>
<div class="toolbar">
    <button onclick="window.print()"><?php 
        esc_html_e( "Print / Save as PDF", "chit-download-codes-for-woocommerce" );
        ?></button>
    <?php 
        ?>
    <span class="info">
        <?php 
        printf( esc_html( 
            /* translators: %1$d: number of codes, %2$d: number of pages */
            _n(
                '%1$d code across %2$d page',
                '%1$d codes across %2$d pages',
                count( $codes ),
                "chit-download-codes-for-woocommerce"
            )
         ), count( $codes ), count( $pages ) );
        ?>
    </span>
</div>

<?php 
        if ( empty( $codes ) ) {
            ?>
    <p style="text-align: center; margin-top: 4em;">
        <?php 
            esc_html_e( "No codes match the current filter.", "chit-download-codes-for-woocommerce" );
            ?>
    </p>
<?php 
            // Fill empty cells so the last sheet still grids cleanly
            // Fill empty cells so the last sheet still grids cleanly
        } else {
            ?>
    <?php 
            foreach ( $pages as $page_codes ) {
                ?>
        <div class="sheet">
            <?php 
                foreach ( $page_codes as $code ) {
                    $product = wc_get_product( (int) $code["product_id"] );
                    $product_name = ( $product ? $product->get_name() : __( "(deleted product)", "chit-download-codes-for-woocommerce" ) );
                    $product_sku = ( $product ? $product->get_sku() : "" );
                    ?>
                <div class="card">
                    <div>
                        <div class="card-header">
                            <?php 
                    ?>
                            <div>
                                <div class="card-product"><?php 
                    echo esc_html( $product_name );
                    ?></div>
                                <?php 
                    if ( $product_sku ) {
                        ?>
                                    <div class="card-sku">
                                        <?php 
                        esc_html_e( "SKU:", "chit-download-codes-for-woocommerce" );
                        ?> <?php 
                        echo esc_html( $product_sku );
                        ?>
                                    </div>
                                <?php 
                    }
                    ?>
                            </div>
                        </div>
                        <div class="card-code"><?php 
                    echo esc_html( $code["code"] );
                    ?></div>
                    </div>
                    <div>
                        <div class="card-url"><?php 
                    echo esc_html( $redeem_url );
                    ?></div>
                    </div>
                </div>
            <?php 
                }
                ?>
            <?php 
                for ($i = count( $page_codes ); $i < 10; $i++) {
                    ?>
                <div class="card" style="border-color: transparent;"></div>
            <?php 
                }
                ?>
        </div>
    <?php 
            }
        }
        ?>
</body>
</html>
<?php 
    }

    public function maybe_handle_export() {
        if ( !isset( $_GET["page"], $_GET["action"] ) || $_GET["page"] !== "chit-view" || $_GET["action"] !== "export_codes" ) {
            return;
        }
        if ( !current_user_can( "manage_woocommerce" ) ) {
            wp_die( esc_html__( "No permission.", "chit-download-codes-for-woocommerce" ), 403 );
        }
        check_admin_referer( "chit_export_codes" );
        $args = [
            "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 ),
            "per_page"   => 100000,
            "page"       => 1,
            "orderby"    => "id",
            "order"      => "ASC",
        ];
        $codes = Chit_Codes::get_codes( $args );
        $filename = "chit-codes-" . current_time( "Y-m-d-His" ) . ".csv";
        nocache_headers();
        header( "Content-Type: text/csv; charset=utf-8" );
        header( 'Content-Disposition: attachment; filename="' . $filename . '"' );
        $redeem_url = $this->get_redeem_url();
        // UTF-8 BOM so Excel renders non-ASCII characters correctly.
        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- binary BOM, not HTML
        echo "﻿";
        echo "\"code\",\"product_name\",\"redeem_url\"\r\n";
        foreach ( $codes as $row ) {
            $product = wc_get_product( (int) $row["product_id"] );
            $product_name = ( $product ? $product->get_name() : "" );
            // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- CSV output, not HTML
            echo '"' . str_replace( '"', '""', $row["code"] ) . '",' . '"' . str_replace( '"', '""', $product_name ) . '",' . '"' . str_replace( '"', '""', $redeem_url ) . "\"\r\n";
            // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
        }
        exit;
    }

    private function get_redeem_url() : string {
        $page_id = (int) get_option( "chit_redeem_page_id", 0 );
        if ( $page_id ) {
            $url = get_permalink( $page_id );
            if ( $url ) {
                return $url;
            }
        }
        return home_url( "/" );
    }

    public function maybe_handle_revoke() {
        if ( !isset( $_GET["page"], $_GET["action"], $_GET["code_id"] ) || $_GET["page"] !== "chit-view" || $_GET["action"] !== "revoke" ) {
            return;
        }
        $code_id = (int) $_GET["code_id"];
        if ( $code_id <= 0 ) {
            return;
        }
        if ( !current_user_can( "manage_woocommerce" ) ) {
            wp_die( esc_html__( "No permission.", "chit-download-codes-for-woocommerce" ), 403 );
        }
        check_admin_referer( "chit_revoke_" . $code_id );
        $ok = Chit_Codes::revoke( $code_id );
        wp_safe_redirect( add_query_arg( [
            "page"    => "chit-view",
            "revoked" => ( $ok ? "1" : "0" ),
        ], admin_url( "admin.php" ) ) );
        exit;
    }

    public function render() {
        if ( !current_user_can( "manage_woocommerce" ) ) {
            wp_die( esc_html__( "No permission.", "chit-download-codes-for-woocommerce" ), 403 );
        }
        require_once CHIT_PATH . "includes/admin/class-chit-codes-list-table.php";
        $this->list_table = new Chit_Codes_List_Table();
        $this->list_table->prepare_items();
        ?>
        <div class="wrap">
            <h1><?php 
        esc_html_e( "View codes", "chit-download-codes-for-woocommerce" );
        ?></h1>

            <?php 
        if ( isset( $_GET["revoked"] ) ) {
            ?>
                <?php 
            if ( $_GET["revoked"] === "1" ) {
                ?>
                    <div class="notice notice-success is-dismissible">
                        <p><?php 
                esc_html_e( "Code revoked.", "chit-download-codes-for-woocommerce" );
                ?></p>
                    </div>
                <?php 
            } else {
                ?>
                    <div class="notice notice-error is-dismissible">
                        <p><?php 
                esc_html_e( "Could not revoke code (already revoked or activated?).", "chit-download-codes-for-woocommerce" );
                ?></p>
                    </div>
                <?php 
            }
            ?>
            <?php 
        }
        ?>

            <form method="get">
                <input type="hidden" name="page" value="chit-view">
                <?php 
        $this->list_table->display();
        ?>
            </form>
        </div>
        <?php 
    }

}
