<?php

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

class Chit_Admin_Import
{
    public function __construct()
    {
        add_action("admin_post_chit_import_upload", [$this, "handle_upload"]);
        add_action("admin_post_chit_import_start", [$this, "handle_start"]);
        add_action("admin_post_chit_import_discard", [$this, "handle_discard"]);
        add_action("admin_post_chit_import_resume", [$this, "handle_resume"]);
        add_action("admin_post_chit_import_cancel", [$this, "handle_cancel"]);
        add_action("admin_post_chit_import_delete", [$this, "handle_delete"]);
        add_action("admin_post_chit_import_sample", [$this, "handle_sample"]);
    }

    private function require_cap(): void
    {
        if (!current_user_can("manage_woocommerce")) {
            wp_die(esc_html__("No permission.", "chit-download-codes-for-woocommerce"), 403);
        }
    }

    private function redirect(array $args = []): void
    {
        wp_safe_redirect(
            add_query_arg(
                array_merge(["page" => "chit-import"], $args),
                admin_url("admin.php")
            )
        );
        exit();
    }

    // ------------------------------------------------------------- handlers

    public function handle_upload(): void
    {
        check_admin_referer("chit_import_upload");
        $this->require_cap();

        if (empty($_FILES["import_file"]["name"])) {
            $this->redirect(["error" => "nofile"]);
        }
        if (
            strtolower(
                pathinfo(
                    sanitize_file_name(wp_unslash($_FILES["import_file"]["name"])),
                    PATHINFO_EXTENSION
                )
            ) !== "csv"
        ) {
            $this->redirect(["error" => "upload"]);
        }
        require_once ABSPATH . "wp-admin/includes/file.php";
        add_filter("upload_dir", [$this, "filter_upload_dir"]);
        $uploaded = wp_handle_upload($_FILES["import_file"], [
            "test_form" => false,
            "mimes" => ["csv" => "text/csv"],
        ]);
        remove_filter("upload_dir", [$this, "filter_upload_dir"]);
        if (!empty($uploaded["error"]) || empty($uploaded["file"])) {
            $this->redirect(["error" => "upload"]);
        }
        $path = $uploaded["file"];

        $summary = Chit_Import::validate($path);

        $token = strtolower(wp_generate_password(12, false));
        set_transient(
            "chit_import_ready_$token",
            [
                "path" => $path,
                "filename" => basename($path),
                "summary" => $summary,
            ],
            HOUR_IN_SECONDS
        );

        $this->redirect(["token" => $token]);
    }

    /**
     * Routes uploads into the protected chit-imports holding directory.
     */
    public function filter_upload_dir(array $dirs): array
    {
        $dirs["path"] = Chit_Import::ensure_import_dir($dirs["basedir"]);
        $dirs["url"] = $dirs["baseurl"] . "/chit-imports";
        $dirs["subdir"] = "/chit-imports";
        return $dirs;
    }

    public function handle_start(): void
    {
        check_admin_referer("chit_import_start");
        $this->require_cap();

        $token = sanitize_key($_POST["token"] ?? "");
        $ready = get_transient("chit_import_ready_$token");
        if (!$ready || empty($ready["summary"]["ok"])) {
            $this->redirect(["error" => "expired"]);
        }
        delete_transient("chit_import_ready_$token");

        $result = Chit_Import::start(
            $ready["path"],
            $ready["filename"],
            (int) $ready["summary"]["total_rows"]
        );
        if (is_wp_error($result)) {
            $this->redirect(["error" => $result->get_error_code()]);
        }
        $this->redirect(["started" => "1"]);
    }

    public function handle_discard(): void
    {
        check_admin_referer("chit_import_discard");
        $this->require_cap();

        $token = sanitize_key($_POST["token"] ?? "");
        $ready = get_transient("chit_import_ready_$token");
        if ($ready) {
            delete_transient("chit_import_ready_$token");
            if (file_exists($ready["path"])) {
                @unlink($ready["path"]);
            }
        }
        $this->redirect();
    }

    public function handle_resume(): void
    {
        check_admin_referer("chit_import_resume");
        $this->require_cap();
        Chit_Import::resume();
        $this->redirect();
    }

    public function handle_cancel(): void
    {
        check_admin_referer("chit_import_cancel");
        $this->require_cap();
        Chit_Import::cancel();
        $this->redirect();
    }

