<?php

namespace App\Console\Commands;


use Carbon\Carbon;
use Illuminate\Console\Command;
use DB;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Portal\Ecuti\Model\LeaveBalance;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;



class UpdateBalance extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'schedule:update-balance';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Calculate to update new balance';
    // Maklumat Cuti Staf untuk Tahun Semasa      
    // Termasuk Baki Cuti Rehat dan Cuti Sakit 
 

    /**
     * Create a new command instance.
     *
     * @return void
     */
   /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {

        //update balance CSAK
        $csak = DB::SELECT("SELECT staff_id,leave_code,SUM(balance) as'balance' FROM `leave_quota` WHERE leave_code = '41' GROUP BY staff_id,leave_code");
               
            foreach ($csak as $key => $value) 
            {
                
                $update = LeaveBalance::where('staff_id', '=', $value->staff_id)->first();
                // dd($value->balance);
                if($update){

                    $update->balance_csak = $value->balance;
                    $update->update();
                }else{


                    $bcsak = new LeaveBalance;
                    $bcsak->staff_id = $value->staff_id;
                    $bcsak->balance_csak = $value->balance;
                    $bcsak->balance_flag = null;
                    $bcsak->balance_creh = 0.00;
                    $bcsak->save();



                }
                              
            }


        //update balance creh
        $creh = DB::SELECT("SELECT staff_id,SUM(entitlement),SUM(taken),SUM(balance) AS 'balance' FROM `leave_quota` WHERE (leave_code = '01' OR leave_code = '10' OR leave_code = '21' OR leave_code = '38') GROUP BY staff_id");

        foreach ($creh as $key => $value) 
            {
                
                $update = LeaveBalance::where('staff_id', '=', $value->staff_id)->first();
                // dd($value->balance);
                if($update){

                    $update->balance_creh = $value->balance;
                    $update->update();
                }else{


                    $bcsak = new LeaveBalance;
                    $bcsak->staff_id = $value->staff_id;
                    $bcsak->balance_creh = $value->balance;
                    $bcsak->balance_flag = null;
                    $bcsak->balance_csak = 0.00;
                    $bcsak->save();



                }
                              
            }

    }
}
