<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputArgument;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use App\Modules\Bookings\Task;
use App\Modules\Bookings\Repair;
use App\Modules\Bookings\Support;
use App\Modules\Bookings\Onsite;
use App\Modules\Bookings\TaskFeedback;
use App\Modules\Gamification\PointsTransaction;
use App\Modules\Clients\Client;
use App\Console\Commands\AbstractCommand;

class StatsTest extends AbstractCommand
{
    /**
     * A friendly name of the command that will be used when loggin messages.
     *
     * @var string
     */
    protected $command_title = 'Stats Testing';

    /**
     * The console command name.
     *
     * @var string
     */
    protected $name = 'stats:test';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Stats testing for the parts/labour. Code from /stats.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return void
     */
    public function fire()
    {
      $start_date_march_16 = "1456790400";
      $end_date_march_16 = "1459425599";

      $start_date_april_16 = "1459468800";
      $end_date_april_16 = "1461974398";


      $users = User::getActiveList(['id', 'first_name', 'last_name', 'points']);
      $task_types = ['repair', 'support', 'onsite'];
  //    $parts = Part::select(DB::raw('SUM(quantity) as qnt'))          ;


    /*  'overdue' => Task::leftJoin('parts', function ($join) {
                      return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                  })
                  ->where('completed', 1)->where('paid', 0)->overdue()
                  ->whereIn('tasks.type', ['repair', 'support', 'onsite'])
                  ->select(\DB::raw('SUM(labour) as labour, SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts'))->first()->toArray(),

*/

      // Get stats for different task types
      $repairs = Task::select(DB::raw('COUNT(id) as cnt, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_march_16, $end_date_march_16)->where('type', 'repair')->groupBy('assigned_to')->get();
      $support = Task::select(DB::raw('COUNT(id) as cnt, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_march_16, $end_date_march_16)->where('type', 'support')->groupBy('assigned_to')->get();
      $onsite_mar = Task::select(DB::raw('COUNT(id) as cnt, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_march_16, $end_date_march_16)->where('type', 'onsite')->groupBy('assigned_to')->get();
      $onsite_apr = Task::select(DB::raw('COUNT(id) as cnt, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_april_16, $end_date_april_16)->where('type', 'onsite')->groupBy('assigned_to')->get();

      $labour = Task::select(DB::raw('SUM(labour) as labour, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_march_16, $end_date_march_16)->whereIn('type', $task_types)->groupBy('assigned_to')->get();
      $booking_fee = Task::select(DB::raw('COUNT(id) as cnt, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_march_16, $end_date_march_16)->whereNotNull('booking_fee_id')->groupBy('assigned_to')->get();

      $parts_mar = Task::leftJoin('parts', function ($join) {
                        return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                    })->select(DB::raw('SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_march_16, $end_date_march_16)->groupBy('assigned_to')->get();

      $parts_apr = Task::leftJoin('parts', function ($join) {
                          return $join->on('parts.related_id', '=', 'tasks.id')->where('parts.related_type', '=', 'task');
                        })->select(DB::raw('SUM(parts.quantity * parts.price * (parts.vat / 100 + 1)) as parts, assigned_to'))->whereNotNull('assigned_to')->completed()->thisMonth($start_date_april_16, $end_date_april_16)->groupBy('assigned_to')->get();


      $points_mar = Task::leftJoin('points_transactions', function ($join) {
        $join = $join->on('points_transactions.task_id', '=', 'tasks.id')->where('points_transactions.identifier', '=', 'task');
      })->select(DB::raw('SUM(points_transactions.amount) as cnt, tasks.assigned_to'))->whereNotNull('user_id')->completed()->thisMonth($start_date_march_16, $end_date_march_16)->where('identifier','task')->groupBy('user_id')->get();


      $points_apr = Task::leftJoin('points_transactions', function ($join) {
        $join = $join->on('points_transactions.task_id', '=', 'tasks.id')->where('points_transactions.identifier', '=', 'task');
      })->select(DB::raw('SUM(points_transactions.amount) as cnt, tasks.assigned_to'))->whereNotNull('user_id')->completed()->thisMonth($start_date_april_16, $end_date_april_16)->where('identifier','task')->groupBy('user_id')->get();


      // A helper function to merge the results from above
      // with all users
      $array_reject = function (&$array, $user_id) {

          foreach ($array as $i => $item) {
            //  if($user_id == 79)
              //  $this->info("Checking if ".$i." is ".$user_id);
              if ($item->assigned_to == $user_id) {
                  if($user_id == 79)
                  {
                  //  $this->info("Found it". $i);
                  //  print_r($array[$i]);
                  }
                  unset($array[$i]);

                  return $item;
              }
          }

          return 0;
      };
      foreach ($users as $user) {
          // Repairs
          //dd($repairs);
          $count = $array_reject($repairs, $user->id);
          $user->repairs = ($count) ? $count->cnt : 0;

          // Remote support
          $count = $array_reject($support, $user->id);
          $user->remoteSupport = ($count) ? $count->cnt : 0;

          // Onsite
          $count = $array_reject($onsite_mar, $user->id);
          $user->onsite = ($count) ? $count->cnt : 0;
          // $this->info("mar onsite-> " .$user->username. " ".$user->onsite);

          $count = $array_reject($onsite_apr, $user->id);
          $user->onsite = ($count) ? $count->cnt : 0;
          // $this->info("apr onsite-> " .$user->username. " ".$user->onsite);


          // Labour
          $count = $array_reject($labour, $user->id);
          $user->labour = ($count) ? $count->labour : 0;

          // Booking Fees
          $count = $array_reject($booking_fee, $user->id);
          $user->booking_fee = ($count) ? $count->cnt * Config::get('settings.booking_fee') : 0;

          // Parts
          $count = $array_reject($parts_mar, $user->id);
          $user->parts = ($count) ? $count->parts : 0;
          // $this->info("mar parts-> " .$user->username. " ".$user->parts);

          $count = $array_reject($parts_apr, $user->id);
          $user->parts = ($count) ? $count->parts : 0;
          // $this->info("apr parts-> " .$user->username. " ".$user->parts);

          // points
          $count = $array_reject($points_apr, $user->id);
          $user->amount = ($count) ? $count->cnt : 0;
          // $user->points = ($points) ? $count->points : 0;
          $this->info("apr  points-> " .$user->username. " ".$user->amount);

          $count = $array_reject($points_mar, $user->id);
          $user->amount = ($count) ? $count->cnt : 0;
          // $user->points = ($points) ? $count->points : 0;
          $this->info("mar  points-> " .$user->username. " ".$user->amount);





      }
      //dd($users);
      $this->info(date("j,n,Y",$start_date_march_16) . " ".date("j,n,Y",$end_date_march_16) );
      $this->info(date("j,n,Y",$start_date_april_16) . " ".date("j,n,Y",$end_date_april_16) );



      return $users;
    }
}
