<?
namespace factory;

class Tasks
{
  public static $statuses = [ 0 => 'nowe', 3 => 'do rozliczenia', 5 => 'do zrobienia', 4 => 'zaplanowane', 1 => 'do sprawdzenia', 6 => 'faktury', 2 => 'zamknięte' ];
  public static $priorities = [ 0 => 'niski', 1 => 'normalny', 2 => 'wysoki', 3 => 'pilny' ];

  static public function task_change_dates( $task_id, $date_start, $date_end )
  {
    global $mdb;

    if ( !$task_id )
      return false;

    return $mdb -> update( 'tasks', [
      'date_start' => $date_start,
      'date_end' => $date_end
    ], [
      'id' => $task_id
    ] );
  }

  static public function parent_tasks( $user_id )
  {
    global $mdb;

    if ( $user_id != 1 )
      $sql = ' AND id IN (SELECT task_id FROM task_user WHERE user_id = ' . $user_id . ') ';
    else
      $sql = '';

    $result = $mdb -> query( 'SELECT name, id, project_id, client_id FROM tasks WHERE parent_id IS NULL AND status != 2 AND status != 3 AND status != 1 ' . $sql . ' ORDER BY date_start ASC, o ASC' ) -> fetchAll( \PDO::FETCH_ASSOC );
    foreach ( $result as $row )
    {
      $task['id'] = $row['id'];
      $task['name'] = htmlspecialchars( $row['name'] );
      $task['project_id'] = $row['project_id'];
      $task['client'] = $row['client_id'] ? \factory\Crm::get_client_name( (int)$row['client_id'] ) : null;
      $task['project'] = \factory\Projects::get_project_name( $row['project_id'] );
      $tasks[] = $task;
    }
    return $tasks;
  }

  static public function get_tasks_gantt( $user_id, $projects = null, $users = null ) {
    global $mdb;

    if ( $users ) {
      $sql = ' AND id IN (SELECT task_id FROM task_user WHERE user_id IN (' . implode( ',', $users ) . ')) ';
    } else {
      $sql = '';
    }

    if ( $projects ) {
      $sql .= ' AND project_id IN (' . implode( ',', $projects ) . ') ';
    }

    if ( $user_id != 1 ) {
      $sql_query = 'SELECT '
                    . 't.id, t.name, t.date_start, t.date_end, t.status, t.client_id, parent_id, priority '
                    . 'FROM tasks AS t '
                    . 'LEFT JOIN task_user AS tu ON t.id = tu.task_id '
                    . 'WHERE tu.user_id = ' . $user_id . ' AND show_in_calendar = 1 AND status != 2 AND status != 3 AND status != 1 AND t.date_start <= DATE_ADD(NOW(), INTERVAL 1 MONTH) ' . $sql . ' ORDER BY priority DESC, date_start ASC, date_end ASC, o ASC';
    } else {
      $sql_query = 'SELECT '
                      . 't.id, t.name, t.date_start, t.date_end, t.status, t.client_id, parent_id, priority '
                    . 'FROM tasks AS t '
                    . 'WHERE show_in_calendar = 1 AND status != 2 AND status != 3 AND status != 1 AND t.date_start <= DATE_ADD(NOW(), INTERVAL 1 MONTH) ' . $sql . ' ORDER BY priority DESC, date_start ASC, date_end ASC, o ASC';
    }

    $tasks = $mdb -> query( $sql_query ) -> fetchAll( \PDO::FETCH_ASSOC );
    foreach ( $tasks as $task ) {
      $task_json = [];
      $task_json['name'] = $task['client_id'] ? \factory\Crm::get_client_name( (int)$task['client_id'] ) . ' - ' . htmlspecialchars( $task['name'] ) : htmlspecialchars( $task['name'] );
      // start
      $task_json['start'] = $task['date_start'];
      // end
      $task_json['end'] = $task['date_end'];
      // id
      $task_json['id'] = $task['id'];
      // custom class
      // if ( $task['date_start'] <= date( 'Y-m-d H:i:s' ) )
      //   $task_json['custom_class'] = 'gantt-task-backlog';

      if ( $task['parent_id'] )
        $task_json['dependencies'] = $task['parent_id'];

      if ( $task['status'] == 6 )
        $task_json['custom_class'] = 'gantt-task-faktura';

      if ( !$task_json['custom_class'] )
        $task_json['custom_class'] = 'gantt-task-priority-' . $task['priority'];

      // progress
      $task_json['progress'] = 0;

      $data[] = $task_json;
    }

    return $data;
  }

