<?php

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

class Chit_Admin_Reports
{
    public function render()
    {
        if (!current_user_can("manage_woocommerce")) {
            wp_die(esc_html__("No permission.", "chit-download-codes-for-woocommerce"), 403);
        }

        $stats = Chit_Codes::get_stats();
        $top = Chit_Codes::get_top_products(10);
        ?>
        <div class="wrap">
            <h1><?php esc_html_e("Reports", "chit-download-codes-for-woocommerce"); ?></h1>

            <?php Chit_Admin::render_stat_tiles($stats); ?>

            <h2 style="margin-top: 2em;">
                <?php esc_html_e("Top products", "chit-download-codes-for-woocommerce"); ?>
            </h2>

            <?php if (empty($top)): ?>
                <p><?php esc_html_e("No codes generated yet.", "chit-download-codes-for-woocommerce"); ?></p>
            <?php else: ?>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e("Product", "chit-download-codes-for-woocommerce"); ?></th>
                            <th><?php esc_html_e("Generated", "chit-download-codes-for-woocommerce"); ?></th>
                            <th><?php esc_html_e("Activated", "chit-download-codes-for-woocommerce"); ?></th>
                            <th><?php esc_html_e(
                                "Activation rate",
                                "chit-download-codes-for-woocommerce"
                            ); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($top as $row):
                            $product = wc_get_product((int) $row["product_id"]);
                            $name = $product
                                ? $product->get_name()
                                : __("(deleted product)", "chit-download-codes-for-woocommerce");
                            $total = (int) $row["total"];
                            $activated = (int) $row["activated"];
                            $rate = $total > 0
                                ? round(($activated / $total) * 100, 1)
                                : 0;
                            ?>
                            <tr>
                                <td><?php echo esc_html($name); ?></td>
                                <td><?php echo esc_html($total); ?></td>
                                <td><?php echo esc_html($activated); ?></td>
                                <td><?php echo esc_html($rate); ?>%</td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div>
        <?php
    }
}
