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

if ( ! class_exists( 'IPJck_Ajax_Getchart' ))
{
  class IPJck_Ajax_Getchart
  {
    /**
     * Execution save options process
     *
     * @return void
     */
    public function exec()
    {
      $data = array_merge( $_POST, $_GET );
      if ( ! empty( $data['pageid'] ) && ! empty( $data['type'] ))
      {
        $widgetId  = absint( $data['pageid'] );
        $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 IPJck_Model_WidgetStat();
        $chart     = array();
        $results   = $model->getStatisticData( $widgetId, $type, $dateStart, $dateEnd );

        if ( ! empty( $results )) {
          foreach( $results as $data ) {
            $timestamp = strtotime( $data->gdate );
            $phpdate   = getdate($timestamp);

            if ( $type == 'rate' ) 
            {
              $clicks = (int)$data->clicks;
              $views  = (int)$data->views;
              if ( ! empty( $views ) && ! empty( $clicks )) {
                $rate  = $clicks/$views;
                $value = number_format( $rate, 2, '.', '' );
              }
            } 
            else {
              $value = (int)$data->value;
            }
            $chart[] = array(
              'value'    => $value,
              'year'     => $phpdate['year'],
              'mon'      => $phpdate['mon'] - 1,
              'day'      => $phpdate['mday'],
            );
          }
        }
        if ( $type == 'click' ) {
          $label = __( 'Clicks', IPJCK_SLUG );
        } elseif ( $type == 'view' ) {
          $label = __( 'Views', IPJCK_SLUG );
        } elseif ( $type == 'subscribe' ) {
          $label = __( 'Subscribes', IPJCK_SLUG );
        } elseif ( $type == 'rate' ) {
          $label = __( 'Conversion Rate', IPJCK_SLUG );
        } else {
          $label = __( 'Data', IPJCK_SLUG );
        }
        echo json_encode( array(
          'status'            => 1,
          'labelDate'         => __( 'Date', IPJCK_SLUG ),
          'labelValue'        => $label,
          'data'              => $chart
        ) );
      }
      else
      {
        echo json_encode( array(
          'status' => 0
        ) );
      }
      die();
    }
  }
}