  static public function work_delete( $work_id ) {
    global $mdb;
    return $mdb -> update( 'tasks_work', [ 'deleted' => 1 ], [ 'id' => $work_id ] );
  }

  static public function change_task_work_date_end( $task_work_id, $date_end )
  {
    global $mdb;
    return $mdb -> update( 'tasks_work', [ 'date_end' => $date_end ? date( 'Y-m-d H:i:s', strtotime( $date_end ) ) : null ], [ 'id' => $task_work_id ] );
  }

  static public function change_task_work_date_start( $task_work_id, $date_start )
  {
    global $mdb;
    return $mdb -> update( 'tasks_work', [ 'date_start' => $date_start ? date( 'Y-m-d H:i:s', strtotime( $date_start ) ) : null ], [ 'id' => $task_work_id ] );
  }

  static public function task_works( $task_id )
  {
    global $mdb;
    return $mdb -> select( 'tasks_work', '*', [ 'AND' => [ 'task_id' => $task_id, 'deleted' => 0 ], 'ORDER' => [ 'date_end' => 'DESC' ] ] );
  }

  static public function get_statuses()
  {
    global $user;

    if ( $user['id'] == 1 )
      return self::$statuses;
    else
      return [ 0 => 'nowe', 3 => 'do rozliczenia', 5 => 'do zrobienia', 4 => 'zaplanowane', 1 => 'do sprawdzenia' ];
  }

  static public function clear_task_opened( $task_id )
  {
    global $mdb;
    return $mdb -> delete( 'tasks_opened', [ 'task_id' => $task_id ] );
  }

  static public function set_task_opened_by_user( $task_id, $user_id )
  {
    global $mdb;

    if ( $mdb -> count( 'tasks_opened', [ 'AND' => [ 'task_id' => $task_id, 'user_id' => $user_id ] ] ) )
      return false;

    return $mdb -> insert( 'tasks_opened', [
      'user_id' => $user_id,
      'task_id' => $task_id
    ] );
  }

  static public function is_taks_is_opened_by_user( $task_id, $user_id )
  {
    global $mdb;
    return $mdb -> count( 'tasks_opened', [ 'AND' => [ 'task_id' => $task_id, 'user_id' => $user_id ] ] );
  }

  static public function get_filtrs( $user_id ) {
    global $mdb;
    return $mdb -> select( 'tasks_filtrs', '*', [ 'user_id' => $user_id ] );
  }

  static public function filtr_update( $filtr_id, $projects, $users ) {
    global $mdb;
    return $mdb -> update( 'tasks_filtrs', [
      'projects' => $projects,
      'users' => $users
    ], [
      'id' => $filtr_id
    ] );
  }

  static public function filtr_save( $user_id, $name, $projects, $users, $is_default ) {
    global $mdb;

    if ( $is_default ) {
      $mdb -> update( 'tasks_filtrs', [ 'is_default' => 0 ], [ 'user_id' => $user_id ] );
    }

    $mdb -> insert( 'tasks_filtrs', [
      'user_id' => $user_id,
      'name' => $name,
      'projects' => $projects,
      'users' => $users,
      'is_default' => $is_default
    ] );

    return $mdb -> id();
  }

  static public function action_change_status( $action_id, $status ) {
    global $mdb;
    return $mdb -> update( 'task_action', [ 'status' => $status ], [ 'id' => $action_id ] );
  }

  static public function comment_delete( $comment_id ) {
    global $mdb;
    return $mdb -> delete( 'tasks_comments', [ 'id' => $comment_id ] );
  }

