<?php

namespace App\Console;

use App\Http\Controllers\InvoiceController;
use App\InvoiceStatuses;
use Carbon\Carbon;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use ZipArchive;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        //
    ];

    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
         $schedule->call(function(){
             $zipname = 'do_'.Carbon::today()->format('Y_m_d').'.zip';
             $zip = new ZipArchive;
             $zip->open(storage_path('tempdir').'/'.$zipname, ZipArchive::CREATE);
             $approvedInvoices = InvoiceStatuses::where('status', 'approve')->whereDate('created_at', Carbon::today())->distinct()->get(['invoice_id']);
             $bookings = [];
             foreach($approvedInvoices as $approved){
                 if($approved->invoice->booking->user_id !== 1){
                     $bookings[] = $approved->invoice->booking->id;
                 }
             }
             foreach ($bookings as $id) {
                 $do = app(InvoiceController::class)->generateSupplierDo($id);
                 $zip->addFromString('do_'.Carbon::today()->format('Y_m_d').'_'.$id.'.pdf', $do->Output('do.pdf', 'S'));
             }
             $zip->close();
             $attachment = storage_path('tempdir').'/'.$zipname;

             Mail::raw( "Attention to VT Admin team:\r\n\r\nKindly refer to the attachment for our DAILY DO COMPILATION ".Carbon::today()->format('d-m-Y').".\r\n\r\n**This is an automatically generated email – please do not reply to it. If you have any queries kindly contact our admin team through Wechat.\r\n\r\n\r\nCIEF WORLDWIDE SDN BHD", function($message) use ($attachment){
                 $message->from('exchange@cief-malaysia.com');
                 $message->to(['vtnation16@gmail.com', 'vtnation@gmail.com', 'atvantic04@gmail.com', 'vtnation2@gmail.com']);
                 $message->cc(['shafiqa_sukeri@cief-malaysia.com', 'frontendcief@gmail.com', 'pm@cief-malaysia.com', 'hasan@cief-malaysia.com', 'shipping_admin@cief-malaysia.com', 'hasanakbar27@gmail.com', 'pmwong2019@gmail.com']);
                 $message->subject('CIEF DAILY DO COMPILATION '.Carbon::today()->format('d-m-Y'));

                 $message->attach($attachment);
             });

             File::delete(storage_path('tempdir').'/'.$zipname);
         })->everyMinute();
    }

    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');

        require base_path('routes/console.php');
    }
}
