<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Subscription;
use App\Client;
use App\Invoice;
use App\Charge;
use App\Email;
use App\Transaction;
use PDF;
use Mail;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\ConfigController;
use App\User;
use App\Notifications\NotifySecondOverDueInvoice;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Send second email to client for invoice over reminder';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        Log::channel('cron_over_due_check')->info('');
        Log::channel('cron_over_due_check')->info('===================== START Overdue 2nd INVOICE SCHEDULER ========================');

        $status = 'o';
        $date = date('Y-m-d', strtotime(now().' -4 day'));

        $invoices = Invoice::where('status',$status)
                            ->where('frcs_verified','1')
                            ->where('transaction_type','Sale')
                            ->where('invoice_type','Normal')
                            ->where('due_date',$date)
                            ->get();

        Log::channel('cron_over_due_check')->info(count($invoices).' Invoice(s) found...');
        Log::channel('cron_over_due_check')->debug('Invoice(s) dump below...');
        Log::channel('cron_over_due_check')->debug($invoices);
        Log::channel('cron_over_due_check')->debug('Invoice(s) dump ends...');

        foreach ($invoices as $invoice) 
        {
            Log::channel('cron_over_due_check')->info('Fetching transactions for invoice# '.$invoice->uuid);

            $transactions = Transaction::where('invoice_id',$invoice->id)->get();
            $balance = Transaction::where('invoice_id',$invoice->id)->sum('amount');

            Log::channel('cron_over_due_check')->info('Total Trnx found '.count($transactions));
            Log::channel('cron_over_due_check')->info('Total remaining balance '.$balance);
            Log::channel('cron_over_due_check')->debug('Transaction(s) dump below...');
            Log::channel('cron_over_due_check')->debug($transactions);
            Log::channel('cron_over_due_check')->debug('Transaction(s) dump ends...');

            //get client email
            $client_email = Client::select('email')->find($invoice->client_id);
            $client_name = Client::select('contact_name')->find($invoice->client_id);
            $client_business_name = Client::select('business_name')->find($invoice->client_id);

            $due_date = $invoice->due_date;
                        $data = array(
                            'name' => $client_name->contact_name,
                            'amount_due'  => $balance,
                            'due_date'  => $invoice->due_date,
                            'invoice'  => $invoice,
                        );

            Log::channel('cron_over_due_check')->info('Preparing to send email...');
            Log::channel('cron_over_due_check')->info('Sending email to '.$client_email);



            try{

                    $emails_data = array(   
                                        'email' => $client_email->email,
                                        'name' => $client_name->contact_name,
                                        'id' => $invoice->uuid,
                                        'cc_name' => config('app.name'),
                                        'cc_email'=> config('app.email')
                                    );

                    Mail::send('emails.sec_overdue', array('data'=>$data), function($message) use ($emails_data)
                    {    
                        $message->to($emails_data['email'],$emails_data['name'])
                                ->cc($emails_data['cc_email'],$emails_data['cc_name'])
                                ->subject('Second Invoice Overdue Notice - Inv#'.$emails_data['id']);
                                
                    });

                    $status_email = false;

            }
            catch(\Exception $e)
            {
                    $email = new Email;
                    $email->type = 'Invoice';
                    $email->type_id = $invoice->id;
                    $email->name = 'Overdue - Second Notice';
                    $email->sent = 'n';
                    $email->save();

                    Log::channel('cron_over_due_check')->debug('Email not sent for invoice ID '.$invoice->uuid);
                    Log::channel('cron_over_due_check')->debug($e);
                    Log::channel('cron_over_due_check')->debug('END ERROR LOGS for Invoice ID '.$invoice->uuid);

                    $status_email = true;
            }

            if($status_email == false)
            {

                $email = new Email;
                $email->type = 'Invoice';
                $email->type_id = $invoice->id;
                $email->name = 'Overdue - Second Notice';
                $email->sent = 'y';
                $email->save();

                $update_invoice = '';
                $update_invoice = Invoice::find($invoice->id);
                $update_invoice->send_email = '';
                $update_invoice->save();
            }
            //Email sending ends

            // update invoice status
            $update = Invoice::find($invoice->id);
            User::find(1)->notify(new NotifySecondOverDueInvoice($update));


        }//end foreach loop

        
        Log::channel('cron_over_due_check')->info('===================== End Overdue INVOICE SCHEDULER ========================');
        Log::channel('cron_over_due_check')->info('');
    }
}
