<?php


class daily_readings_widget extends WP_Widget {
    // Create Multiple WordPress Widgets
    function __construct() {
        parent::__construct('daily_readings', __('Daily Readings', 'daily-readings'), array(
            'description' => __('Daily Readings Widget for sidebar', 'daily-readings')
        ));
        add_action( 'plugins_loaded', array( $this, 'daily_readings_loadTranslations' ) );
    }
    
    // This function creates Daily Readings
    public function widget($args, $instance) {
       
        $daily_readings_options = get_option( 'daily_readings_option_name' );
        $rite_0 = $daily_readings_options['rite_0']; 
        $color_1 = $daily_readings_options['color_1'];
        $direction = ($rite_0 == 'AR' || $rite_0 == 'BYA' || $rite_0 == 'CHA' || $rite_0 == 'COA' || $rite_0 == 'MAA' || $rite_0 == 'SYA') ? 'rtl' : 'ltr' ; 

        $title = apply_filters('title', $instance['title']);
        $hide_first_reading_2  = $instance['hide_first_reading_2'] ? true : false;
        $hide_psalm_3  = $instance['hide_psalm_3'] ? true : false;
        $hide_second_reading_4  = $instance['hide_second_reading_4'] ? true : false;
        $hide_gospel_5  = $instance['hide_gospel_5'] ? true : false;
        $read_more_limit = apply_filters('read_more_limit', $instance['read_more_limit']);
        $image = apply_filters('image', $instance['image']);
        $linkPage = get_post( $instance['wpage'] );

        $time_zone_7 = $daily_readings_options['time_zone_7'];
        $currentDate = current_time( 'Ymd' );
       

       $responseLiturgy = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date='. $currentDate .'&lang='. $rite_0 .'&type=liturgic_t');

        $responseTitleEpistle = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading_lt&content=EP');

        $responseTitleFirstReading = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading_lt&content=FR');
        $responseTitlePsalm = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading_lt&content=PS');
        $responseTitleSecondReading = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading_lt&content=SR');
        $responseTitleGospel = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading_lt&content=GSP'); 


        $Content = '<style>';
        $Content .= '.widget_daily_readings h4.daily-readings-reading-heading {';
        $Content .= 'color: ' . $color_1 . ';}';
        $Content .= '</style>';

        $Content .= '<div id="direction-wrapper" dir="' . $direction . '" >';  

        $Content .= '<p class="daily-readings-date">' . $responseLiturgy . '</p>';

        $Content .= '<div id="epistleReading" class="reading-wrapper">';

        if ((!$hide_first_reading_2 || !$hide_second_reading_4) && $responseTitleEpistle ) {

            $responseEpistle = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading&content=EP');

            $Content .= daily_readings_renderReadingWidget($responseTitleEpistle, $read_more_limit, $responseEpistle, 'epistle', true);
        }
        $Content .= '</div>';

        $Content .= '<div id="firstReading" class="reading-wrapper">';

        if (!$hide_first_reading_2 && $responseTitleFirstReading ) {

            $responseFirstReading = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading&content=FR');

            $Content .= daily_readings_renderReadingWidget($responseTitleFirstReading, $read_more_limit, $responseFirstReading, 'first', true);
        }
        $Content .= '</div>';


        $Content .= '<div id="psalmReading" class="reading-wrapper">';

        if (!$hide_psalm_3 && $responseTitlePsalm) {

            $responsePsalm = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading&content=PS');

            $Content .= daily_readings_renderReadingWidget($responseTitlePsalm, $read_more_limit, $responsePsalm, 'psalm', true);
        }
        $Content .= '</div>';


        $Content .= '<div id="secondReading" class="reading-wrapper">';

        if (!$hide_second_reading_4 && $responseTitleSecondReading) {

            $responseSecondReading = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading&content=SR');

            $Content .= daily_readings_renderReadingWidget($responseTitleSecondReading, $read_more_limit, $responseSecondReading, 'second', true);
        }
        $Content .= '</div>';


        $Content .= '<div id="gospelReading" class="reading-wrapper">';

        if (!$hide_gospel_5 && $responseTitleGospel) {

            $responseGospel = fetch_reading_widget('https://feed.evangelizo.org/v2/reader.php?date=' . $currentDate . '&lang=' . $rite_0 . '&type=reading&content=GSP');

            $Content .= daily_readings_renderReadingWidget($responseTitleGospel, $read_more_limit, $responseGospel, 'gospel', false);
        }
        $Content .= '</div>'; 

        $Content .= '</div>'; //direction-wrapper

        if ($linkPage) {
            $Content .= '<p id="see-all-readings"><a href="' . get_permalink( $linkPage ) . '">' . __( 'Go to Daily Readings', 'daily-readings' ) . '</a></p>'; 
        }
        

        echo $args['before_widget'];
        
        if ($title){
            echo $args['before_title'] . $title . $args['after_title'];
        }

        if ($image){
            echo '<a href="' . get_permalink( $linkPage ) . '" ><img src="' . esc_url($image) . '" alt="daily-readings"></a>';
        }

        echo $Content;
        echo $args['after_widget'];
    }
    