  static public function comment_save( $task_id, $user_id, $text )
  {
    global $mdb;

    if ( !$task_id or !$user_id or !$text )
      return false;

    return $mdb -> insert( 'tasks_comments', [
        'task_id' => $task_id,
        'user_id' => $user_id,
        'text' => $text,
        'date_add' => date( 'Y-m-d H:i:s' )
      ] );
  }

  static public function action_delete( $action_id )
  {
    global $mdb;
    return $mdb -> delete( 'task_action', [ 'id' => $action_id ] );
  }

  static public function action_save( $task_id, $text )
  {
    global $mdb;
    return $mdb -> insert( 'task_action', [
        'name' => $text,
        'task_id' => $task_id
      ] );
  }

  static public function get_tasks( int $status, $user_id, $projects = null, $users = null )
  {
    global $mdb;

    $tasks = [];

    if ( $status == 2 )
    {
      $sql = ' AND date_complete > \'' . date( 'Y-m-d', strtotime( "-2 months") ) . '\'';
    }

    if ( $projects )
    {
      $sql .= ' AND project_id IN (' . implode( ',', $projects ) . ')';
    }

    if ( $users )
    {
      $sql .= ' AND id IN (SELECT task_id FROM task_user WHERE user_id IN (' . implode( ',', $users ) . '))';
    }

    if ( $user_id == 1 )
    {
      if ( in_array( $status, [ 0, 2, 3 ] ) )
        $results = $mdb -> query( 'SELECT * FROM tasks WHERE status = ' . $status . ' ' . $sql . ' ORDER BY date_end IS NOT NULL DESC, date_end ASC, name ASC' ) -> fetchAll( \PDO::FETCH_ASSOC );
      elseif ( $status == 6 )
        $results = $mdb -> query( 'SELECT * FROM tasks WHERE status = ' . $status . ' ' . $sql . ' ORDER BY open DESC, date_end IS NOT NULL DESC, date_end ASC, name ASC' ) -> fetchAll( \PDO::FETCH_ASSOC );
      else
        $results = $mdb -> query( 'SELECT * FROM tasks WHERE status = ' . $status . ' ' . $sql . ' ORDER BY open DESC, o ASC, status ASC, date_start IS NOT NULL DESC, date_start ASC, date_end IS NOT NULL DESC, date_end ASC, name ASC' ) -> fetchAll( \PDO::FETCH_ASSOC );
    }
    else
    {
      if ( in_array( $status, [ 0, 2, 3 ] ) )
        $results = $mdb -> query( 'SELECT t.* FROM tasks t LEFT JOIN task_user tu ON t.id = tu.task_id WHERE t.status = ' . $status . ' AND tu.user_id = ' . $user_id . ' ' . $sql . ' ORDER BY t.date_end IS NOT NULL DESC, t.date_end ASC, t.name ASC' ) -> fetchAll( \PDO::FETCH_ASSOC );
      else
        $results = $mdb -> query( 'SELECT t.* FROM tasks t LEFT JOIN task_user tu ON t.id = tu.task_id WHERE t.status = ' . $status . ' AND tu.user_id = ' . $user_id . ' ' . $sql . ' ORDER BY t.open DESC, t.o ASC, t.status ASC, t.date_start IS NOT NULL DESC, t.date_start ASC, t.date_end IS NOT NULL DESC, t.date_end ASC, t.name ASC' ) -> fetchAll( \PDO::FETCH_ASSOC );
    }

    foreach ( $results as $row )
    {
      $row['users'] = $mdb -> select( 'task_user', 'user_id', [ 'task_id' => $row['id'] ] );
      $tasks[] = $row;
    }

    return $tasks;
  }

  static public function get_open_task_id( $user_id )
  {
    global $mdb;
    return $mdb -> get( 'tasks_work', 'task_id', [ 'AND' => [ 'user_id' => $user_id, 'date_end' => null ] ] );
  }

