<?php

class Cron
{
  public static function recursive_tasks()
  {
    global $mdb;

    $results = $mdb -> query( 'SELECT '
          . 't.*, ( SELECT COUNT(0) FROM tasks WHERE parent_id = t.id ) AS quantity '
        . 'FROM '
          . 'tasks AS t '
        . 'WHERE '
          . 'recursively = 1 AND deleted = 0 AND ( status = 1 OR status = 2 ) AND date_end IS NOT NULL AND date_end < \'' . date( 'Y-m-d', strtotime( '+366 days', time() ) ) . '\' '
        . 'HAVING quantity = 0 ORDER BY date_end ASC' ) -> fetchAll( \PDO::FETCH_ASSOC );
    if ( is_array( $results ) and count( $results ) )
    {
      foreach ( $results as $row )
      {
        if ( $row['date_end_month_day'] == null )
        {
          $mdb -> update( 'tasks', ['date_end_month_day' => date( 'j', strtotime( $row['date_end'] ) )], ['id' => $row['id']] );
          $row['date_end_month_day'] = date( 'j', strtotime( $row['date_end'] ) );
        }

        if ( $row['date_start_month_day'] == null )
        {
          $mdb -> update( 'tasks', ['date_start_month_day' => date( 'j', strtotime( $row['date_start'] ) )], ['id' => $row['id']] );
          $row['date_start_month_day'] = date( 'j', strtotime( $row['date_start'] ) );
        }

        /* powtarzanie co x dni */
        if ( $row['period'] == 1 )
        {
          $new_date_end = date( 'Y-m-d', strtotime( '+' . $row['frequency'] . ' days', strtotime( $row['date_end'] ) ) );

          if ( $row['date_start'] )
            $new_date_start = date( 'Y-m-d', strtotime( '+' . $row['frequency'] . ' days', strtotime( $row['date_start'] ) ) );
        }

        /* powtarzanie do x miesięcy */
        if ( $row['period'] == 2 )
        {
          $new_date_end = date( 'Y-m', strtotime( '+' . $row['frequency'] . ' months', strtotime( date( 'Y-m', strtotime( $row['date_end'] ) ) ) ) );
          $max_days = date( 't', strtotime( $new_date_end ) );

          if ( $max_days <= $row['date_end_month_day'] )
            $new_date_end = date( 'Y-m-d', strtotime( $new_date_end . '-' . $max_days ) );
          else
            $new_date_end = date( 'Y-m-d', strtotime( $new_date_end . '-' . $row['date_end_month_day'] ) );

          if ( $row['date_start'] )
          {
            $new_date_start = date( 'Y-m', strtotime( '+' . $row['frequency'] . ' months', strtotime( date( 'Y-m', strtotime( $row['date_start'] ) ) ) ) );
            $max_days = date( 't', strtotime( $new_date_start ) );

            if ( $max_days <= $row['date_start_month_day'] )
              $new_date_start = date( 'Y-m-d', strtotime( $new_date_start . '-' . $max_days ) );
            else
              $new_date_start = date( 'Y-m-d', strtotime( $new_date_start . '-' . $row['date_start_month_day'] ) );
          }
        }

        /* powtarzanie co x lat */
        if ( $row['period'] == 3 )
        {
          $new_date_end = date( 'Y-m', strtotime( '+' . $row['frequency'] . ' years', strtotime( date( 'Y-m', strtotime( $row['date_end'] ) ) ) ) );
          $max_days = date( 't', strtotime( $new_date_end ) );

          if ( $max_days <= $row['date_end_month_day'] )
            $new_date_end = date( 'Y-m-d', strtotime( $new_date_end . '-' . $max_days ) );
          else
            $new_date_end = date( 'Y-m-d', strtotime( $new_date_end . '-' . $row['date_end_month_day'] ) );

          if ( $row['date_start'] )
          {
            $new_date_start = date( 'Y-m', strtotime( '+' . $row['frequency'] . ' years', strtotime( date( 'Y-m', strtotime( $row['date_start'] ) ) ) ) );
            $max_days = date( 't', strtotime( $new_date_start ) );

            if ( $max_days <= $row['date_start_month_day'] )
              $new_date_start = date( 'Y-m-d', strtotime( $new_date_start . '-' . $max_days ) );
            else
              $new_date_start = date( 'Y-m-d', strtotime( $new_date_start . '-' . $row['date_start_month_day'] ) );
          }
        }

        $days_reminder = explode( ',', $row['reminders_interval'] );
        $max_days_reminder = max( $days_reminder );

        if ( $row['status'] != 2 ) {
          $status = $row['status'];
        } else {
          $status = 0;
        }

        $task_users = $mdb -> select( 'task_user', 'user_id', ['task_id' => $row['id']] );

        $new_task_id = \factory\Tasks::task_save(
                          null, $row['id'], $row['created_by'], $row['name'], $row['text'], $new_date_start, $new_date_end, $row['project_id'], $row['client_id'], $row['pay_rate'], $row['reminders_interval'], $row['recursively'] ? 'on' : 'off', $row['frequency'], $row['period'], $task_users, $row['date_end_month_day'], $row['date_start_month_day'], null, $row['task_change_status'], true, $status
                        );

        if ( $new_task_id ) {
          $task_actions = $mdb -> select( 'task_action', [ 'name' ], [ 'task_id' => $row['id'] ] );
          if ( $task_actions ) foreach ( $task_actions as $task_action )
            $mdb -> insert( 'task_action', [
              'name' => $task_action['name'],
              'task_id' => $new_task_id
            ] );
        }

        return [
            'status' => 'ok',
            'msg'    => 'Dodawanie rekursywnych zadań: <b>' . $row['name'] . '</b> - <b>' . $new_date_end . "</b>"
        ];
      }
    }
    return false;
  }

