<?php

namespace WPIS;

class FormEstateShortcode {

    private static $shortcode = 'wpis-form-estate';

    static public function init() {

        $class = new self();

        add_shortcode( self::$shortcode, [$class, 'generateShortcode'] );
    }

    public function generateShortcode($atts = false, $content = null) {

        $literals = [
            'form.gender.label'        => __('Gender', 'wpis'),
            'form.gender.value.male'   => __('Mister', 'wpis'),
            'form.gender.value.female' => __('Madam', 'wpis'),
            'form.gender.value.couple' => __('Mister and Madam', 'wpis'),
            'form.gender.value.other'  => __('Other', 'wpis'),
            'form.firstname.label'     => __('Firstname', 'wpis'),
            'form.lastname.label'      => __('Lastname', 'wpis'),
            'form.message.label'       => __('Message', 'wpis'),
            'form.phone.label'         => __('Phone', 'wpis'),
            'form.email.label'         => __('Email', 'wpis'),
            'form.policy.label'        => __('Privacy policy', 'wpis'),
            'form.policy.value'        => __('You affirm that you have read our confidentiality policy. You can unsubscribe at any time using the unsubscribe links.', 'wpis'),
            'form.submit.value'        => __('Send', 'wpis'),
            'message.success'          => __('Your message has been sent successfully !', 'wpis'),
            'message.processing'       => __('Sending ...', 'wpis'),
            'error.single'             => __('An error has occurred:', 'wpis'),
            'error.multiple'           => __('Several errors occurred:', 'wpis')
        ];

        wp_enqueue_script('wpis_forms', plugin_dir_url(__FILE__) . '../../dist/client/wpis-forms.js');

        global $post;

        $allowedStyleOption = ['on', 'off'];
        $allowedFormTypes = ['default'];

        if( isset($atts['type']) && !in_array($atts['type'], $allowedFormTypes) ){
            return $this->generateError(__('Error, only the following form type are allowed: ', 'wpis') . implode(', ', $allowedFormTypes));
        };

        if( isset($atts['style']) && !in_array($atts['style'], $allowedStyleOption) ){
            return $this->generateError(__('Error, only the following style option are allowed: ', 'wpis') . implode(', ', $allowedStyleOption));
        };

        if( ! $estateId = get_post_meta($post->ID, 'wpis_id', true) ){
            return $this->generateError('Error, this form should only be used on estate pages, no estate ID found.');
        }

        if( isset($atts['submit']) && $atts['submit'] !== "" ){
            $literals['form.submit.value'] = $atts['submit'];
        };

        $formType = $atts['type'] ?? 'default';
        $form = file_get_contents(__DIR__ . '/../../templates/form/estate.' . $formType . '.form.html');

        $form = str_replace('%estateId%', $estateId, $form);
        $form = str_replace('%postId%', $post->ID, $form);

        if( isset($atts['style']) && $atts['style'] === 'off' ){
            $form = $this->removeDefaultStyle($form);
        }

        wp_localize_script('wpis_forms', 'literals', $literals);

        foreach($literals as $key => $value){
            $form = preg_replace('/{{\s*' . preg_quote($key, '/') . '\s*}}/', $value, $form);
        }

        return $form;
    }

    public function generateError( $message ){
        return sprintf('[ %s ]', self::$shortcode) . ' : ' .  $message;
    }

    private function removeDefaultStyle($html) {
        $tagName = 'style';
        $html = preg_replace('/<'.$tagName.'[^>]*>.*?<\/'.$tagName.'>/is', '', $html);
        return $html;
    }
}