<?php

class Widgetkit_Pro_Library {
    protected $api;
    public function __construct() {
        $this->api = 'http://demo.themesgrove.com/widgetkit-template-api/';
        add_action('admin_menu', array($this, 'widgetkit_pro_library_admin_options'));

        // Template save
        add_action('wp_ajax_widgetkit_save_import_remote_template_page', [$this, 'widgetkit_save_import_remote_template_page']);
        add_action('wp_ajax_widgetkit_save_import_elementor_template', [$this, 'widgetkit_save_import_elementor_template']);


        add_action('admin_enqueue_scripts',array($this,'widgetkit_pro_library_scripts'));
    }

    public function widgetkit_pro_library_admin_options() {
        add_submenu_page(
            'widgetkit-settings',
	        __( 'Template Library', 'widgetkit-pro' ),
            __( 'Template Library', 'widgetkit-pro' ),
	        'manage_options',
	        'widgetkit-template-library',
	        array($this, 'display_widgetkit_templates')
        );
    }

    public function widgetkit_pro_library_scripts( $screen ) {
        if(  $screen == 'widgetkit_page_widgetkit-template-library' ) {
            wp_enqueue_script('widgetkit-pro-template-library-js', plugin_dir_url( __FILE__). 'js/template-library.js' , array('jquery'), '1.0' , true );
            $js_info = array(
                'ajaxurl' => admin_url( 'admin-ajax.php' ),
                'site_admin_url' => admin_url( )
            );

            wp_localize_script( 'widgetkit-pro-template-library-js', 'settings', $js_info );
        }
    }

    /**
    * Display Widgetkit Templates
    */
    public function display_widgetkit_templates() { 

        $response = wp_remote_get($this->api . 'info.json');
        $responseBody = wp_remote_retrieve_body( $response );
        $result = json_decode($responseBody,true);
        $action = isset($_GET['action']) ? $_GET['action'] : '';
        $tid = isset($_GET['id']) ? $_GET['id'] : '';
        $package_type = isset($_GET['package']) ? $_GET['package'] : '';
        //var_dump($result['library']['templates']);
        if( $action != 'single-template' ) :
        ?>
        <div class="wrap">
            <div class="wk-container">
                <div class="wk-header wk-padding-small wk-card wk-card-default wk-margin-medium-top">
                    <div class="wk-header__top wk-margin-small-bottom">
                        <div class="wk-text-center wk-padding-small">
                            <img src="<?php echo WKP_URL . 'dist/images/logo-t.svg'; ?>" width="200" wk-svg>
                        </div>
                    </div>
                </div>
                <div class="wk-main wk-margin wk-padding-small widgetkit-templates-wrapper">
                    <div class="wk-grid">
                        <div class="wk-width-1-1">
                            <div class="wk-card-small">
                                <div class="wk-grid wk-child-width-1-4 wk-grid-match" wk-grid>
                                    <?php if( is_array($result['templates']) ): ?>
                                        <?php foreach( $result['templates'] as $singletemplate ) : ?>
                                            <div class="wk-first-column">
                                                <div class="wk-card wk-card-default">
                                                    <a href="<?php echo esc_url( admin_url('admin.php?page=widgetkit-template-library&package='.esc_attr($singletemplate['package_type']).'&action=single-template&id='.esc_attr($singletemplate['id'])) ); ?>">
                                                        <div class="wk-card-badge wk-label" style="background:#f0506e;padding:2px 6px;color:white;border-radius:4px;"><?php echo esc_html($singletemplate['package_type']); ?></div>
                                                        <div class="wk-card-media-top wk-background-default">
                                                            <img src="<?php echo esc_url( $singletemplate['thumbnail'] ); ?>" alt="">
                                                            <div class="widget-template-image-hover">
                                                                <span class="dashicons dashicons-arrow-right-alt"></span>
                                                            </div>
                                                        </div>
                                                        <div class="wk-card-body wk-flex wk-background-default">
                                                            <span class="widgetkit-library-template-name"><?php echo esc_html($singletemplate['title']); ?></span>
                                                        </div>
                                                    </a>
                                                </div>  
                                            </div>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php else: ?>
            <?php 
                $response = wp_remote_get($this->api .'templates/'.esc_attr($tid).'/'.esc_attr($tid).'.json');
                $responseBody = wp_remote_retrieve_body( $response );
                $result = json_decode($responseBody,true);
            ?>
            <div class="wrap widgetkit-template-libray-single">
                <div class="wk-container">
                    <div class="wk-header wk-padding-small wk-card wk-card-default wk-margin-medium-top">
                        <div class="wk-header__top wk-margin-small-bottom">
                            <div class="wk-text-center wk-padding-small">
                                <img src="<?php echo WKP_URL . 'dist/images/logo-t.svg'; ?>" width="200" wk-svg>
                            </div>
                        </div>
                        <div class="wk-header__bottom wk-margin-small-top">
                            <a class="wk-flex" href="<?php echo esc_url( admin_url( 'admin.php?page=widgetkit-template-library' ) ); ?>"> <span class="wk-icon wk-margin-small-right" wk-icon="chevron-left"></span> Back to Library</a>
                        </div>
                    </div>
                    <div class="wk-main wk-margin wk-padding-small widgetkit-single-template-wrapper">
                        <div class="wk-grid">
                            <div class="wk-width-1-1">
                                <div class="wk-card-small">
                                    <div class="wk-grid">
                                        <div class="wk-width-2-3">
                                            <div class="wk-card widgetkit-single-template-image">
                                                <div class="wk-card-badge wk-label"><?php echo esc_html($package_type); ?></div>
                                                <img src="<?php echo esc_url( $result['preview_image'] ); ?>" alt="">
                                            </div>
                                        </div>
                                        <div class="wk-width-1-3">
                                            <div class="wk-card wk-card-default wk-card-body wk-margin">
                                                <h3 class="wk-card-title"><?php echo esc_html__('Import Template','widgetkit-for-elmentor'); ?></h3>
                                                <p><?php echo esc_html__('Import this template to make it available in your Elementor Saved Templates list for future use.','widgetkit-for-elmentor'); ?></p>
                                                <a data-td="<?php echo esc_attr($tid); ?>" class="button button-primary ele-template-importer" href="#"><?php echo esc_html__('Import Template','widgetkit-for-elmentor'); ?><span class="dashicons dashicons-image-rotate"></span></a>
                                            </div>
                                            <div class="wk-card wk-card-default wk-card-body">
                                                <h3 class="wk-card-title"><?php echo esc_html__('Create Page from Template','widgetkit-for-elmentor'); ?></h3>
                                                <p><?php echo esc_html__('Create a new page from this template to make it available as a page in your Pages list.','widgetkit-for-elmentor'); ?></p>
                                                <form class="page-import-form" data-td="<?php echo esc_attr($tid); ?>">
                                                    <div class="wk-inline">
                                                        <input required name="single-template-page-name" placeholder="<?php echo esc_attr__('Enter Page Name','widgetkit-for-elmentor'); ?>" class="regular-text" type="text">
                                                        <button class="button button-primary" type="submit"><?php echo esc_html__('Create Page','widgetkit-for-elmentor'); ?><span class="dashicons dashicons-image-rotate"></span></button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    <?php
    }