    public function handle_delete(): void
    {
        check_admin_referer("chit_import_delete");
        $this->require_cap();
        $batch_id = absint($_POST["batch_id"] ?? 0);
        if ($batch_id > 0) {
            $deleted = Chit_Import::delete_import($batch_id);
            $this->redirect(["deleted" => $deleted]);
        }
        $this->redirect();
    }

    public function handle_sample(): void
    {
        check_admin_referer("chit_import_sample");
        $this->require_cap();
        nocache_headers();
        header("Content-Type: text/csv; charset=utf-8");
        header('Content-Disposition: attachment; filename="chit-import-sample.csv"');
        echo "code,sku,status,activated_at,activated_email\r\n";
        echo "LEGACY-A1B2-C3D4,BOOK-001,unused,,\r\n";
        echo "LEGACY-E5F6-G7H8,BOOK-001,activated,2025-11-03 14:22:00,customer@example.com\r\n";
        echo "OLDSHOP-9J8K7,ALBUM-002,revoked,,\r\n";
        exit();
    }

    // --------------------------------------------------------------- render

    public function render(): void
    {
        $this->require_cap();
        ?>
        <div class="wrap">
            <h1><?php esc_html_e("Import codes", "chit-download-codes-for-woocommerce"); ?></h1>
            <?php
            $this->render_notices();

            $state = Chit_Import::get_state();
            if ($state) {
                $this->render_progress($state);
            } else {
                $token = sanitize_key($_GET["token"] ?? "");
                $ready = $token ? get_transient("chit_import_ready_$token") : false;
                if ($ready) {
                    $this->render_summary($token, $ready);
                } else {
                    $this->render_form();
                }
            }

            $this->render_history();
            ?>
        </div>
        <?php
    }

    private function render_notices(): void
    {
        $messages = [
            "upload" => __("The upload failed. Only .csv files are accepted.", "chit-download-codes-for-woocommerce"),
            "nofile" => __("Choose a file to upload.", "chit-download-codes-for-woocommerce"),
            "expired" => __("That validation result expired. Please upload the file again.", "chit-download-codes-for-woocommerce"),
            "chit_import_busy" => __("Another import is already running.", "chit-download-codes-for-woocommerce"),
            "chit_import_as" => __("Action Scheduler is unavailable — is WooCommerce active?", "chit-download-codes-for-woocommerce"),
        ];
        $error = sanitize_key($_GET["error"] ?? "");
        if ($error && isset($messages[$error])) {
            echo '<div class="notice notice-error is-dismissible"><p>' .
                esc_html($messages[$error]) .
                "</p></div>";
        }
        if (isset($_GET["started"])) {
            echo '<div class="notice notice-success is-dismissible"><p>' .
                esc_html__("Import started. It runs in the background — you can leave this page.", "chit-download-codes-for-woocommerce") .
                "</p></div>";
        }
        if (isset($_GET["deleted"])) {
            echo '<div class="notice notice-success is-dismissible"><p>' .
                sprintf(
                    /* translators: %d: number of deleted codes */
                    esc_html__("Import deleted (%d codes removed).", "chit-download-codes-for-woocommerce"),
                    absint($_GET["deleted"])
                ) .
                "</p></div>";
        }
    }

