<?php

namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;

use App\Cawangan;
use App\Gadai;
use Carbon\Carbon;

class DailyGadai extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'gadai:daily';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Update JBG for every active gadai';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $cawangan = Cawangan::on('mysql7')->get();
        $current = Carbon::now();
        foreach($cawangan as $cawangan_mysql){
            $all_gadai = Gadai::on($cawangan_mysql['mysql'])->whereNotIn('sttebus',['L','T'])->get();
            foreach($all_gadai as $gadai){
                if($gadai['t_update'] == null){
                    $tarikh_update = Carbon::parse($gadai['t_gadai'].' '. $gadai['masa']);
                }else{
                    $tarikh_update = Carbon::parse($gadai['t_update'].' 00:00:00' );
                }
                $tarikh_gadai = Carbon::parse($gadai['t_gadai'].' '. $gadai['masa']);

                $diff_gadai = date_diff($tarikh_gadai,$current);
                $month_gadai = $diff_gadai->format("%m");
                $days_gadai = $diff_gadai->format("%d");
                $days_gadai = $days_gadai + 1;

                if($days_gadai >= 1 && $days_gadai <= 15)
                {
                    $extensivemonth_gadai = 0.5;
                }
                else if($days_gadai >= 16)
                {
                    $extensivemonth_gadai = 1;
                }
                $tempoh_gadai = $month_gadai + $extensivemonth_gadai;

                $diff = date_diff($tarikh_update,$current);
                $month = $diff->format("%m");
                $days = $diff->format("%d");
                $days = $days + 1;
                if($days >= 1 && $days <= 15)
                {
                    $extensivemonth = 0.5;
                }
                else if($days >= 16)
                {
                    $extensivemonth = 1;
                }
                $tempoh_update = $month + $extensivemonth;
                Gadai::on($cawangan_mysql['mysql'])->where('norujukan','=',$gadai['norujukan'])->update(array(
                    'jbg' => $tempoh_update,
                    'tempoh' => $tempoh_gadai
                ));
            }
        }
    }
}