    /**
    *  Page save from remote 
    */
    public function widgetkit_save_import_remote_template_page() {
        $pagename = $_POST['pagename'];
        $tid = $_POST['tid'];
        $postdata = array(
            'post_title' => $pagename,
            'post_status'   => 'publish',
            'post_type' => 'page'
        );

        $response = wp_remote_get($this->api .'templates/'.esc_attr($tid).'/'.esc_attr($tid).'.json');
        $responseBody = wp_remote_retrieve_body( $response );
        $result = json_decode($responseBody,true);

        $postid = wp_insert_post($postdata);
        update_post_meta( $postid, '_wp_page_template', 'elementor_header_footer' );
        update_post_meta( $postid, '_elementor_data', $result['content'] );
        update_post_meta( $postid, '_elementor_edit_mode', 'builder' );

        $data =  array(
            'postid' =>  $postid,
            'permalink' => get_permalink($postid)
        );

        wp_send_json_success( $data );
        die();
    }


    /**
    *  Elementor template save
    */
    public function widgetkit_save_import_elementor_template() {
        $tid = $_POST['tid'];
        
        $response = wp_remote_get($this->api .'templates/'.esc_attr($tid).'/'.esc_attr($tid).'.json');
        $responseBody = wp_remote_retrieve_body( $response );
        $result = json_decode($responseBody,true);
        $title = $result['title'];
        $postdata = array(
            'post_title' => $title,
            'post_status'   => 'publish',
            'post_type' => 'elementor_library'
        );

        $postid = wp_insert_post($postdata);
        update_post_meta( $postid, '_wp_page_template', 'elementor_header_footer' );
        update_post_meta( $postid, '_elementor_data', $result['content'] );
        update_post_meta( $postid, '_elementor_edit_mode', 'builder' );

        $data =  array(
            'postid' =>  $postid,
            'permalink' => get_permalink($postid)
        );

        wp_send_json_success( $data );
        die();
    }
}

new Widgetkit_Pro_Library;