<?php
namespace factory;

class Statistics
{
  public static function phrases_diffs()
  {
    global $mdb, $user;

    if ( $user['type'] != 'admin' )
      return false;

    if ( !$out = \FileCache::fetch( "phrases-diffs" ) )
    {
      $results = $mdb -> query( 'SELECT '
                                      . 'prp.id, phrase, name, '
                                      . '( SELECT position FROM phrase_positions_statistic WHERE phrase_id = prp.id ORDER BY date DESC LIMIT 1 ) AS today, '
                                      . '( SELECT position FROM phrase_positions_statistic WHERE phrase_id = prp.id ORDER BY date DESC LIMIT 1 OFFSET 1 ) AS yesterday '
                                    . 'FROM '
                                      . 'pro_rr_phrases AS prp '
                                      . 'INNER JOIN pro_rr_sites AS prs ON prp.site_id = prs.id '
                                    . 'WHERE '
                                      . '( prp.date_end >= \'' . date( 'Y-m-d' ) . '\' OR prp.date_end IS NULL ) '
                                    . 'AND '
                                      . '( prs.date_start <= \'' . date( 'Y-m-d' ) . '\' OR prs.date_start IS NULL ) '
                                    . 'AND '
                                      . '( prp.date_start <= \'' . date( 'Y-m-d' ) . '\' OR prp.date_start IS NULL ) '
                                    . 'AND '
                                      . '( prs.date_end >= \'' . date( 'Y-m-d' ) . '\' OR prs.date_end IS NULL ) '
                                    . 'ORDER BY '
                                      . 'prp.id ASC' ) -> fetchAll();

      if ( is_array( $results ) and !empty( $results ) ) foreach ( $results as $row )
      {
        $diff = 0;

        if ( $row['today'] == 0 and $row['yesterday'] != 0 )
          $diff = $row['yesterday'] - 200;

        else if ( $row['today'] != 0 and $row['yesterday'] == 0 )
          $diff = 200 - $row['today'];

        else
          $diff = $row['yesterday'] - $row['today'];

        $out[ $row['id'] ]['domain'] = $row['name'];
        $out[ $row['id'] ]['phrase'] = $row['phrase'];
        $out[ $row['id'] ]['diff']   = $diff;
        $out[ $row['id'] ]['today']  = $row['today'];
      }
      \FileCache::store( "phrases-diffs", $out, 'n' );
    }
    return $out;
  }
}
?>
