<?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(['http_errors' => false]);

        $payload = json_decode(file_get_contents('php://input'), true);
        $response = $client->post($this->baseUrl . '/api/lead', [
            'json' => $payload,
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . $this->token(),
            ]
        ]);

        if ($response->getStatusCode() === 401) {
            $this->error('Anmeldung fehlgeschlagen.');
        }

        if ($response->getStatusCode() === 500) {
            $this->error('Ein Fehler ist aufgetreten.');
        }

        if ($response->getStatusCode() === 422) {
            wp_send_json(json_decode((string) $response->getBody()), 422);
        }
    }

    private function error(string $error): void
    {
        wp_send_json(['message' => '', 'errors' => ['error' => [$error]]], 422);
    }

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