<?php

namespace App\Console\Commands;

use App\Mail\CarenceDocs;
use App\Models\Company;
use App\Models\Document;
use App\Models\Dossier;
use App\Models\Email;
use App\Models\Notification;
use App\Models\Step;
use App\Models\Transaction;
use App\Models\TypeDocument;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Console\Command;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Type;

class MailCron extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:mail';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $dossiers = Dossier::where('dossier_status_id', 2)
        ->with('document.typedocument', 'currentStep', 'company')
        ->get();

    foreach ($dossiers as $dossier) {
        $array = [];
        $result = [];
        $email = Email::where('step_id', $dossier->step_id)->with('typedocument')->first();
        if ($email) {
            foreach ($email->typedocument as $type) {
                array_push($array, $type->id);
            }
            if (!empty($array)) {
                if ($dossier->document) {
                    $types = [];
                    foreach ($dossier->document as $doc) {
                        foreach ($array as $type) {
                            if ($doc->type_document_id == $type) {
                                array_push($types, $type);
                            }
                        }
                    }
                    $result = array_diff($array, $types);

                }
                else{
                    $result = $array;
                }

                if (!empty($result)) {
                    // Mail::to($dossier->company->email_pro)->send(new CarenceDocs($email, $dossier,$result));
                    Mail::send('email.carence', ['email'=>$email,'dossier' => $dossier,'result'=>$result], function ($message) use ($email,$dossier,$result) {
                        $message->from('namaty06@gmail.com', 'AMEA');
                        $message->to($dossier->company->email_pro);
                        $message->subject($email->subject);

                    });
                    Transaction::create([
                        'from' => "nma@gmail.com",
                        'to' => $dossier->company->email,
                        'subject' => $email->subject,
                        'content' => $email->content,
                        'dossier_id' => $dossier->id

                    ]);
                }
            }
        }
    }
    }
}
