<?php

namespace App\Http\Controllers;

use App\CustomClass\Helper;
use App\Models\InOut;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class CronJobController extends Controller
{
    public function execute($manual = false)
    {
        $today = date('Y-m-d');
        $presents = InOut::with('user')
            ->select('date', 'user_id', DB::raw('MAX(id)as id','in_time'))
            ->where('out_time', null)
            ->groupBy('user_id', 'date')
            ->orderBy('user_id', 'ASC')
            ->whereHas('user',function ($query){
                $query->where('auto_exit',1);
            });
        if ($manual == 1) {
            $presents = $presents->where('client_id',1);
        } else {
            $presents = $presents->where('date', $today);
            $presents = $presents->where('client_id',1);
        }
        $presents = $presents->get();
        foreach ($presents as $val) {
            date_default_timezone_set($val->user->timezone);
            $now = date('hi');
            if ($now > 2350 && $now < 2359) {
                $time_calc= (new Carbon($val->user->out_time))->diff(new Carbon($val->in_time))->format('%h:%i:%s');
                $time_calc= Helper::timeToSecond($time_calc);
                $val->update(['out_time' => $val->user->out_time,'time_calc'=>$time_calc]);
            }
        }
        Log::info($presents);
    }
}
