<?php

namespace Zoomyboy\Stepper;

use GuzzleHttp\Client;
use Dotenv\Dotenv;

class Stepper
{

    public string $url;
    public string $scriptUrl;
    public string $baseUrl;

    public function loadEnv(string $dir): void
    {
        $env = Dotenv::createImmutable($dir);
        $env = $env->safeLoad();
        $this->baseUrl = $env['STEPPER_URL'] ?? 'https://app.immotooler.com';
    }

    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($this->baseUrl . '/api/lead', [
            'json' => $payload,
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $this->token(),
            ]
        ]);
    }

    protected function token(): string
    {
        return get_option('it-slider-options')['it-slider-access-key'];
    }
}
