<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Jobs\SendEmail;
use App\model\EmailAutomation;
use App\model\LeadStatus;
use App\model\Agentemail;
use App\model\Company;
use App\model\Leadclient;
use App\model\CollectionDetails;
use App\model\VendorDetails;
use App\User;
use App\model\Property;
use PDF;

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

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

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $emails = EmailAutomation::all();
        if($emails->count() > 0)
        {
            foreach($emails as $data)
            {
                $leadId = LeadStatus::where('id',$data->curr_status)->first();
                
                $user = User::where('id',$data->agent_id)->first();
                // get all the emails created by this agent
                //$getemailtypes = Agentemail::where('agent_id',$user->create_by_user)->orWhere('agent_id',$user->assign_to_ar)->get();

                $getemailtypes = Agentemail::where([['agent_id',$user->create_by_user],['status',1]])->orWhere([['agent_id',$user->assign_to_ar],['status',1]])->get();


                foreach($getemailtypes as $types)
                {
                    $w9File = '';
                    $brokerLicense = '';
                    $invoice = '';

                    if($types->auto_send_day != '' && $leadId->new_status_name == $types->curr_status)
                    {
                        $statusDate = $data->date;
                        $sendMailDate = date('Y-m-d', strtotime($statusDate. ' + '.$types->auto_send_day.' days'));

                        $time = $types->time.' '.$types->timezone;
                        
                        if($sendMailDate == date('Y-m-d') && date('H:i A') == date('H:i A', strtotime($time)))
                        {
                            $body = $types->email_body;
                            
                            $email_signature = nl2br($types->email_signature);

                            $admin = User::where('id',$user->create_by_user)->first();
                            $fromEmail = $admin->email;

                            $company = Company::where('id',$user->company)->first();
                            if($types->w9_file == 1)
                            {
                                $w9File = $company->mgmt_w9;
                            }

                            if($types->broker_license == 1)
                            {
                                $broker_license = $company->mgmt_broker_license;
                            }

                            if($types->invoice == 1)
                            {
                                $agent_id       =  $data->agent_id;

                                $agent_info     =   User::where('id',$agent_id)->first();
                                $company        =   $agent_info->company;
                                // dd($company);
                                $leadclient     =   Leadclient::find($data->lead_id);
                                $agentdetail    =   User::find($agent_id);
                                
                                $collection     =   CollectionDetails::where('property_id', $leadclient->prop_id)
                                                                ->where('company_id', $company)
                                                                ->OrderBy('id', 'desc')
                                                                ->first();

                                $vendor         =   VendorDetails::where('property_id', $leadclient->prop_id)
                                                        ->where('company_id', $company)
                                                        ->OrderBy('id', 'desc')
                                                        ->first();

                                $property       =   Property::find($leadclient->prop_id);
                                $real_state     =   Company::find($company);

                                if (empty($property)){
                                    
                                    $property   = (object) array(
                                        'prop_name'             => '',
                                        'bill_add'              => '',
                                        'bill_city'             => '',
                                        'bill_state'            => '',
                                        'prop_phone'            => '',
                                        'prop_fax'              => '',
                                        'prop_manager'          => '',
                                        'bill_zip'              => ''
                                    );

                                    $company    = array();
                                }

                                /* Get the details of client and company */
                                $agent_id       = $leadclient->agent_id;
                                $leadagent      = User::find($agent_id);
                                $company        = Company::find($leadagent->company);

                                if (!empty($collection)){
                                  $collection_notes = $collection->collection_details;
                                }else{
                                  $collection_notes = '';
                                }

                                if (!empty($vendor)){
                                  $vendor_id    = $vendor->vendor_id;
                                }else{
                                  $vendor_id    = '';
                                }

                                $tot_com        = 0;
                              
                                if (trim($leadclient->commision) == ""){
                                  $leadclient->commision    = 0;
                                }

                                if (trim($leadclient->bonus) == ""){
                                  $leadclient->bonus        = 0;
                                }

                                if ($leadclient->commision_unit == "1"){
                                    if ((float) $leadclient->commision != 0 || (float) $leadclient->commision != 0.00){

                                      $tot_com  = ((float) $leadclient->rent_amount * ((float) $leadclient->commision / 100));
                                      $total    = ((float) $leadclient->rent_amount * ((float) $leadclient->commision / 100)) + $leadclient->bonus;
                                      $leadclient->commision_unit = "%";
                                    }else{
                                        $total = 0;
                                    }
                                }else{

                                    $tot_com                    = (float) $leadclient->commision;
                                    $total                      = (float) $leadclient->commision + (float) $leadclient->bonus;
                                    $leadclient->commision_unit = "Flat Fee";
                                }
                                
                                /* Get all related data here for calculation  */
                                $leadclient->commision      =   number_format((float)$leadclient->commision, 2, '.', '');
                                $leadclient->tot_com        =   number_format((float)$leadclient->tot_com, 2, '.', '');
                                $leadclient->rent_amount    =   number_format((float)$leadclient->rent_amount,2, '.', '');
                                $leadclient->bonus          =   number_format((float)$leadclient->bonus, 2, '.', '');
                                $total                      =   number_format((float)$total, 2, '.', '');
                                $date                       =   date("m/d/Y");
                                
                                if ($leadclient->commision_unit == "Flat Fee"){
                                  $leadclient->commision = "$" . $leadclient->commision;
                                }

                                /* calculate total commision here */
                                $otherdata['tot_com'] = (float) $tot_com;
                                $otherdata['total']   = (float) $total;

                                $pdf    =   PDF::loadView('leadclient.invoicepdf', 
                                                        [
                                                            'property'          =>  $property, 
                                                            'clientdetail'      =>  $leadclient , 
                                                            'leadclient'        =>  $leadclient, 
                                                            'agentdetail'       =>  $agentdetail, 
                                                            'otherdata'         =>  $otherdata, 
                                                            'company'           =>  $company, 
                                                            'collection_notes'  =>  $collection_notes, 
                                                            'vendor_id'         =>  $vendor_id
                                                        ],

                                compact('leadclient'));
                                $pdf->save(storage_path('pdf/invoicepdf/' . $leadclient->id . '_leaseverify.pdf'));
                                $invoice = storage_path('pdf/invoicepdf/'.$leadclient->id.'_leaseverify.pdf');
                                //dd('done');
                            }
                            
                            $types->email_body = str_replace("[Signature]",$email_signature,$types->email_body);

                            $details= ['prop_email' => $data->prop_email, 'prop_invoice_email' => $data->prop_invoice_email, 'lead_id' => $data->lead_id,'data' => $types,'w9_file' => $w9File,'broker_license' => $broker_license, 'invoice' => $invoice, 'fromEmail' => $fromEmail];
                            // SendEmail::dispatch($details);
                            SendEmail::dispatchNow($details);
                            // SendEmail::dispatch($details)->delay(now()->addSeconds(30));
                            // SendEmail::dispatch($details)->onQueue('email_automation');
                        }
                    }
                }
            }
        }
    }
}
