<?php

add_action('widgets_init', 'wplms_dash_course_progress');

function wplms_dash_course_progress()
{
    register_widget('wplms_course_progress');
}

class wplms_course_progress extends WP_Widget
{
    /** constructor -- name this the same as the class above */
    function __construct()
    {
        $widget_ops = array(
            'classname' => 'wplms_course_progress',
            'description' => __(
                'Student Progress in Courses',
                'wplms'
            )
        );
        $control_ops = array(
            'width' => 300,
            'height' => 350,
            'id_base' => 'wplms_course_progress'
        );
        parent::__construct(
            'wplms_course_progress',
            __(' DASHBOARD : Course Progress', 'wplms'),
            $widget_ops,
            $control_ops
        );

        //Start recording Course Progress
        add_action(
            'wplms_student_course_reset',
            array($this, 'wplms_student_course_reset'),
            10,
            2
        );
        add_action(
            'wplms_student_course_remove',
            array($this, 'wplms_student_course_remove'),
            10,
            2
        );
        add_action(
            'wp_ajax_reset_course_user',
            array($this, 'reset_course_user'),
            20
        ); // RESETS COURSE FOR USER


        add_action('wp_enqueue_scripts',array($this,'enqueue_script'));
        
    
        add_filter('vibebp_member_dashboard_widgets',array($this,'add_custom_script'));
    }
    
    function add_custom_script($args){
      $args[]='wplms_course_progress';
      return $args;
    }

