<?php
/**
 * Controller to handling get chart
 *
 * @package wp-video-attention
 * @author InstaProduct
 * @link http://insta-product.com/
 */

if ( ! class_exists( 'IPVisc_Ajax_Getchart' ))
{
    class IPVisc_Ajax_Getchart
    {
        /**
         * Execution save options process
         *
         * @return void
         */
        public function exec()
        {
            $data = array_merge( $_POST, $_GET );
            if ( ! empty( $data['videoid'] ) && ! empty( $data['type'] ))
            {
                $videoid   = absint( $data['videoid'] );
                $type      = apply_filters( 'pre_term_name', $data['type'] );
                $dateStart = false;
                $dateEnd   = false;
                if ( ! empty( $data['start'] ) && ! empty( $data['end'] )) {
                    $timeEnd   = strtotime( $data['end'] );
                    $timeStart = strtotime( $data['start'] );
                    $dateStart = gmdate("Y-m-d", $timeStart);
                    $dateEnd   = gmdate("Y-m-d", $timeEnd);
                }
                $model     = new IPVisc_Model_Stat();
                $chart     = array();
                $results   = $model->getStatisticData( $videoid, $type, $dateStart, $dateEnd );

                if ( ! empty( $results )) {
                    foreach( $results as $data ) {
                        $timestamp = strtotime( $data->gdate );
                        $phpdate   = getdate($timestamp);
                        $value     = (int)$data->value;
                        $chart[] = array(
                            'value'    => $value,
                            'year'     => $phpdate['year'],
                            'mon'      => $phpdate['mon'] - 1,
                            'day'      => $phpdate['mday'],
                        );
                    }
                }
                if ( $type == 'click' ) {
                    $label = __( 'Clicks', IPVISC_SLUG );
                } elseif ( $type == 'view' ) {
                    $label = __( 'View', IPVISC_SLUG );
                } elseif ( $type == 'play' ) {
                    $label = __( 'Play', IPVISC_SLUG );
                } elseif ( $type == 'subscribe' ) {
                    $label = __( 'Subscribe', IPVISC_SLUG );
                } else {
                    $label = __( 'Data', IPVISC_SLUG );
                }
                echo json_encode( array(
                    'status'            => 1,
                    'labelDate'         => __( 'Date', IPVISC_SLUG ),
                    'labelValue'        => $label,
                    'data'              => $chart
                ) );
            } else {

                echo json_encode( array(
                    'status' => 0
                ) );
            }
            die();
        }
    }
}
