<?php
/**
 * Renders the withdrawal form.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wp;

use SkyServers\Retragere\Wc\Bootstrap;
use SkyServers\Retragere\Wc\OrderLookup;

/**
 * Templates are overridable from the theme, the same way WooCommerce does it.
 */
final class Shortcode
{
    public const TAG = 'skyservers_retragere';

    public static function register(): void
    {
        add_shortcode(self::TAG, [self::class, 'render']);
    }

    public static function render(): string
    {
        CacheExclusion::apply();

        wp_enqueue_style(
            'ssrc-form',
            SSRC_URL . 'assets/form.css',
            [],
            SSRC_VERSION
        );

        wp_enqueue_script(
            'ssrc-form',
            SSRC_URL . 'assets/form.js',
            [],
            SSRC_VERSION,
            true
        );

        wp_localize_script(
            'ssrc-form',
            'ssrcForm',
            [
                'ajaxUrl'     => admin_url('admin-ajax.php'),
                'linesAction' => \SkyServers\Retragere\Wc\LinesAjax::ACTION,
            ]
        );

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display switch.
        $reference = isset($_GET['ssrc_ref']) ? sanitize_text_field(wp_unslash((string) $_GET['ssrc_ref'])) : '';

        if ('' !== $reference) {
            return self::template('success', ['reference' => $reference]);
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only display switch.
        $raw    = isset($_GET['ssrc_err']) ? sanitize_text_field(wp_unslash((string) $_GET['ssrc_err'])) : '';
        $errors = array_filter(explode(',', $raw));

        $orders   = [];
        $selected = 0;

        if (Bootstrap::isActive() && is_user_logged_in()) {
            $orders = OrderLookup::forCustomer(get_current_user_id());
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only preselection.
        if (isset($_GET['ssrc_order'])) {
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only preselection.
            $selected = (int) $_GET['ssrc_order'];
        }

        $lines = [];

        if (Bootstrap::isActive() && $selected > 0) {
            $order = OrderLookup::byId($selected);

            if (null !== $order && (int) $order->get_customer_id() === get_current_user_id()) {
                $evaluation = \SkyServers\Retragere\Wc\OrderEvaluation::forOrder($order);
                $lines      = $evaluation['lines'];
            }
        }

        return self::template(
            'form',
            [
                'errors'     => $errors,
                'settings'   => Settings::all(),
                'actionUrl'  => admin_url('admin-post.php'),
                'nonceField' => wp_nonce_field('ssrc_submit', 'ssrc_nonce', true, false),
                'orders'     => $orders,
                'selected'   => $selected,
                'lines'      => $lines,
                'wcActive'   => Bootstrap::isActive(),
            ]
        );
    }

    /**
     * @param array<string,mixed> $args
     */
    public static function template(string $name, array $args): string
    {
        $relative = 'skyservers-retragere-contract/' . $name . '.php';
        $file     = locate_template($relative);

        if ('' === $file) {
            $file = SSRC_PATH . 'templates/' . $name . '.php';
        }

        if (!file_exists($file)) {
            return '';
        }

        ob_start();
        include $file;

        return (string) ob_get_clean();
    }
}