  static public function task_start( $task_id, $user_id )
  {
    global $mdb;

    $mdb -> update( 'tasks_work', [
              'date_end' => date( 'Y-m-d H:i:s' )
            ], [
              'AND' => [
                'date_end'  => null,
                'user_id'   => $user_id
              ]
            ] );

    $mdb -> insert( 'tasks_work', [
              'user_id'     => $user_id,
              'task_id'     => $task_id,
              'date_start'  => date( 'Y-m-d H:i:s' )
            ] );
    return [ 'status' => 'success' ];
  }

  static public function task_end( $task_id, $user_id )
  {
    global $mdb;

    $mdb -> update( 'tasks_work', [
              'date_end' => date( 'Y-m-d H:i:s' )
            ], [
              'AND' => [
                'task_id'   => $task_id,
                'user_id'   => $user_id,
                'date_end'  => null
              ]
            ] );
    return [ 'status' => 'success' ];
  }

  static public function task_details( $task_id, $user_id = null )
  {
    global $mdb;

    $task = $mdb -> get( 'tasks', '*', [ 'id' => $task_id ] );
    $task['users'] = $mdb -> select( 'task_user', 'user_id', [ 'task_id' => $task_id ] );
    $task['actions'] = $mdb -> select( 'task_action', '*', [ 'task_id' => $task_id, 'ORDER' => [ 'status' => 'ASC', 'id' => 'ASC' ] ] );
    $task['total_time'] = self::task_total_time( $task_id );
    if ( $user_id )
      $task['is_open'] = self::is_task_open( $task_id, $user_id );
    $task['comments'] = $mdb -> select( 'tasks_comments', '*', [ 'task_id' => $task_id, 'ORDER' => [ 'date_add' => 'DESC' ] ] );

    return $task;
  }

  static public function task_total_time( $task_id, $month = '' )
  {
    global $mdb;

    $seconds = 0;

    if ( $month )
    {
      $results = $mdb -> select( 'tasks_work', [ 'date_start', 'date_end' ], [ 'AND' => [ 'deleted' => 0, 'task_id' => $task_id, 'date_end[>=]' => $month . '-01 00:00:00', 'date_end[<=]' => $month . '-' . date( 't', strtotime( $month ) ) . ' 23:59:59' ], 'ORDER' => [ 'id' => 'ASC' ] ] );
    }
    else
      $results = $mdb -> select( 'tasks_work', [ 'date_start', 'date_end' ], [ 'AND' => [ 'deleted' => 0, 'task_id' => $task_id ], 'ORDER' => [ 'id' => 'ASC' ] ] );

    if ( is_array( $results ) and count( $results ) ) foreach ( $results as $row )
    {
      if ( !$row['date_end'] )
        $row['date_end'] = date( 'Y-m-d H:i:s' );

      $seconds += strtotime( $row['date_end'] ) - strtotime( $row['date_start'] );
    }
    return $seconds;
  }

  static public function is_task_open( $task_id, $user_id )
  {
    global $mdb;

    if ( $mdb -> count( 'tasks_work', [ 'AND' => [ 'user_id' => $user_id, 'task_id' => $task_id, 'date_end' => null ] ] ) )
      return true;

    return false;
  }