    // Create Instance and Assign Values
    public function form($instance) {

        $title = $instance[ 'title' ];
        $image = $instance['image'];
        $preview_image = $instance['preview_image'];
        
        $instance['hide_first_reading_2']  = $instance['hide_first_reading_2'] ? 'true' : 'false';
        $instance['hide_psalm_3']  = $instance['hide_psalm_3'] ? 'true' : 'false';
        $instance['hide_second_reading_4']  = $instance['hide_second_reading_4'] ? 'true' : 'false'; 
        $instance['hide_gospel_5']  = $instance['hide_gospel_5'] ? 'true' : 'false';  

        $read_more_limit = $instance['read_more_limit'];   

        $instance = wp_parse_args( (array) $instance, $default );
        $args = array(
          'name' => $this->get_field_name('wpage'),
          'show_option_none' => 'None',
          'option_none_value' => '-1',
          'selected' => $instance['wpage']
        );
?>
 
<!--  This is Daily Readings Widget Form -->
<p>
    <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title');?></label>
    <input class="widefat" id="<?php echo $this->get_field_id('title');?>" name="<?php echo $this->get_field_name('title');?>" type="text" value="<?php echo esc_attr($title);?>" />
</p>

<div class="daily-readings-image-wrapper">
    <div class="daily-readings-input-wrapper">
        <label for="<?php echo $this->get_field_id( 'image' ); ?>"><?php _e( 'Image' ); ?></label>
        <input class="widefat" id="<?php echo $this->get_field_id( 'image' ); ?>" name="<?php echo $this->get_field_name( 'image' ); ?>" type="text" value="<?php echo esc_url( $image ); ?>" />
    </div>
    <div class="daily-readings-preview-image-wrapper">
        <img id="<?php echo $this->get_field_id( 'preview_image' ); ?>" class="daily-readings-preview-image" src="<?php echo esc_url( $image ); ?>" />
    </div>
    <div>
        <button class="daily-readings-upload_image_button button"><?php _e( 'Select image' ); ?></button>
        <button class="daily-readings-remove_image_button button"><?php _e( 'Cancel image' ); ?></button>
    </div>
</div>

    <h4><?php _e('Readings to hide', 'daily-readings' ); ?></h4>
    <div class="daily-readings-readings-to-hide"><input type="checkbox" class="checkbox" name="<?php echo $this->get_field_name('hide_first_reading_2'); ?>" id="<?php echo $this->get_field_id('hide_first_reading_2'); ?>" <?php checked($instance['hide_first_reading_2'], 'true'); ?>><label for="hide_first_reading_2"><?php _e('First', 'daily-readings' ); ?></label></div>

    <div class="daily-readings-readings-to-hide"><input type="checkbox" class="checkbox" name="<?php echo $this->get_field_name('hide_psalm_3'); ?>" id="<?php echo $this->get_field_id('hide_psalm_3'); ?>" <?php checked($instance['hide_psalm_3'], 'true'); ?>><label for="hide_psalm_3"><?php _e('Psalm', 'daily-readings' ); ?></label></div>

    <div class="daily-readings-readings-to-hide"><input type="checkbox" class="checkbox" name="<?php echo $this->get_field_name('hide_second_reading_4'); ?>" id="<?php echo $this->get_field_id('hide_second_reading_4'); ?>" <?php checked($instance['hide_second_reading_4'], 'true'); ?>><label for="hide_second_reading_4"><?php _e('Second', 'daily-readings' ); ?></label></div>

    <div class="daily-readings-readings-to-hide"><input type="checkbox" class="checkbox" name="<?php echo $this->get_field_name('hide_gospel_5'); ?>" id="<?php echo $this->get_field_id('hide_gospel_5'); ?>" <?php checked($instance['hide_gospel_5'], 'true'); ?>><label for="hide_gospel_5"><?php _e('Gospel', 'daily-readings' ); ?></label></div>
    <p><i><?php _e( 'Tick the checkbox if you don\'t want to render a daily reading', 'daily-readings' ); ?></i></p>

<p>
    <label for="<?php echo $this->get_field_id('read_more_limit'); ?>"><?php _e('Read More Limit', 'daily-readings' );?></label>
    <input class="widefat" id="<?php echo $this->get_field_id('read_more_limit');?>" name="<?php echo $this->get_field_name('read_more_limit');?>" type="number" value="<?php echo esc_attr($read_more_limit);?>" />
    <p><i><?php _e( 'Number of characters to show before the interruption.<br>Whole reading will be displayed if empty', 'daily-readings' ); ?></i></p>
</p>
<p>
    <label><?php _e('Daily Readings Page', 'daily-readings' );?></label>
    <?php wp_dropdown_pages( $args );?>
    <p><i><?php _e( 'Select the page with complete daily readings', 'daily-readings' ); ?></i></p>
</p>

<?php
    }
    