  public static function tasks_emails()
  {
    global $mdb, $setttings;

    include_once 'libraries/phpmailer/class.phpmailer.php';
    include_once 'libraries/phpmailer/class.smtp.php';

    $results = $mdb -> query( 'SELECT '
        . 't.* '
        . 'FROM '
        . 'tasks AS t '
        . 'WHERE '
        . 'reminders_interval IS NOT NULL AND reminders_send = 0 AND status != 2 AND deleted = 0 AND date_end IS NOT NULL' ) -> fetchAll( \PDO::FETCH_ASSOC );
    if ( is_array( $results ) and!empty( $results ) ) foreach ( $results as $row )
    {
      $days_counter = explode( ',', $row['reminders_interval'] );
      rsort( $days_counter );

      if ( is_array( $days_counter ) ) foreach ( $days_counter as $dc )
      {
        if ( !$mdb -> count( 'tasks_reminders', [ 'AND' => [ 'task_id' => $row['id'], 'day_counter' => $dc ] ] ) )
        {
          $send = false;
          $date_tmp = date( 'Y-m-d', strtotime( '+' . $dc . 'days', strtotime( date( 'Y-m-d' ) ) ) );

          if ( $date_tmp >= $row['date_end'] )
          {
            if ( !$mdb -> count( 'tasks_reminders', ['AND' => ['task_id' => $row['id'], 'day_counter' => $dc]] ) )
            {
              $users = $mdb -> select( 'task_user', 'user_id', ['task_id' => $row['id']] );

              if ( is_array( $users ) and count( $users ) )
              {
                foreach ( $users as $user )
                {
                  $user_email = $mdb -> get( 'users', 'email', ['id' => $user] ); echo $user_mail;

                  date( 'Y-m-d', strtotime( $row['date_end'] ) ) == date( 'Y-m-d' ) ? $date = 'dzisiaj' : $date = date( 'Y-m-d', strtotime( $row['date_end'] ) );


                  $subject = 'crmPRO - ' . $row['name'] . ' (#' . $row['id'] . ')';
                  $text = '<p>Witaj.</p>' .
                    '<p>Otrzymałeś ten email z powodu ustawionego przypomnienia. Poniżej znajdziesz jego treść.</p>' .
                    '<p>---------------------------------------------------------------------------------------</p>' .
                    '<p><b>' . $row['name'] . '</b> (termin zadania: <b>' . $date . ')</b></p>' .
                    '<p><i>' . \factory\Crm::get_client_name( (int)$task['client_id'] ) . '</i></p>' .
                    '<p>' . htmlspecialchars_decode( $row['text'] ) . '</p>';

                  if ( \S::send_email( $user_email, $subject, $text ) );
                    $send = true;
                }

                if ( $send )
                {
                  $mdb -> insert( 'tasks_reminders', ['task_id' => $row['id'], 'day_counter' => $dc] );
                  return [
                      'status' => 'ok',
                      'msg'    => 'Wiadomość została wysłana na adres: ' . $user_email
                  ];
                }
              }
              else
              {
                $mdb -> insert( 'tasks_reminders', ['task_id' => $row['id'], 'day_counter' => $dc] );
                return [
                    'status' => 'ok',
                    'msg'    => 'Wiadomość nie wysłana z powodu braku odbiorców.'
                ];
              }
            }
          }
        }
      }

      if ( count( $days_counter ) == $mdb -> count( 'tasks_reminders', ['task_id' => $row['id']] ) )
        $mdb -> update( 'tasks', ['reminders_send' => 1], ['id' => $row['id']] );
    }
    return ['status' => 'empty'];
  }
}