<?php

namespace App\Console\Commands;

use DB;
use App\Gasto;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        date_default_timezone_set('America/Mexico_City');
        $fechaactual = date("Y-m-d");
        $diaActual =  date("j");
        $mesActual = date("n");
        //echo 'Dia='.$diaActual.' Mes='.$mesActual.'<br>';
        $query = 'SELECT * from catalogo_gastos where estatus=1';
        $gastos = DB::select($query);
        $gastos = $this->object_to_array($gastos);
        foreach ($gastos as $key => $value) {
            //echo $value['concepto'].'<br>';
            if($value['periocidad']==1){
                if($diaActual==$value['dia_pago']){
                    $data = [
                        'tipo' => 1,
                        'concepto' => $value['concepto'],
                        'importe' => $value['importe'],
                        'periocidad' => $value['periocidad'],
                        'fecha' => $fechaactual
                    ];
                    $cliente = Gasto::create($data);
                }
            }elseif($value['periocidad']==2){
                if($diaActual==$value['dia_pago'] && $mesActual==$value['mes_pago']){
                    $data = [
                        'tipo' => 1,
                        'concepto' => $value['concepto'],
                        'importe' => $value['importe'],
                        'periocidad' => $value['periocidad'],
                        'fecha' => $fechaactual
                    ];
                    $cliente = Gasto::create($data);        
                }
            }else{

            }
        }
    }
    public function object_to_array($data) {
        if (is_array($data) || is_object($data)) {
            $result = array();
            foreach ($data as $key => $value) {
                $result[$key] = $this->object_to_array($value);
            }
            return $result;
        }
    return $data;
    }
}