    private function render_progress(array $state): void
    {
        $processed = (int) $state["imported"] + (int) $state["skipped"];
        $total = max(1, (int) $state["total_rows"]);
        $percent = min(100, (int) floor(($processed / $total) * 100));
        ?>
        <h2><?php echo esc_html(
            sprintf(
                /* translators: %s: CSV filename */
                __("Importing %s", "chit-download-codes-for-woocommerce"),
                $state["filename"]
            )
        ); ?></h2>

        <?php if ($state["status"] === "failed"): ?>
            <div class="notice notice-error"><p>
                <?php echo esc_html(
                    sprintf(
                        /* translators: %s: error message */
                        __("Import failed: %s", "chit-download-codes-for-woocommerce"),
                        $state["error"]
                    )
                ); ?>
            </p></div>
        <?php endif; ?>

        <div style="max-width: 480px; background: #dcdcde; border-radius: 3px; height: 22px; overflow: hidden; margin: 1em 0;">
            <div style="width: <?php echo esc_attr($percent); ?>%; background: #2271b1; height: 100%;"></div>
        </div>
        <p>
            <?php echo esc_html(
                sprintf(
                    /* translators: 1: processed row count, 2: total row count, 3: imported count, 4: skipped count */
                    __("%1\$s of %2\$s rows processed — %3\$s imported, %4\$s skipped as duplicates.", "chit-download-codes-for-woocommerce"),
                    number_format_i18n($processed),
                    number_format_i18n((int) $state["total_rows"]),
                    number_format_i18n((int) $state["imported"]),
                    number_format_i18n((int) $state["skipped"])
                )
            ); ?>
        </p>

        <p>
            <?php if ($state["status"] === "failed"): ?>
                <form method="post" action="<?php echo esc_url(admin_url("admin-post.php")); ?>" style="display: inline;">
                    <input type="hidden" name="action" value="chit_import_resume">
                    <?php wp_nonce_field("chit_import_resume"); ?>
                    <button type="submit" class="button button-primary"><?php esc_html_e("Resume import", "chit-download-codes-for-woocommerce"); ?></button>
                </form>
            <?php endif; ?>
            <form method="post" action="<?php echo esc_url(admin_url("admin-post.php")); ?>" style="display: inline;">
                <input type="hidden" name="action" value="chit_import_cancel">
                <?php wp_nonce_field("chit_import_cancel"); ?>
                <button type="submit" class="button" onclick="return confirm('<?php echo esc_js(
                    __("Cancel this import? Rows already imported will remain (you can delete them from the history below).", "chit-download-codes-for-woocommerce")
                ); ?>');"><?php esc_html_e("Cancel import", "chit-download-codes-for-woocommerce"); ?></button>
            </form>
        </p>