    function enqueue_script(){
        if(bp_current_component() == 'dashboard' || apply_filters('vibebp_enqueue_profile_script',false)){
            wp_enqueue_script(
                'wplms_course_progress',
                WPLMS_PLUGIN_URL.'/assets/js/course-progress.js',
                array('wp-element'),
                WPLMS_PLUGIN_VERSION,
                true
            );
            wp_enqueue_style('wplms_dashboard_css',WPLMS_PLUGIN_URL.'/assets/css/dashboard.css',array(),WPLMS_PLUGIN_VERSION);
            wp_localize_script('wplms_course_progress', 'course_progress', array(
                'settings' => array(),
                'api' => rest_url(BP_COURSE_API_NAMESPACE . '/dashboard/widget'),
                'user_id' => get_current_user_id(),
                'translations' => array(
                    'no_courses' => __('No enrolled Courses!', 'wplms')
                )
            ));
        }
    }
    /** @see WP_Widget::widget -- do not rename this */
    function widget($args, $instance)
    {
        extract($args);
        $user_id = apply_filters(
            'wplms_dashboard_student_id',
            get_current_user_id()
        );

        //Our variables from the widget settings.
        global $wpdb, $bp;
        $title = apply_filters('widget_title', $instance['title']);
        $num = $instance['number'];
        $finished = $instance['finished'];

        $width = $instance['width'];
        echo '<div class="' .
            $width .
            '">
            <div class="dash-widget">' .
            $before_widget;

        // Display the widget title
        if ($title) {
            echo $before_title . $title . $after_title;
        }

        if(is_wplms_4_0()){
            echo '<div class="wplms_course_progress"></div>';
        }else if(bp_is_my_profile()){

            $query = apply_filters('wplms_usermeta_direct_query',$wpdb->prepare("
              SELECT posts.ID as id,meta.meta_value as status
              FROM {$wpdb->posts} AS posts
              LEFT JOIN {$wpdb->usermeta} AS meta ON CONCAT('course_status','',posts.ID) = meta.meta_key
              WHERE   posts.post_type   = %s
              AND   posts.post_status   = %s
              AND   meta.user_id   = %d
              LIMIT 0,{$num}
              ",'course','publish',$user_id));
            if(!isset($finished) || !$finished){
              $query = apply_filters('wplms_usermeta_direct_query',$wpdb->prepare("
              SELECT posts.ID as id,meta.meta_value as status
              FROM {$wpdb->posts} AS posts
              LEFT JOIN {$wpdb->usermeta} AS meta ON CONCAT('course_status','',posts.ID) = meta.meta_key
              WHERE   posts.post_type   = %s
              AND   posts.post_status   = %s
              AND   meta.user_id   = %d
              AND   meta.meta_value < %d
              LIMIT 0,{$num}
              ",'course','publish',$user_id,3));
              
            }

            $results = $wpdb->get_results($query);
            if(!empty($results) && !is_wp_error($results)){

                echo '<div class="course_progress">
                           <ul class="dash-courses-progress">';
                 $i=0;
                foreach($results as $key => $course){
                    $course_id = $course->id;
                    $percentage = bp_course_get_user_progress($user_id,$course_id);
                    $percentage = apply_filters('wplms_course_progress_display',  $percentage ,$course_id);
                    if(empty($percentage)){
                      $percentage = 0;
                    }
                            echo '<li>
                          <strong><a href="'.get_permalink($course_id).'">'.get_the_title($course_id).'</a><span>'.$percentage.'%</span></strong>
                                        <div class="progress course_progress" data-course="'.$course_id.'">
                           <div class="bar animate stretchRight" style="width: '.$percentage.'%; background-color:'.wplms_get_random_color($i).'"></div>
                         </div>';
                        do_action('wplms_dashboard_course_progress_student_list',$user_id,$course_id,$percentage);
                            echo '</li>';
                      $i++;
                            }             
                echo '</ul>
                </div>';
            }
        }else{
          echo '<div class="wplms_course_progress"></div>';
        }
        
        echo $after_widget . '</div></div>';
    }

    /** @see WP_Widget::update -- do not rename this */
    function update($new_instance, $old_instance)
    {
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        $instance['number'] = $new_instance['number'];
        $instance['finished'] = $new_instance['finished'];
        $instance['width'] = $new_instance['width'];
        return $instance;
    }

    /** @see WP_Widget::form -- do not rename this */
    function form($instance)
    {
        $defaults = array(
            'title' => __('Course Progress', 'wplms'),
            'number' => 5,
            'finished' => 1,
            'width' => 'col-md-6 col-sm-12'
        );
        $instance = wp_parse_args((array) $instance, $defaults);
        $title = esc_attr($instance['title']);
        $finished = esc_attr($instance['finished']);
        $number = esc_attr($instance['number']);
        $width = esc_attr($instance['width']);
        ?>
        <p>
          <label for="<?php echo $this->get_field_id(
              'title'
          ); ?>"><?php _e('Title:', 'wplms'); ?></label> 
          <input class="regular_text" id="<?php echo $this->get_field_id(
              'title'
          ); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id(
              'number'
          ); ?>"><?php _e('Number of activities in one screen', 'wplms'); ?></label> 
          <input class="regular_text" id="<?php echo $this->get_field_id(
              'number'
          ); ?>" name="<?php echo $this->get_field_name('number'); ?>" type="text" value="<?php echo $number; ?>" />
        </p>
        <p>
          <label for="<?php echo $this->get_field_id(
              'finished'
          ); ?>"><?php _e('Show Finished Courses', 'wplms'); ?></label> 
          <input class="checkbox" id="<?php echo $this->get_field_id(
              'finished'
          ); ?>" name="<?php echo $this->get_field_name('finished'); ?>" type="checkbox" value="1"  <?php checked($finished, 1, true); ?>/>
        </p>
        <p>
          <label for="<?php echo $this->get_field_id(
              'width'
          ); ?>"><?php _e('Select Width', 'wplms'); ?></label> 
          <select id="<?php echo $this->get_field_id(
              'width'
          ); ?>" name="<?php echo $this->get_field_name('width'); ?>">
          	<option value="col-md-3 col-sm-6" <?php selected(
               'col-md-3 col-sm-6',
               $width
           ); ?>><?php _e('One Fourth', 'wplms'); ?></option>
          	<option value="col-md-4 col-sm-6" <?php selected(
               'col-md-4 col-sm-6',
               $width
           ); ?>><?php _e('One Third', 'wplms'); ?></option>
          	<option value="col-md-6 col-sm-12" <?php selected(
               'col-md-6 col-sm-12',
               $width
           ); ?>><?php _e('One Half', 'wplms'); ?></option>
            <option value="col-md-8 col-sm-12" <?php selected(
                'col-md-8 col-sm-12',
                $width
            ); ?>><?php _e('Two Third', 'wplms'); ?></option>
             <option value="col-md-8 col-sm-12" <?php selected(
                 'col-md-9 col-sm-12',
                 $width
             ); ?>><?php _e('Three Fourth', 'wplms'); ?></option>
          	<option value="col-md-12" <?php selected(
               'col-md-12',
               $width
           ); ?>><?php _e('Full', 'wplms'); ?></option>
          </select>
        </p>
        <?php
    }

    function wplms_student_course_reset($course_id, $user_id)
    {
        $progress = 'progress' . $course_id;
        update_user_meta($user_id, $progress, 0);
    }
    function wplms_student_course_remove($course_id, $user_id)
    {
        $progress = 'progress' . $course_id;
        delete_user_meta($user_id, $progress);
    }

    function calculate_course_progress($course_id)
    {
        $user_id = get_current_user_id();
        $progress = 'progress' . $course_id;
        $curriculum = bp_course_get_curriculum_units($course_id);
        $base = count($curriculum);
        foreach ($curriculum as $key => $unit) {
            $check = get_user_meta($user_id, $unit, true);
            if (!isset($check) || !$check) {
                break;
            }
        }
        if (!$base) {
            $base = 1;
        }
        $course_progress = round(100 * ($key / $base), 0);
        update_user_meta($user_id, $progress, $course_progress);
        return $course_progress;
    }
    function reset_course_user()
    {
        $course_id = $_POST['id'];
        $user_id = $_POST['user'];

        if (
            !isset($_POST['security']) ||
            !wp_verify_nonce($_POST['security'], 'vibe_security')
        ) {
            echo '<p>' .
                __('Security check failed !', 'wplms') .
                '</p>';
            die();
        }

        if (!isset($user_id) || !is_numeric($user_id) || !$user_id) {
            echo '<p>' .
                __(' Incorrect User selected.', 'wplms') .
                '</p>';
            die();
        }
        $progress = 'progress' . $course_id;
        update_user_meta($user_id, $progress, 0);
        die();
    }
}

?>
