<?php
/**
 * Class model page statistic
 *
 * @package wp-viral-click
 * @author InstaProduct
 * @link http://insta-product.com/
 */

if ( ! class_exists( 'IPJck_Model_PageStat' )) {

  /**
   * Class model page statatistic
   */
  class IPJck_Model_PageStat
  {
		/**
		 * Get All Stats
		 *
		 * @return array
		 */
		public function getAllStats()
		{
			global $wpdb;

			$table  = $wpdb->prefix . 'ipjck_page_stats';
			$query  = "
					SELECT
						SUM( `stat_view` ) as `views`,
						SUM( `stat_click` ) as `clicks`
					FROM $table
			";
			$results = $wpdb->get_row( $query );
			return $results;
		}

		/**
		 * Get Stats
		 *
		 * @return int   $pageId
		 * @return array
		 */
		public function getStats( $pageId )
		{
			global $wpdb;

			$pageId = absint( $pageId );
			$table  = $wpdb->prefix . 'ipjck_page_stats';
			$query  = "
					SELECT * FROM $table
					WHERE
							page_id = $pageId
			";
			$results = $wpdb->get_row( $query );
			return $results;
		}

		/**
     * Get stat by page date
     *
     * @param  int $pageId
     * @return array
     */
    public function getStatByPage( $pageId )
    {
      global $wpdb;

      $pageId = absint( $pageId );
      $table  = $wpdb->prefix . 'ipjck_page_stats';
      $sql    = "
          SELECT *
          FROM `$table`
          WHERE page_id = $pageId
      ";
      $results = $wpdb->get_row( $sql );
      return $results;
    }

		/**
     * Do save statistic
     *
     * @param object $page
     * @param string $type
     * @param int    $count
     * @return void
     */
    public function saveStat( $page, $type, $count = 1 )
    {
      $_types = array(
        'view',
        'click'
      );
      $key = 'stat_';
      if ( in_array( $type, $_types )) {
        $key .= $type;
      }
      $data = array();
      if ( $stat = $this->getStatByPage( $page->ID ))
      {
        $ccount = 0;
        if ( isset( $stat->$key )) {
          $ccount = $stat->$key;
        }
        $data[$key] = $ccount + $count;
        $this->updateStat( $stat->stat_id, $data );
      }
      else {
        $data['page_id']   = $page->ID;
        $data['stat_date'] = date( 'Y-m-d 00:00:00' );
        $data[$key]        = $count;
        $this->insertStat( $data );
      }
    }

    /**
     * Get statistic data
     *
     * @return array
     */
    public function getStatisticData( $pageId, $type, $start = null, $end = null )
    {
      global $wpdb;

      $pageId = absint( $pageId );
      $table    = $wpdb->prefix . 'ipjck_page_stats';
      $query    = "
          SELECT
            DATE_FORMAT(stat_date, '%Y-%m-%d') AS gdate,";
			      //Type value
			      if ( $type == 'view' ) {
			        $query .= 'SUM(stat_view) AS value';
			      } elseif ( $type == 'click' ) {
			        $query .= 'SUM(stat_click) AS value';
			      } elseif ( $type == 'rate' ) {
			        $query .= 'SUM(stat_click) AS clicks,';
			        $query .= 'SUM(stat_view) AS views';
			      }
			      $query .= " FROM $table
			                  WHERE page_id = $pageId";

      if ( ! empty( $start ) && ! empty( $end ))
      {
        if ( $start == $end ) {
          $query .= " AND DATE_FORMAT( stat_date, '%Y-%m-%d' ) = '$start'";
        } else {
          $query .= " AND stat_date BETWEEN '$start' AND '$end'";
        }
      }
      elseif ( ! empty( $start )) {
        $query .= " AND DATE_FORMAT( stat_date, '%Y-%m-%d' ) = '$start'";
      }
      elseif ( ! empty( $end )) {
        $query .= " AND DATE_FORMAT( stat_date, '%Y-%m-%d' ) = '$end'";
      }
      $query .= " GROUP BY gdate";
      $results = $wpdb->get_results( $query );
      return $results;
    }

		/**
		 * Insert Stat
		 *
		 * @param  array $data
		 * @param  array $format
		 * @return void
		 */
		public function insertStat( $data, $format = array() )
		{
				global $wpdb;
				$table  = $wpdb->prefix . 'ipjck_page_stats';
				$data   = (array)$data;

				$result = $wpdb->insert( $table, $data, $format );
				if ( $result ) {
						return $wpdb->insert_id;
				}
				return false;
		}

		/**
		 * Update Stat
		 *
		 * @param  int   $id
		 * @param  array $data
		 * @return void
		 */
		public function updateStat( $id, $data )
		{
				global $wpdb;
				$table  = $wpdb->prefix . 'ipjck_page_stats';
				$data   = (array)$data;
				$where  = array(
						'stat_id' => absint( $id )
				);
				$result = $wpdb->update( $table, $data, $where );
				return $result;
		}

		/**
		 * Delete Stat
		 *
		 * @param  int   $id
		 * @return void
		 */
		public function deleteStat( $id )
		{
			global $wpdb;
			$table  = $wpdb->prefix . 'ipjck_page_stats';
			$where  = array(
					'stat_id' => absint( $id )
			);
			$result = $wpdb->delete( $table, $where );
			return $result;
		}
	}
}