    // Updating widget replacing old instances with new
    function update($new_instance, $old_instance){
        $instance = array();

        $instance['title'] = (!empty($new_instance['title'])) ? strip_tags($new_instance['title']) : '';
        $instance['image'] = (!empty($new_instance['image'])) ? strip_tags($new_instance['image']) : '';
        $instance['preview_image'] = (!empty($new_instance['preview_image'])) ? strip_tags($new_instance['preview_image']) : '';
    
        $instance['hide_first_reading_2']  = $new_instance['hide_first_reading_2'];
        $instance['hide_psalm_3']  = $new_instance['hide_psalm_3'];
        $instance['hide_second_reading_4']  = $new_instance['hide_second_reading_4'];
        $instance['hide_gospel_5']  = $new_instance['hide_gospel_5'];
        $instance['read_more_limit'] = (!empty($new_instance['read_more_limit'])) ? strip_tags($new_instance['read_more_limit']) : '';

        if ( isset( $new_instance['wpage'] ) && (int) $new_instance['wpage'] > 0 ) {
            $instance['wpage'] = $new_instance['wpage'];
        }
        return $instance;
    }
}


function daily_readings_renderReadingWidget($lecture, $read_more_limit, $verses, $context, $removeCopyright) {
    if($verses){

        $verses = remove_copyright_widget($verses, $removeCopyright);

        $Content = '<h4 class="daily-readings-reading-heading">' . $lecture . '</h4>';
        if ($read_more_limit){
            
            $pattern = "/\\w\\s\\w/i";
            preg_match($pattern, $verses, $matches, PREG_OFFSET_CAPTURE, intval($read_more_limit));

            $subLecture = substr_replace($verses, '<span class="daily-readings-dots">... </span><span class="daily-readings-read-more">', $matches[0][1]+1, 0);
            
            $Content .= '<div class="daily-readings-reading ' . $context . '">' .  $subLecture . '</span><p class="daily-readings-read-more-button"><a onclick="readToggle(\'' . $context . '\')" id="' . $context . '-read-more-daily-readings"><i title="' . __( 'Open/Close', 'daily-readings' ) . '" class="fa fa-chevron-down" aria-hidden="true"></i></a></p></div>';
        } else {
            $Content .= '<div class="daily-readings-reading">' . $verses . '</div>';
        }
        return $Content;
    }
}

function fetch_reading_widget($url) {
    $response = wp_remote_get($url);
    $response = wp_remote_retrieve_body($response);

    if (str_contains($response, 'Error : wrong')) {
        return null;
    }

    return $response;
}

    function remove_copyright_widget($verses, $remove) {
        if(!$remove){
            return $verses;
        }

        for ($i = 0; $i < 2; $i++) {
            $verses = substr($verses, 0, strrpos($verses, '<br />'));
        }

        return $verses;
    }
    

function daily_readings_loadTranslations() {
    load_plugin_textdomain( 'daily-readings', false, 'daily-readings/languages' );
}
 
function daily_readings_plugin() {
    global $pagenow;

    wp_enqueue_style( 'daily-readings-css', plugins_url('../style.css', __FILE__ ));

    wp_enqueue_style( 'dr-datepicker-css', 'https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css');
    wp_enqueue_script( 'dr-datepicker-js', 'https://code.jquery.com/ui/1.12.1/jquery-ui.min.js', array( 'jquery' ));
    
    wp_enqueue_script( 'daily-readings-js', plugins_url('../daily-readings-frontend.js', __FILE__ ));
    
    if( $pagenow === 'widgets.php' ) {
        wp_enqueue_script( 'daily-readings-js-widget', plugins_url('../daily-readings-backend-widget.js', __FILE__ ));
    }

    register_widget('daily_readings_widget');
}
 
// Initialize Plugin
add_action('widgets_init', 'daily_readings_plugin');

?>