public function run()
 {
     Model::unguard();
     $faker = Faker::create('pt_BR');
     $faker->addProvider(new \Faker\Provider\pt_BR\Person($faker));
     $faker->addProvider(new \Faker\Provider\pt_BR\Address($faker));
     // $faker->addProvider(new \Faker\Provider\en_US\Address($faker));
     // $faker->addProvider(new \Faker\Provider\en_US\PhoneNumber($faker));
     // $faker->addProvider(new \Faker\Provider\en_US\Company($faker));
     $faker->addProvider(new \Faker\Provider\Lorem($faker));
     $faker->addProvider(new \Faker\Provider\Internet($faker));
     /*
     				CREATE FAKE USERS
     */
     foreach (range(1, 2) as $index) {
         $user = User::create(['username' => $index == 1 ? env('ADMIN_USERNAME', 'tonetlds') : $faker->userName(), 'name' => $index == 1 ? env('ADMIN_NAME', 'Luciano') : $faker->firstName(), 'email' => $index == 1 ? env('ADMIN_EMAIL', '*****@*****.**') : $faker->email(), 'password' => $index == 1 ? Hash::make(env('ADMIN_PASSWORD', '1234')) : Hash::make('1234')]);
         echo "______________________________________________________________________________________";
         echo "\n";
         echo "User " . $index . ": #" . $user->id . " " . $user->name . "";
         echo "\n";
         /*
         					Clients for each user
         */
         foreach (range(1, 3) as $index_client) {
             $empresa = $faker->company();
             $client = new Client();
             $client->name = $empresa;
             $client->responsavel = $faker->firstName() . " " . $faker->lastName();
             $client->email = $faker->email();
             $client->email2 = $faker->email();
             $client->phones = $faker->phoneNumber() . ", " . $faker->phoneNumber();
             $client->company = $empresa;
             $client->address = $faker->streetAddress();
             $client->city = $faker->city();
             $client->cep = $faker->postcode();
             $client->obs = $faker->sentence($nbWords = 6, $variableNbWords = true);
             $slug = $client->slug;
             $client->slug = $slug;
             $client->owner_id = $user->id;
             $client->save();
             echo "Cliente " . $client->name;
             echo "\n";
             /* CONTACTS */
             foreach (range(1, 3) as $index) {
                 Contact::create(['name' => $faker->firstName() . " " . $faker->lastName(), 'email' => $faker->email(), 'address' => $faker->streetAddress(), 'company' => $faker->company(), 'client_id' => $client->id, 'owner_id' => $user->id]);
             }
             /*
             	PROJECTS
             */
             foreach (range(1, 3) as $index_project) {
                 $project = Project::create(['title' => $index . '-' . $faker->stateAbbr(), 'description' => $faker->company(), 'status' => '', 'date' => $faker->dateTimeBetween($startDate = '-1 years', $endDate = 'now'), 'client_id' => $client->id, 'owner_id' => $user->id]);
                 echo "Criado projeto " . $project->id . " para " . $client->name . " (user: "******")";
                 echo "\n";
                 /* DISCIPLINAS */
                 foreach (range(1, 3) as $index_discipline) {
                     $items = ['Estrutura Metálica', 'Concreto', 'Instalações de Ar Condicionado', 'Segurança'];
                     $disciplines = ProjectDiscipline::create(['title' => $items[$index_discipline - 1], 'description' => $faker->sentence($nbWords = 6), 'project_id' => $project->id, 'owner_id' => $user->id]);
                     echo "Disciplina " . $disciplines->title;
                     echo "\n";
                 }
                 /* ETAPAS */
                 foreach (range(1, 3) as $index_stage) {
                     $items = ['Geral', '1A', '1B', '2A'];
                     $projectstage = ProjectStage::create(['title' => $index_stage . ' ' . $items[$index_stage - 1], 'status' => 'Em andamento', 'description' => $faker->company(), 'project_id' => $project->id, 'owner_id' => $user->id]);
                     echo "Etapa " . $projectstage->title;
                     echo "\n";
                     /* CONSULTAS TÉCNICAS */
                     foreach (range(1, 3) as $index_consults) {
                         $tc_types = array(0, 1, 2);
                         $tc_type = $tc_types[array_rand($tc_types)];
                         $tc_rating = array(1, 2, 3);
                         $color = new Alfred();
                         $consult = TechnicalConsult::create(['title' => 'Consulta teste ' . $index_consults . ' Projeto ' . $project->id . ' Etapa ' . $projectstage->id, 'description' => $faker->company(), 'cliente_id' => $project->client->id, 'project_id' => $project->id, 'project_stage_id' => $projectstage->id, 'color' => $color->randomColor(), 'owner_id' => $user->id]);
                         echo "Consulta tecnica '" . $consult->title . "' com 3 emails";
                         echo "\n";
                         /* EMAILS */
                         $subjects = 'Consulta sobre ' . $faker->sentence($nbWords = 2);
                         $email_message = EmailMessage::create(['type' => 1, 'from' => $client->email, 'to' => '*****@*****.**', 'subject' => $subjects, 'body_text' => 'Texto do corpo do email', 'body_html' => '<strong>Teste</strong> de e-mail em <i>html</i> enviado para ' . $client->email . ' em ' . $consult->created_at . '.', 'headers' => '', 'consulta_tecnica_id' => $consult->id, 'email_message_id' => null, 'owner_id' => $user->id, 'status' => null, 'date' => $faker->dateTimeThisYear($max = 'now'), 'rating' => $tc_rating[array_rand($tc_rating)]]);
                         echo "E-mail enviado para <" . $email_message->to . ">";
                         echo "\n";
                         $email_message = EmailMessage::create(['type' => 2, 'from' => '*****@*****.**', 'to' => $client->email, 'subject' => 'RE: ' . $subjects, 'body_text' => 'Texto do corpo do segundo email', 'body_html' => '<strong>Título</strong><p>Segundo E-mail em html enviado para ' . $client->email . '.</p>', 'headers' => '', 'consulta_tecnica_id' => $consult->id, 'email_message_id' => $email_message->id, 'owner_id' => $user->id, 'status' => null, 'date' => $faker->dateTimeThisYear($max = 'now'), 'rating' => $tc_rating[array_rand($tc_rating)]]);
                         echo "E-mail enviado para <" . $email_message->to . ">";
                         echo "\n";
                         $email_message = EmailMessage::create(['type' => $tc_type, 'from' => '*****@*****.**', 'to' => $client->email, 'subject' => 'RE: ' . $subjects, 'body_text' => 'Texto do corpo do segundo email', 'body_html' => '<strong>Título</strong><p>Segundo E-mail em html enviado para ' . $client->email . '.</p>', 'headers' => '', 'consulta_tecnica_id' => $consult->id, 'email_message_id' => $email_message->id, 'owner_id' => $user->id, 'status' => null, 'date' => $faker->dateTimeThisYear($max = 'now'), 'rating' => $tc_rating[array_rand($tc_rating)]]);
                         echo "E-mail enviado para <" . $email_message->to . ">";
                         echo "\n";
                     }
                 }
             }
         }
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request, Validator $validator)
 {
     $data = $request->all();
     // dd($data);
     $data['technical_consult']['owner_id'] = $request->user()->id;
     $data['technical_consult']['color'] = (new Alfred())->randomColor();
     $data['email_message']['date'] = empty($data['email_message']['date']) ? date('Y-m-d') : $data['email_message']['date'];
     $data['email_message']['time'] = empty($data['email_message']['time']) ? date('H:i') : $data['email_message']['time'];
     // CRIA CONSULTA TÉCNICA
     if (isset($data['technical_consult_id']) && $data['technical_consult_id'] > 0) {
         $technical_consult = TechnicalConsult::find($data['technical_consult_id']);
     } else {
         $technical_consult = TechnicalConsult::create($data['technical_consult']);
     }
     if (!$technical_consult) {
         $this->sys_notifications[] = array('type' => 'danger', 'message' => 'Erro ao criar consulta técnica');
         $request->session()->flash('sys_notifications', $this->sys_notifications);
         return back()->withInput($request->all());
     }
     $email_data = $data['email_message'];
     $email_data['date'] = date('Y-m-d H:i:s', strtotime($email_data['date'] . ' ' . $email_data['time'] . ':00'));
     $contact = Contact::find($data['technical_consult']['contact_id']);
     $email_data['to'] = $contact->email;
     $email_data['toname'] = $contact->name;
     $email_data['from'] = $request->user()->email;
     $email_data['subject'] = $data['technical_consult']['title'];
     $email_data['consulta_tecnica_id'] = $technical_consult->id;
     $email_data['owner_id'] = $request->user()->id;
     $email_data['body_html'] = $data['technical_consult']['description'];
     $email_data['body_text'] = strip_tags($data['technical_consult']['description']);
     $email_data['email_message_id'] = $data['email_message_id'] && !empty($data['email_message_id']) ? $data['email_message_id'] : null;
     // CRIA EMAIL MESSAGE
     $email_message = EmailMessage::create($email_data);
     if (!$email_message) {
         $this->sys_notifications[] = array('type' => 'danger', 'message' => $validator->errors()->first());
         $request->session()->flash('sys_notifications', $this->sys_notifications);
         return back()->withInput($request->all());
     }
     // ATTACH FILES
     $files = $request->file('file');
     if ($files[0] != null) {
         $filesupload = (new FileEntryController())->upload($request, false, $email_message->id);
         if ($filesupload['uploaded'] > 0) {
             // $this->sys_notifications[] = array('type' => 'success', 'message' => $filesupload['uploaded'] . ' arquivos anexados');
         }
     }
     $anexos = array();
     if (!empty($filesupload['ids'])) {
         foreach ($filesupload['ids'] as $key => $fileid) {
             $entry = FileEntry::find($fileid);
             $entry->email_message_id = $email_message->id;
             $entry->save();
             $anexos[] = $entry;
         }
     }
     // SEND MAIL
     if ($email_data['type'] == 1) {
         Mail::send('emails.message', ['email_data' => $email_data], function ($message) use($email_data, $anexos, $request, $email_message, $technical_consult) {
             foreach ($anexos as $anexo) {
                 $message->attach(storage_path('app/' . $request->user()->id . '/' . $email_message->id . '/' . $anexo->original_filename));
             }
             $message->from($email_data['from'], 'Consultas Técnicas');
             $message->to($email_data['to'], $email_data['toname'])->subject('Consulta Técnica CT0' . $technical_consult->id);
             $message->bcc('*****@*****.**', $email_data['toname'])->subject('Consulta Técnica CT0' . $technical_consult->id);
         });
     }
     $this->sys_notifications[] = array('type' => 'success', 'message' => 'Nova consulta técnica registrada com sucesso!');
     $request->session()->flash('sys_notifications', $this->sys_notifications);
     return redirect('obras/');
     return back()->withInput($request->all());
 }
 public function anexos(Request $request, $technical_consult_id = null, $email_message_id = null)
 {
     $email = EmailMessage::find($email_message_id);
     if ($email) {
         return view('arquivos.table')->with('files', $email->attachments);
     } else {
         return null;
     }
 }
 /**
  * Store a newly created resource in storage.
  *
  * @param  \Illuminate\Http\Request  $request
  * @return \Illuminate\Http\Response
  */
 public function store(Request $request, Validator $validator)
 {
     $data = $request->all();
     if (!isset($data['email_message']['project_id'])) {
         return 'Informe a obra';
     }
     $obra = Obra::find(@$data['email_message']['project_id']);
     $data['technical_consult']['cod'] = $obra->consultas_tecnicas->max('cod') + 1;
     switch (@$data['email_message']['type']) {
         case 0:
             // CRIA ACONTECIMENTO
             $technical_consult = ConsultaTecnica::create($data['technical_consult']);
             // CRIA EMAIL MESSAGE
             $email_message = new EmailMessage();
             break;
         case 2:
             // REGISTRAR RETORNO
             $technical_consult = ConsultaTecnica::find($data['technical_consult']['id']);
             // CRIA EMAIL MESSAGE
             $email_message = new EmailMessage();
             $email_message->email_message_id = $data['email_message']['email_message_id'];
             break;
         default:
             // CRIA CONSULTA TÉCNICA
             $technical_consult = new ConsultaTecnica();
             $technical_consult->owner_id = $request->user()->id;
             $technical_consult->color = (new Alfred())->randomColor();
             $technical_consult->project_id = @$data['technical_consult']['project_id'];
             $technical_consult->project_stage_id = @$data['technical_consult']['project_stage_id'];
             $technical_consult->project_discipline_id = @$data['technical_consult']['project_discipline_id'];
             $technical_consult->title = @$data['technical_consult']['title'];
             $technical_consult->cod = $data['technical_consult']['cod'];
             $technical_consult->save();
             // CRIA EMAIL MESSAGE
             $email_message = new EmailMessage();
             break;
     }
     if (isset($data['email_message']['date'])) {
         $date = str_replace('/', '-', $data['email_message']['date']);
     } else {
         $date = date('Y-m-d');
     }
     $data['email_message']['date'] = empty($data['email_message']['date']) ? date('Y-m-d') : date('Y-m-d', strtotime($date));
     $data['email_message']['time'] = empty($data['email_message']['time']) ? date('H:i') : $data['email_message']['time'];
     $email_message->date = date('Y-m-d H:i:s', strtotime($data['email_message']['date'] . ' ' . $data['email_message']['time']));
     // DADOS PARA O CORPO DO EMAIL
     $email_data = $data['email_message'];
     $email_data['obra'] = $technical_consult->project->title;
     $email_data['subject'] = $technical_consult->title;
     $email_data['consulta_tecnica_id'] = $technical_consult->formattedCod('CT #');
     $email_data['etapa'] = $technical_consult->projectstage ? $technical_consult->projectstage->title : '';
     $email_data['disciplina'] = $technical_consult->projectdiscipline ? $technical_consult->projectdiscipline->title : '';
     $email_data['body_html'] = $email_data['description'];
     // dd($email_data);
     $contatos = array();
     $email_data_to['contato_emails'] = array();
     $email_message->type = null !== @$email_data['type'] ? $email_data['type'] : 1;
     if (null == @$email_data['to']) {
         $email_data['to'] = EmailMessage::find($email_message->email_message_id)->to;
         $email_data['to'] = explode(',', @$email_data['to']);
     }
     foreach ($email_data['to'] as $contato_id) {
         $contato = Contato::find($contato_id);
         if (null !== $contato) {
             $contatos[] = $contato;
             $email_data_to['contato_emails'][] = $contato->email;
         }
     }
     $email_message->to = implode(',', $email_data_to['contato_emails']);
     $email_message->from = $request->user()->email;
     $email_message->subject = $email_data['subject'];
     $email_message->consulta_tecnica_id = $technical_consult->id;
     $email_message->owner_id = $request->user()->id;
     $email_message->body_html = $email_data['description'];
     $email_message->rating = @$email_data['rating'];
     $email_message->private = null === @$email_data['private'] ? false : true;
     // SALVA EMAIL MESSAGE
     $email_message->save();
     if (!$technical_consult) {
         $this->sys_notifications[] = array('type' => 'danger', 'message' => 'Erro ao adicionar consulta técnica');
         $request->session()->flash('sys_notifications', $this->sys_notifications);
         return back()->withInput($request->all());
     }
     if (!$email_message) {
         $this->sys_notifications[] = array('type' => 'danger', 'message' => $validator->errors()->first());
         $request->session()->flash('sys_notifications', $this->sys_notifications);
         return back()->withInput($request->all());
     }
     // ENVIAR EMAIL
     if ($email_message->type == 1 && "on" == @$data['sendnow']) {
         // ATTACH FILES
         $files = $request->file('file');
         if ($files[0] != null) {
             $filesupload = (new FileEntryController())->upload($request, false, $email_message->id);
             if ($filesupload['uploaded'] > 0) {
                 // $this->sys_notifications[] = array('type' => 'success', 'message' => $filesupload['uploaded'] . ' arquivos anexados');
             }
         }
         $anexos = array();
         if (!empty($filesupload['ids'])) {
             foreach ($filesupload['ids'] as $key => $fileid) {
                 $entry = FileEntry::find($fileid);
                 $entry->email_message_id = $email_message->id;
                 $entry->save();
                 $anexos[] = $entry;
             }
         }
         // SEND MAIL TO ME
         if (null !== @$data['sendtome']) {
             $email_data['bcc'] = $request->user()->email;
         }
         // PROCESS THE JOB
         $this->dispatch(new SendEmail($email_data, $anexos, $request, $email_message, $technical_consult, $contatos));
         // return view('emails.message', compact('email_data', 'anexos', 'request', 'email_message', 'technical_consult', 'contatos'));
         $this->sys_notifications[] = array('type' => 'success', 'message' => 'E-mail enviado!');
     }
     $this->sys_notifications[] = array('type' => 'success', 'message' => 'Consulta Técnica registrada com sucesso!');
     $request->session()->flash('sys_notifications', $this->sys_notifications);
     return redirect('obras/' . $technical_consult->project_id);
 }