<?php

namespace HelpGent\App\Providers;

defined( 'ABSPATH' ) || exit;

use HelpGent\App\Repositories\FormRepository;
use HelpGent\App\Repositories\QuizRepository;
use HelpGent\WpMVC\Contracts\Provider;
use HelpGent\WpMVC\Enqueue\Enqueue;
use HelpGent\WpMVC\View\View;

class ShortCodeServiceProvider implements Provider {
    public function boot() {
        add_action( 'init', [ $this, 'action_init' ] );
    }

    /**
     * Fires after WordPress has finished loading but before any headers are sent.
     *
     */
    public function action_init() : void {
        add_shortcode( "helpgent-form", [$this, 'content'] );
        add_shortcode( "helpgent_user_dashboard", [$this, 'user_dashboard'] );
        add_shortcode( "helpgent_messages", [$this, 'user_dashboard'] );
    }

    public function content( $attr ) {

        if ( ! is_array( $attr ) || empty( $attr['id'] ) ) {
            return;
        }

        $id          = intval( $attr['id'] );
        $full_screen = in_array( 'full-screen', $attr, true );

        /**
         * @var FormRepository $form_repository
         */
        $form_repository = helpgent_singleton( FormRepository::class );

        $form = $form_repository->get_by_id_publish( $id );

        if ( ! $form ) {
            return;
        }

        /**
         * @var QuizRepository $quiz_repository
         */
        $quiz_repository = helpgent_singleton( QuizRepository::class );
        $form            = $quiz_repository->sanitize_public_form( $form );

        include_once helpgent_dir( 'enqueues/register.php' );
        include_once helpgent_dir( 'enqueues/enqueue-common.php' );

        wp_enqueue_script( 'helpgent/form/shortcode' );

        return View::get( 'form-content', compact( 'form', 'full_screen' ) );
    }

    public function user_dashboard() {        
        include_once helpgent_dir( 'enqueues/register.php' );
        include_once helpgent_dir( 'enqueues/enqueue-common.php' );

        Enqueue::script( 'helpgent/userdashboard/shortcode', 'build/js/frontend/UserDashboard/index', ['helpgent/notification'] );

        do_action( 'helpgent_maybe_create_user' );
        do_action( 'helpgent_before_render_dashboard' );

        return View::get( 'user-dashboard' );
    }
}
