<?php

namespace App\Console\Commands;

use App\CustomerProperty;
use App\CustomerStatement;
use Illuminate\Console\Command;
use DB;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check due date and add surcharge accordingly';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $properties = CustomerProperty::where('status',CustomerProperty::approved)->orderBy('created_at', 'desc')->where([['is_deleted', false]]) 
        ->get();
        $today = \Carbon\Carbon::today();
        foreach( $properties as $property){

           $days_after_fine_added = $property->schedulePlan->days_after_fine_added;
           $fine_per = $property->schedulePlan->fine;
           $query=    $property->statement()
            ->selectRaw("*, DATEDIFF(CURDATE(), due_date) AS days_difference")
            ->where('due_date', '<', $today)
            ->where('balance', '>', 0)
            ->whereRaw("DATEDIFF(CURDATE(), due_date) >= ?", [$days_after_fine_added])
            ->get()
             ;
            
             if(sizeof($query) > 0){
    
                 foreach($query as $q){
                   $day_diff= abs($days_after_fine_added - $q->days_difference);
                   $latedays=      $day_diff + 1;
                   $amount = $q->due;
                   $value =   ($latedays * (($amount/100) * $fine_per));
                   $value =  round($value);
                     CustomerStatement::where('id',$q->id)->update([      
                        'surcharge_calculated_by_cron' => $value
                    ]);
                 }
             }
        }
       
        
     
   
    }
}