  static public function work_time_clients()
  {
    global $mdb;

    $results = $mdb -> select( 'crm_client', '*', [ 'ORDER' => [ 'firm' => 'ASC' ] ] );
    foreach ( $results as $row )
    {
      $results2 = $mdb -> query( 'SELECT DISTINCT(t.id), t.name, t.pay_rate FROM tasks AS t LEFT JOIN tasks_work AS tw ON t.id = tw.task_id WHERE status != 2 AND client_id = ' . $row['id'] . ' AND tw.date_end BETWEEN \'' . date( 'Y-m-01' ) . ' 00:00:00\' AND \'' . date( 'Y-m-' ) . date( 't' ) . ' 00:00:00\' ORDER BY t.date_add DESC' ) ->  fetchAll( \PDO::FETCH_ASSOC );
      foreach ( $results2 as $row2 )
      {

        $row2['time' ] = \factory\Projects::task_total_time( $row2['id'], date( 'Y-m' ) );
        $row['tasks'][ date( 'Y-m' )][] = $row2;
      }

      $results2 = $mdb -> query( 'SELECT DISTINCT(t.id), t.name, t.pay_rate FROM tasks AS t LEFT JOIN tasks_work AS tw ON t.id = tw.task_id WHERE status != 2 AND client_id = ' . $row['id'] . ' AND tw.date_end BETWEEN \'' . date( 'Y-m-01', strtotime( '-1 months', time() ) ) . ' 00:00:00\' AND \'' . date( 'Y-m-', strtotime( '-1 months', time() ) ) . date( 't', strtotime( '-1 months', time() ) ) . ' 00:00:00\' ORDER BY t.date_add DESC' ) ->  fetchAll( \PDO::FETCH_ASSOC );
      foreach ( $results2 as $row2 )
      {

        $row2['time' ] = \factory\Projects::task_total_time( $row2['id'], date( 'Y-m', strtotime( '-1 months', time() ) ) );
        $row['tasks'][ date( 'Y-m', strtotime( '-1 months', time() ) )][] = $row2;
      }

      $results2 = $mdb -> query( 'SELECT DISTINCT(t.id), t.name, t.pay_rate FROM tasks AS t LEFT JOIN tasks_work AS tw ON t.id = tw.task_id WHERE status != 2 AND client_id = ' . $row['id'] . ' AND tw.date_end BETWEEN \'' . date( 'Y-m-01', strtotime( '-2 months', time() ) ) . ' 00:00:00\' AND \'' . date( 'Y-m-', strtotime( '-2 months', time() ) ) . date( 't', strtotime( '-2 months', time() ) ) . ' 00:00:00\' ORDER BY t.date_add DESC' ) ->  fetchAll( \PDO::FETCH_ASSOC );
      foreach ( $results2 as $row2 )
      {

        $row2['time' ] = \factory\Projects::task_total_time( $row2['id'], date( 'Y-m', strtotime( '-2 months', time() ) ) );
        $row['tasks'][ date( 'Y-m', strtotime( '-2 months', time() ) )][] = $row2;
      }

      $work_time[] = $row;
    }
    return $work_time;
  }

