<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

class OnlineQuotes extends SiteController {
  function __construct () {
    parent::__construct();
    $this->data['page'] = 'online-quotes';
    $this->data['metatags'] = $this->getMetatags($this->data['page']);
  }

  public function index () {
    $this->load->model('internBannerModel');
    $this->data['banner'] = $this->internBannerModel->getRowWhere(['slug' => 'online-quotes']);

    $this->load->model('unityModel');
    $this->data['unities'] = $this->unityModel->getAll();

    $this->load->view('online-quotes', $this->data);
  }

  public function save () {
    try {
      $this->form_validation->set_rules('cnpj', 'CNPJ', 'trim');
      $this->form_validation->set_rules('company_name', 'Nome da empresa', 'trim|required');
      $this->form_validation->set_rules('email', 'E-mail', 'trim|required');
      $this->form_validation->set_rules('phone', 'Telefone', 'trim|required');
      $this->form_validation->set_rules('origin_city', 'Cidade de origem', 'trim|required');
      $this->form_validation->set_rules('destination_city', 'Cidade de destino', 'trim|required');
      $this->form_validation->set_rules('weight', 'Peso (KG)', 'trim|required');
      $this->form_validation->set_rules('volume', 'Volume (M³)', 'trim|required');
      $this->form_validation->set_rules('merchandise_value', 'Valor da mercadoria', 'trim|required');
      $this->form_validation->set_rules('message', 'Mensagem', 'trim');

      if ($this->form_validation->run() == false) {
        return $this->response(['success' => false, 'error' => strip_tags(validation_errors())]);
      }

      $email = $this->input->post('email');

      if (!validEmail($email)) {
        return $this->response(['success' => false, 'error' => 'Digite um e-mail válido']);
      }

      $data = [
        'cnpj' => antiInjection($this->input->post('cnpj')),
        'company_name' => antiInjection($this->input->post('company_name')),
        'email' => antiInjection($this->input->post('email')),
        'phone' => antiInjection($this->input->post('phone')),
        'origin_city' => antiInjection($this->input->post('origin_city')),
        'destination_city' => antiInjection($this->input->post('destination_city')),
        'weight' => antiInjection($this->input->post('weight')),
        'volume' => antiInjection($this->input->post('volume')),
        'merchandise_value' => antiInjection($this->input->post('merchandise_value')),
        'message' => antiInjection($this->input->post('message')),
      ];
      
      $this->load->model('OnlineQuoteModel');
      $createdId = $this->OnlineQuoteModel->create($data);

      if (!$createdId) {
        return $this->response(['success' => false, 'error' => 'Não foi possível enviar a cotação, tente novamente']);
      }

      $emailResponse = $this->sendEmail($data);

      return $this->response(['success' => true, 'email' => $emailResponse['success'], 'error' => $emailResponse['error']]);
    } catch (\Throwable $th) {
      return $this->response(['success' => false, 'error' => 'Erro ao enviar cotação, se continuar entre em contato']);
    }
  }

  public function sendEmail (array $message) {
    $PHPMailerResponse = $this->PHPMailerSend($message);

    if (!$PHPMailerResponse['success']) {
      return ['success' => false, 'error' => $PHPMailerResponse['error']];
    }

    return ['success' => true, 'error' => null];
  }

  private function PHPMailerSend (array $message) {
    require APPPATH . 'plugins/PHPMailer/src/Exception.php';
    require APPPATH . 'plugins/PHPMailer/src/PHPMailer.php';
    require APPPATH . 'plugins/PHPMailer/src/SMTP.php';
    
    $this->load->model('companyInformationModel');
    $companyInformations = $this->companyInformationModel->getLast();

    try {
      $mailer = new PHPMailer(true);
      $mailer->setFrom($message['email'], $message['company_name']);
      $mailer->addAddress($companyInformations->email, $companyInformations->fantasy_name);
      $mailer->isHTML(true);

      $mailer->CharSet = 'UTF-8';
      $mailer->Subject = 'Nova cotação online';
      $mailer->Body = $this->getEmailHTML($message);

      $mailer->send();
      return ['success' => true];
    } catch (Exception $error) {
      return ['success' => false, 'error' => $mailer->ErrorInfo];
    }
  }

  private function getEmailHTML (array $message) {
    $message = (object) $message;
    $body = "
      <section>
        <div style=\"width: 100%; max-width: 448px\">
          <h1 style=\"color: #343434; font-size: 20px; font-weight: 600\">Nova mensagem no site</h1>     
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 16px\">
            CNPJ: $message->cnpj
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 16px\">
            Nome da empresa: $message->company_name
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Email: $message->email
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Telefone: $message->phone
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Cidade de origem: $message->origin_city
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Cidade de destino: $message->destination_city
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Peso (KG): $message->weight
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Volume (M³): $message->volume
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Valor da mercadoria: $message->merchandise_value
          </p>
          <p style=\"color: #5c5c5c; font-size: 14px; margin-top: 8px\">
            Mensagem adicional: $message->message
          </p>
        </div>
      </section>
    ";

    return $body;
  }
}