<?php

namespace Vendtics\App\Providers\Admin;

defined( "ABSPATH" ) || exit;

use Vendtics\WpMVC\Contracts\Provider;
use Vendtics\App\Repositories\SettingsRepository;
use Vendtics\WpMVC\Exceptions\Exception;

class MenuServiceProvider implements Provider {
    public function boot() {
        add_action( 'admin_menu', [$this, 'action_admin_menu'] );
    }

    public function action_admin_menu() {
        $page_url = admin_url( 'admin.php?page=vendtics' );
        add_menu_page( "Vendtics", 'Vendtics', 'manage_options', 'vendtics-menu', function () { }, '', 2 );
        // add_submenu_page( 'vendtics-menu', esc_html__( 'Dashboard', 'vendtics' ), esc_html__( 'Dashboard', 'vendtics' ), 'manage_options', 'vendtics', [$this, 'content'] );
        add_submenu_page( 'vendtics-menu', esc_html__( 'Contacts', 'vendtics' ), esc_html__( 'Contacts', 'vendtics' ), 'manage_options', 'vendtics', [$this, 'content'] );
        add_submenu_page( 'vendtics-menu', esc_html__( 'Campaigns', 'vendtics' ), esc_html__( 'Campaigns', 'vendtics' ), 'manage_options', $page_url . '#/campaigns' );
        // add_submenu_page( 'vendtics-menu', esc_html__( 'Automations', 'vendtics' ), esc_html__( 'Automations', 'vendtics' ), 'manage_options', $page_url . '#/automations' );
        add_submenu_page( 'vendtics-menu', esc_html__( 'Settings', 'vendtics' ), esc_html__( 'Settings', 'vendtics' ), 'manage_options', $page_url . '#/settings' );
        remove_submenu_page( 'vendtics-menu', 'vendtics-menu' );
    }

    public function content() {
        $this->create_unsubscrption_confirm_page();

        add_filter( 'user_can_richedit', '__return_true' );
        vendtics_render( '<div class="vendtics-root"></div>' );
    }

    protected function create_unsubscrption_confirm_page() {
        $repository          = vendtics_singleton( SettingsRepository::class );
        $settings            = $repository->get_settings();
        $general_settings    = $settings['general'];
        $unsubscription_page =  get_post( intval( $general_settings['unsubscribe_confirm_page'] ) );

        if ( empty( $unsubscription_page ) || 'publish' !== $unsubscription_page->post_status ) {
            $new_page_id = wp_insert_post(
                [
                    'post_title'   => "Vendtics Unsubscribe Confirmation",
                    'post_content' => "<!-- wp:shortcode -->
    [vendtics_unsubscribe_confirmation]
    <!-- /wp:shortcode -->",
                    'post_status'  => 'publish',
                    'post_type'    => 'page',
                    'post_name'    => "unsubscribe-confirmation"
                ]
            );

            $settings['general']['unsubscribe_confirm_page'] = "{$new_page_id}";
            $repository->save_settings( $settings );
        }
    }
}