  // przy zmianach pamiętać o zadaniach z CRON
  static public function task_save( $task_id, $parent_id = null, $user_id, $name, $text, $date_start, $date_end, $project_id, $client_id, $pay_rate, $reminders_interval, $recursively, $frequency, $period, $users, $date_end_month_day = null, $date_start_month_day = null, $send_email_notification = false, $status_change_mail, $rescursive = false, $status = 0, $show_in_calendar, $priority = 0 )
  {
    global $mdb;

    if ( !$task_id )
    {
      $order = $mdb -> max( 'tasks', 'o', [ 'AND' => [ 'project_id' => $project_id, 'date_end[<=]' => $date_end ] ] );

      $mdb -> insert( 'tasks', [
        'created_by' => $user_id,
        'parent_id' => $parent_id,
        'name' => $name,
        'text' => $rescursive ? $text : htmlspecialchars( $text ),
        'date_start' => $date_start != '' ? "$date_start" : null,
        'date_end' => $date_end != '' ? $date_end : null,
        'project_id' => $project_id,
        'client_id' => $client_id ? $client_id : null,
        'pay_rate' => ( $pay_rate != '' and $pay_rate > 0 ) ? $pay_rate : null,
        'reminders_interval' => $reminders_interval != '' ? $reminders_interval : null,
        'recursively' => $recursively == 'on' ? 1 : 0,
        'frequency' => $frequency,
        'period' => $period,
        'date_end_month_day' => $date_end_month_day,
        'date_start_month_day' => $date_start_month_day,
        'status_change_mail' => $status_change_mail == 'on' ? 1 : 0,
        'o' => ++$order,
        'status' => $status,
        'show_in_calendar' => $show_in_calendar == 'on' ? 1 : 0,
        'priority' => $priority,
      ] );
      $id = $mdb -> id();

      /* uczestnicy */
      if ( is_array( $users ) and !empty( $users ) ) foreach ( $users as $user )
      {
        if ( $id and $user and !$mdb -> count( 'task_user', [ 'AND' => [ 'task_id' => (int)$id, 'user_id' => (int)$user ] ] ) )
        {
          if ( $mdb -> insert( 'task_user', [ 'task_id' => (int)$id, 'user_id' => (int)$user ] ) )
            if ( $send_email_notification == 'on' )
              \factory\Projects::send_email_notification( $id, $user );
        }
      }
      else if ( $users and !empty( $users ) )
      {
        if ( $id and $users and !$mdb -> count( 'task_user', [ 'AND' => [ 'task_id' => (int)$id, 'user_id' => (int)$users ] ] ) )
         if ( $mdb -> insert( 'task_user', [ 'task_id' => (int)$id, 'user_id' => (int)$users ] ) );
          if ( $send_email_notification == 'on' )
            \factory\Projects::send_email_notification( $id, $users );
      }

      return $id;
    }
    else
    {
      $mdb -> update( 'tasks', [
        'name' => $name,
        'text' => htmlspecialchars( $text ),
        'date_start' => $date_start != '' ? $date_start : null,
        'date_end' => $date_end != '' ? $date_end : null,
        'project_id' => $project_id,
        'client_id' => $client_id ? $client_id : null,
        'pay_rate' => ( $pay_rate != '' and $pay_rate > 0 ) ? $pay_rate : null,
        'reminders_interval' => $reminders_interval,
        'recursively' => $recursively == 'on' ? 1 : 0,
        'frequency' => $frequency,
        'period' => $period,
        'reminders_send' => 0,
        'status_change_mail' => $status_change_mail == 'on' ? 1 : 0,
        'status' => $status,
        'show_in_calendar' => $show_in_calendar == 'on' ? 1 : 0,
        'priority' => $priority,
      ], [
        'AND' => [
          'id' => $task_id
        ]
      ] );

      /* uczestnicy */
      $mdb -> delete( 'task_user', [ 'task_id' => (int)$task_id ] );

      if ( is_array( $users ) and !empty( $users ) ) foreach ( $users as $user )
      {
        if ( $task_id and $user )
          $mdb -> insert( 'task_user', [ 'task_id' => (int)$task_id, 'user_id' => (int)$user ] );
      }
      else if ( !empty( $users ) )
      {
        if ( $task_id and $users )
          $mdb -> insert( 'task_user', [ 'task_id' => (int)$task_id, 'user_id' => (int)$users ] );
      }

      $mdb -> delete( 'tasks_reminders', [ 'task_id' => $task_id ] );

      return $task_id;
    }
    return false;
  }

  static public function task_delete( $task_id ) {

    $task_first_id = \factory\Tasks::task_first_id( $task_id );
    \factory\Tasks::task_delete_all( $task_first_id );

    return true;
  }

  static public function task_first_id( $parent_id ) {
    global $mdb;

    if ( $task_id = $mdb -> get( 'tasks', 'parent_id', [ 'id' => $parent_id ] ) )
      return self::task_first_id( $task_id );
    else
      return $parent_id;
  }

  static public function task_delete_all( $task_id )
  {
    global $mdb;

    $parent_id = $mdb -> get( 'tasks', 'parent_id', [ 'id' => $task_id ] );

    if ( !$parent_id ) {
      $children_id = self::task_delete_from_db( $task_id );
      if ( $children_id )
        self::task_delete_all( $children_id );
    }

    if ( $parent_id )
      self::task_delete_all( $parent_id );
    else
      return false;
  }

  static public function task_delete_from_db( int $task_id )
  {
    global $mdb;

    $children = $mdb -> get( 'tasks', 'id', [ 'parent_id' => $task_id ] );

    $mdb -> delete( 'tasks', [ 'id' => $task_id ] );
    $mdb -> update( 'tasks', [ 'parent_id' => null ], [ 'parent_id' => $task_id ] );

    return $children;
  }
}
?>