<?php

namespace Zoomyboy\Stepper;

use GuzzleHttp\Client;
use Dotenv\Dotenv;

class Stepper
{

    public string $url;
    public string $scriptUrl;

    public function loadEnv(string $dir): void
    {
        $env = Dotenv::createImmutable($dir);
        $env->safeLoad();
    }

    public function initFrontend()
    {
        add_action('wp_enqueue_scripts', [$this, 'enqueue']);
        add_action('wp_ajax_nopriv_stepper_submit', [$this, 'onSubmit']);
        add_action('wp_ajax_stepper_submit', [$this, 'onSubmit']);

        if (!is_admin()) {
            add_action('wp_footer', [$this, 'enqueueOverwrite']);
            add_shortcode('stepper', [$this, 'handle']);
        }
    }

    public function enqueueOverwrite(): void
    {
        ob_start();
        require(__DIR__ . '/../templates/overwrite.htm');
        echo ob_get_clean();
    }

    public function enqueue()
    {
        wp_enqueue_script('stepper-js', $this->scriptUrl . 'app.js', [], false, true);
        wp_enqueue_style('stepper-css', $this->scriptUrl . 'app.css');
    }

    public function handle()
    {
        ob_start();
        require(__DIR__ . '/../templates/stepper.htm');
        return ob_get_clean();
    }

    public function onSubmit()
    {
        $client = new Client();

        $payload = json_decode(file_get_contents('php://input'), true);
        $client->post(STEPPER_URL, [
            'json' => $payload,
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . STEPPER_TOKEN,
            ]
        ]);
    }
}