        <?php if ($state["status"] === "running"): ?>
            <p class="description"><?php esc_html_e("This page refreshes automatically.", "chit-download-codes-for-woocommerce"); ?></p>
            <script>setTimeout(function () { window.location.reload(); }, 4000);</script>
        <?php endif;
    }

    private function render_summary(string $token, array $ready): void
    {
        $summary = $ready["summary"];
        ?>
        <h2><?php echo esc_html(
            sprintf(
                /* translators: %s: CSV filename */
                __("Dry run: %s", "chit-download-codes-for-woocommerce"),
                $ready["filename"]
            )
        ); ?></h2>

        <table class="widefat striped" style="max-width: 640px;">
            <tbody>
                <tr>
                    <td><?php esc_html_e("Data rows", "chit-download-codes-for-woocommerce"); ?></td>
                    <td><strong><?php echo esc_html(number_format_i18n((int) $summary["total_rows"])); ?></strong></td>
                </tr>
                <tr>
                    <td><?php esc_html_e("Unique SKUs", "chit-download-codes-for-woocommerce"); ?></td>
                    <td><?php echo esc_html(number_format_i18n((int) $summary["unique_skus"])); ?></td>
                </tr>
                <?php foreach ($summary["statuses"] as $status => $count):
                    if (!$count) {
                        continue;
                    } ?>
                    <tr>
                        <td><?php echo esc_html(
                            sprintf(
                                /* translators: %s: code status */
                                __("Status: %s", "chit-download-codes-for-woocommerce"),
                                $status
                            )
                        ); ?></td>
                        <td><?php echo esc_html(number_format_i18n((int) $count)); ?></td>
                    </tr>
                <?php
                endforeach; ?>
                <tr>
                    <td><?php esc_html_e("Errors", "chit-download-codes-for-woocommerce"); ?></td>
                    <td><?php echo esc_html(number_format_i18n((int) $summary["error_count"])); ?></td>
                </tr>
                <tr>
                    <td><?php esc_html_e("Warnings", "chit-download-codes-for-woocommerce"); ?></td>
                    <td><?php echo esc_html(number_format_i18n((int) $summary["warning_count"])); ?></td>
                </tr>
            </tbody>
        </table>

        <?php $this->render_issue_list(__("Errors", "chit-download-codes-for-woocommerce"), $summary["errors"], (int) $summary["error_count"]); ?>
        <?php $this->render_issue_list(__("Warnings", "chit-download-codes-for-woocommerce"), $summary["warnings"], (int) $summary["warning_count"]); ?>

        <?php if ($summary["ok"]): ?>
            <p><?php esc_html_e("No blocking problems found. Nothing has been written yet.", "chit-download-codes-for-woocommerce"); ?></p>
        <?php else: ?>
            <p><strong><?php esc_html_e("The file has errors and cannot be imported. Fix the rows above and upload it again.", "chit-download-codes-for-woocommerce"); ?></strong></p>
        <?php endif; ?>

        <p>
            <?php if ($summary["ok"]): ?>
                <form method="post" action="<?php echo esc_url(admin_url("admin-post.php")); ?>" style="display: inline;">
                    <input type="hidden" name="action" value="chit_import_start">
                    <input type="hidden" name="token" value="<?php echo esc_attr($token); ?>">
                    <?php wp_nonce_field("chit_import_start"); ?>
                    <button type="submit" class="button button-primary">
                        <?php echo esc_html(
                            sprintf(
                                /* translators: %s: number of rows */
                                __("Import %s rows", "chit-download-codes-for-woocommerce"),
                                number_format_i18n((int) $summary["total_rows"])
                            )
                        ); ?>
                    </button>
                </form>
            <?php endif; ?>
            <form method="post" action="<?php echo esc_url(admin_url("admin-post.php")); ?>" style="display: inline;">
                <input type="hidden" name="action" value="chit_import_discard">
                <input type="hidden" name="token" value="<?php echo esc_attr($token); ?>">
                <?php wp_nonce_field("chit_import_discard"); ?>
                <button type="submit" class="button"><?php esc_html_e("Discard", "chit-download-codes-for-woocommerce"); ?></button>
            </form>
        </p>
        <?php
    }

    private function render_issue_list(string $label, array $issues, int $total): void
    {
        if (!$issues) {
            return;
        }
        ?>
        <h3><?php echo esc_html($label); ?></h3>
        <ul style="list-style: disc; padding-left: 2em;">
            <?php foreach ($issues as $issue): ?>
                <li>
                    <?php echo esc_html(
                        sprintf(
                            /* translators: 1: CSV line number, 2: message */
                            __("Line %1\$d: %2\$s", "chit-download-codes-for-woocommerce"),
                            (int) $issue[0],
                            $issue[1]
                        )
                    ); ?>
                </li>
            <?php endforeach; ?>
            <?php if ($total > count($issues)): ?>
                <li><?php echo esc_html(
                    sprintf(
                        /* translators: %s: count of additional unlisted issues */
                        __("… and %s more.", "chit-download-codes-for-woocommerce"),
                        number_format_i18n($total - count($issues))
                    )
                ); ?></li>
            <?php endif; ?>
        </ul>
        <?php
    }

    private function render_form(): void
    {
        $sample_url = wp_nonce_url(
            add_query_arg("action", "chit_import_sample", admin_url("admin-post.php")),
            "chit_import_sample"
        );
        ?>
        <p><?php esc_html_e(
            "Bring codes you issued elsewhere into Chit, including their redemption state. Prepare a CSV in the format below, upload it, review the dry run, then start the import.",
            "chit-download-codes-for-woocommerce"
        ); ?></p>

        <h2><?php esc_html_e("File format", "chit-download-codes-for-woocommerce"); ?></h2>
        <pre style="background: #fff; border: 1px solid #c3c4c7; padding: 1em; max-width: 640px; overflow-x: auto;">code,sku,status,activated_at,activated_email</pre>
        <ul style="list-style: disc; padding-left: 2em; max-width: 720px;">
            <li><?php echo wp_kses(
                __("<code>code</code> — required. 4–64 characters: letters, numbers, dashes. Stored uppercase.", "chit-download-codes-for-woocommerce"),
                ["code" => []]
            ); ?></li>
            <li><?php echo wp_kses(
                __("<code>sku</code> — required. The SKU of the WooCommerce product (or variation) the code unlocks.", "chit-download-codes-for-woocommerce"),
                ["code" => []]
            ); ?></li>
            <li><?php echo wp_kses(
                __("<code>status</code> — <code>unused</code>, <code>activated</code>, <code>revoked</code>, or <code>expired</code>. Blank means unused.", "chit-download-codes-for-woocommerce"),
                ["code" => []]
            ); ?></li>
            <li><?php echo wp_kses(
                __("<code>activated_at</code> — optional date/time for activated codes, e.g. <code>2025-11-03 14:22:00</code>.", "chit-download-codes-for-woocommerce"),
                ["code" => []]
            ); ?></li>
            <li><?php echo wp_kses(
                __("<code>activated_email</code> — optional. Matched to an existing user account; left unlinked if no user has that email.", "chit-download-codes-for-woocommerce"),
                ["code" => []]
            ); ?></li>
        </ul>
        <p>
            <a href="<?php echo esc_url($sample_url); ?>"><?php esc_html_e("Download a sample CSV", "chit-download-codes-for-woocommerce"); ?></a>
        </p>
        <p class="description" style="max-width: 720px;">
            <?php esc_html_e(
                "Duplicate codes (in the file or already in Chit) are skipped, never overwritten. Imported codes redeem exactly like generated ones.",
                "chit-download-codes-for-woocommerce"
            ); ?>
        </p>

        <h2><?php esc_html_e("Upload", "chit-download-codes-for-woocommerce"); ?></h2>
        <form method="post" action="<?php echo esc_url(admin_url("admin-post.php")); ?>" enctype="multipart/form-data">
            <input type="hidden" name="action" value="chit_import_upload">
            <?php wp_nonce_field("chit_import_upload"); ?>
            <table class="form-table"><tbody>
                <tr>
                    <th><label for="chit-import-file"><?php esc_html_e("CSV file", "chit-download-codes-for-woocommerce"); ?></label></th>
                    <td><input type="file" id="chit-import-file" name="import_file" accept=".csv"></td>
                </tr>
            </tbody></table>
            <?php submit_button(esc_html__("Validate file", "chit-download-codes-for-woocommerce"), "primary", "submit", false); ?>
        </form>
        <?php
    }

    private function render_history(): void
    {
        $history = Chit_Import::get_history();
        if (!$history) {
            return;
        }
        ?>
        <h2 style="margin-top: 2em;"><?php esc_html_e("Past imports", "chit-download-codes-for-woocommerce"); ?></h2>
        <table class="wp-list-table widefat fixed striped" style="max-width: 900px;">
            <thead>
                <tr>
                    <th><?php esc_html_e("File", "chit-download-codes-for-woocommerce"); ?></th>
                    <th><?php esc_html_e("Batch", "chit-download-codes-for-woocommerce"); ?></th>
                    <th><?php esc_html_e("Imported", "chit-download-codes-for-woocommerce"); ?></th>
                    <th><?php esc_html_e("Skipped", "chit-download-codes-for-woocommerce"); ?></th>
                    <th><?php esc_html_e("Finished", "chit-download-codes-for-woocommerce"); ?></th>
                    <th><?php esc_html_e("Status", "chit-download-codes-for-woocommerce"); ?></th>
                    <th><?php esc_html_e("Actions", "chit-download-codes-for-woocommerce"); ?></th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($history as $entry): ?>
                    <tr>
                        <td><?php echo esc_html($entry["filename"]); ?></td>
                        <td>
                            <a href="<?php echo esc_url(
                                add_query_arg(
                                    ["page" => "chit-view", "batch_id" => (int) $entry["batch_id"]],
                                    admin_url("admin.php")
                                )
                            ); ?>">#<?php echo (int) $entry["batch_id"]; ?></a>
                        </td>
                        <td><?php echo esc_html(number_format_i18n((int) $entry["imported"])); ?></td>
                        <td><?php echo esc_html(number_format_i18n((int) $entry["skipped"])); ?></td>
                        <td><?php echo esc_html($entry["finished_at"]); ?></td>
                        <td><?php echo esc_html($entry["status"]); ?></td>
                        <td>
                            <form method="post" action="<?php echo esc_url(admin_url("admin-post.php")); ?>">
                                <input type="hidden" name="action" value="chit_import_delete">
                                <input type="hidden" name="batch_id" value="<?php echo (int) $entry["batch_id"]; ?>">
                                <?php wp_nonce_field("chit_import_delete"); ?>
                                <button type="submit" class="button button-small button-link-delete" onclick="return confirm('<?php echo esc_js(
                                    __("Delete every code from this import, including any that have since been redeemed? This cannot be undone.", "chit-download-codes-for-woocommerce")
                                ); ?>');"><?php esc_html_e("Delete import", "chit-download-codes-for-woocommerce"); ?></button>
                            </form>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php
    }
}
