<!-- 181022 - correo -->
<?php    
  include 'phpMailer/class.smtp.php';
  require 'phpMailer/class.phpmailer.php';
  include('include/functions.php');
  require_once __DIR__ . '/pdf/librerias/vendor/autoload.php';   

  try{
    $mpdf = new \Mpdf\Mpdf([
      'default_font_size' => 8.5,
	    'default_font' => 'sans-serif',
      'line-height' => '1.15',
      'format' => 'letter'
    ]);    

    $stylesheet = file_get_contents('pdf/estilo.css');
    $mpdf->WriteHTML($stylesheet,\Mpdf\HTMLParserMode::HEADER_CSS);
    


    if($_GET['tipo_cotizador'] == 'unidad_completa') { 
      $titulo_main = "Cotización Unidad Completa";
      $redireccion_gracias = "https://expressmg.com.mx/gracias-unidad-completa";
      $cliente = "";
      
      $html = '    
      
        <h3>Origen</h3>
        <table id="table1" class="table-pdf" width="50%">
          <thead>
            <th width="25%">Dato</th>
            <th width="75%">Información</th>
          </thead>
          <tbody>
            <tr>
              <td>Código postal</td>
              <td>'. $_GET['cp_origen'] .'</td>
            </tr>
            <tr>
              <td>País</td>
              <td>'. $_GET['pais_origen'] .'</td>
            </tr>
            <tr>
              <td>Estado</td>
              <td>'. $_GET['estado_origen'] .'</td>
            </tr>
            <tr>
              <td>Ciudad</td>
              <td>'. $_GET['ciudad_origen'] .'</td>
            </tr>
            <tr>
              <td>Colonia</td>
              <td>'. $_GET['colonia_origen'] .'</td>
            </tr>
            <tr>
              <td>Calle</td>
              <td>'. $_GET['calle_origen'] .'</td>
            </tr>
            <tr>
              <td>Número exterior</td>
              <td>'. $_GET['num_exterior_origen'] .'</td>
            </tr>
            <tr>
              <td>Referencias</td>
              <td>'. $_GET['referencias_origen'] .'</td>
            </tr>
            <tr>
              <td>Entre calles</td>
              <td>'. $_GET['entre_calles_origen'] .'</td>
            </tr>
          </tbody>
        </table>
        <br>

        <h3>Destino</h3>
        <table id="table1" class="table-pdf" width="50%">
          <thead>
            <th width="25%">Dato</th>
            <th width="75%">Información</th>
          </thead>
          <tbody>
            <tr>
              <td>Código postal</td>
              <td>'. $_GET['cp_destino'] .'</td>
            </tr>
            <tr>
              <td>País</td>
              <td>'. $_GET['pais_destino'] .'</td>
            </tr>
            <tr>
              <td>Estado</td>
              <td>'. $_GET['estado_destino'] .'</td>
            </tr>
            <tr>
              <td>Ciudad</td>
              <td>'. $_GET['ciudad_destino'] .'</td>
            </tr>
            <tr>
              <td>Colonia</td>
              <td>'. $_GET['colonia_destino'] .'</td>
            </tr>
            <tr>
              <td>Calle</td>
              <td>'. $_GET['calle_destino'] .'</td>
            </tr>
            <tr>
              <td>Número exterior</td>
              <td>'. $_GET['num_exterior_destino'] .'</td>
            </tr>
            <tr>
              <td>Referencias</td>
              <td>'. $_GET['referencias_destino'] .'</td>
            </tr>
            <tr>
              <td>Entre calles</td>
              <td>'. $_GET['entre_calles_destino'] .'</td>
            </tr>
          </tbody>
        </table>
        <br>


        <h3>Datos adicionales</h3>
        <table id="table2" class="table-pdf" width="50%">
          <thead>
            <th width="50%">Dato</th>
            <th width="50%">Información</th>
          </thead>
          <tbody>
            <tr>
              <td>Tipo de unidad:</td>
              <td>'. $_GET['tipo_unidad'] .'</td>
            </tr>
            <tr>
              <td>Peso:</td>
              <td>'. $_GET['peso'] .' Kg.</td>
            </tr>
            <tr>
              <td>Tipo de mercancía:</td>
              <td>'. $_GET['tipo_mercancia'] .'</td>
            </tr>
            <tr>
              <td>Observaciones:</td>
              <td>'. $_GET['observaciones'] .'</td>
            </tr>
          </tbody>
        </table>';



    } else {
      $titulo_main = "Cotización Servicios Especializados";
      $redireccion_gracias = "https://expressmg.com.mx/gracias-por-contactarnos-paqueteria";
      $cliente = $_GET['empresa'];
      $origen = $_GET['c1'] == 1 ? 'León' : 'Guadalajara';
      $destino = ver_destino($_GET['c2']);

      // Calculos
      $c15 = (float) get_c15($_GET['c1'], $_GET['c2']);
      $c16 = (float) get_c16($_GET['c1'], $_GET['c2']);
      $minimo = get_minimo($_GET['c1'], $_GET['c2']);
      $d15 = (float) round( get_d15($_GET['c5'], $_GET['c6'], $_GET['c7'], $_GET['c8'], $c15), 2 );
      $d16 = (float) round( get_d16($_GET['c10'], $_GET['c11'], $c16), 2);
      $f5 = get_f5($d15, $d16);
      $f9 = get_f9($f5, $_GET['f7']);
      $f9 = $f9 < $minimo ? $minimo : $f9;
      $costo_mercancia = isset($_GET['costo_mercancia']) ? $_GET['costo_mercancia'] : 1000;
      $seguro = isset($_GET['total_seguro']) ? $_GET['total_seguro'] : 10;
      $f10 = $f9 + $seguro;
      $iva_simple = $f10 * .16;
      $iva = $f10 * 1.16;
      $isr = $retencion == 1 ? $iva * .04 : 0;
      $total_final = $iva - $isr;

      

      switch($_GET['tipo_servicio']) {
        case 1: $tipo_servicio_web = 'Paquetería'; break;
        case 2: $tipo_servicio_web = 'Mudanza'; break;
        case 3: $tipo_servicio_web = 'Mercancía Frágil'; break;
      }

      $html = '    
      <table id="table1" class="table-pdf" width="50%">
      <thead>
        <th width="25%">Dato</th>
        <th width="75%">Información</th>
      </thead>
      <tbody>
        <tr>
          <td>Origen</td>
          <td>'.$origen.'</td>
        </tr>
        <tr>
          <td>Destino</td>
          <td>'.$destino.'</td>
        </tr>
        <tr>
          <td>Tipo de servicio</td>
          <td>'.$tipo_servicio_web.'</td>
        </tr>
        <tr>
          <td>Largo</td>
          <td>'.$_GET['c8'].$_GET['c5'].'</td>
        </tr>
        <tr>
          <td>Alto</td>
          <td>'.$_GET['c6'].$_GET['c5'].'</td>
        </tr>
        <tr>
          <td>Ancho</td>
          <td>'.$_GET['c7'].$_GET['c5'].'</td>
        </tr>
        <tr>
          <td>Cantidad</td>
          <td>'.$_GET['f7'].'</td>
        </tr>
        <tr>
          <td>Peso</td>
          <td>'.$_GET['c11'].$_GET['c10'].'</td>
        </tr>
        <tr>
          <td>Costo de mercancía</td>
          <td>$'.$costo_mercancia.'</td>
        </tr>
        
      </tbody>
    </table>
  
  
    <table class="total" width="100%">
      <tbody>
        <tr>
          <td width="5%">Subtotal</td>
          <td width="15%">$'.$f9.'</td>
        </tr>
        <tr>
          <td>Total seguro</td>
          <td>$'.$seguro.'</td>
        </tr>
        <tr>
          <td>IVA</td>
          <td>$'.$f10.'</td>
        </tr>
        <tr>
          <td>Retención 4%</td>
          <td>-$'. round($isr, 2).'</td>
        </tr>
        <tr>
          <td>Total</td>
          <td>$'.round($total_final, 2).'</td>
        </tr>
      </tbody>
    </table>';

    }



    $encabezado = '
      <img src="img/logo-express-mg.png">
      <br>
      <h2>'.$titulo_main.'</h2>

      <p>Ave.Transportistas #414, Fracción de los Gomez</p>
      <p>León, Guanajuato 37140</p>
      <p>Sitio web: <a href="https://expressmg.com.mx">https://expressmg.com.mx</a></p>
      <p>Teléfono: <a href="tel:4774704000">477 470 4000</a></p>

      <table id="table0" class="table-pdf">
        <thead>
          <th width="50%">Cliente</th>
          <th width="50%">Correo</th>
        </thead>
        <tr>
          <td>Cliente: '. $cliente .'</td>
          <td>Correo: '. $_GET['correo'] .'</td>
        </tr>
      </table>
      
      ';
      
     
    $terminos = '
        <div class="terminos">
        <br>
            <h3>Términos y condiciones del servicio</h3>
            
            <strong>General:</strong>
                
            <ol>
                <li>Toda cotización está sujeta a medición y peso</li>
                <li>Cualquier alteración a nuestras cotizaciones será motivo de invalidación inmediata y puesto a disposición de las autoridades.</li>
                <li>Cualquier dato incorrecto introducido en las cotizaciones tendrá que ser ajustado.</li>
                <li>Todo embalaje es responsabilidad directa del cliente.</li>
                <li>Recomendable contratar seguro de mercancía, el cual esta sujeto a decisión del cliente.</li>
            </ol>
            
            
            <strong>PTL:</strong>
            <ol>
                <li>Esta cotización tiene validez solo 15 dias a partir de su fecha de expedición.</li>
                <li>Monitoreo 24/7 incluido.</li>
                <li>Toda cotización esta sujeta a medición y peso.</li>
                <li>Se recomienda asegurar su mercancía por solo el 1% del Valor declarado.</li>
                <li>Con 3 horas de carga y 3 horas para descarga.</li>
                <li>Penalización de $140.00 pesos MXN mas IVA. Por hora adicional a las ya mencionadas.</li>
                <li>Estadías por día, 3,200.00 pesos MX.</li>
            </ol>
            
            
            <strong>LTL</strong>
            
            <ol>
                <li>Sujeto a peso y medición.</li>
                <li>Se recomienda asegurar su mercancía por solo el 1% del Valor declarado.</li>
                <li>Express MG no se hace responsable por mercancia mal empaquetada y/o sin seguro</li>
            </ol>
            
            
            <strong>FTL</strong>
            
            <ol>
                <li>Esta cotización tiene validez solo 15 dias a partir de su fecha de expedición.</li>
                <li>Con 3 horas de carga y 3 horas para descarga.</li>
                <li>Penalización de $140.00 pesos MXN mas IVA. Por hora adicional a las ya mencionadas.</li>
                <li>Toda cotización esta sujeta a medición y peso.</li>
                <li>Se recomienda asegurar su mercancía por solo el 1% del Valor declarado.</li>
                <li>28 Toneladas Máximo.</li>
                <li>Monitoreo 24/7 incluido.</li>
                <li>100 metros cubicos/ 53 pies.</li>
                <li>Cuenta espejo incluida.</li>
                <li>Estadías por día, 3,200.00 pesos MXN.</li>
            </ol>
        </div>
    ';
    
    // $html_estilo = mb_convert_encoding($html_estilo, 'UTF-8', 'UTF-8');
    $html = mb_convert_encoding($html, 'UTF-8', 'UTF-8');    
    

    //$mpdf->AddPage();
    $mpdf->WriteHTML($encabezado . $html . $terminos);

    if(!file_exists("cotizaciones/")){
      mkdir("cotizaciones/", 0700);
    }
    
    
    $ruta = '/home/expressmgcom/public_html/sistema/cotizador/v4/cotizaciones/';
    $prefijo = $_GET['tipo_cotizador'] == 'unidad_completa' ? 'unidad-completa' : 'paqueteria';
    $archivo = $ruta. 'cotizacion-'.$prefijo.'-'.date('dmY-His').'.pdf';
    $mpdf->Output($archivo, 'F');
    ob_clean(); 
    flush(); 

    // echo "{\"mensaje\":\"correcto\",\"archivo\":\"Archivo - fff - fff.pdf\"}";
    // echo $archivo;
    //$mpdf->Output();
    
  }catch(Exception $ex){   
    // echo "{\"mensaje\":\"error\",\"detalles\":\"".$ex->getMessage()."\"}";
  }
  
  


    // Enviar correo
    $correo = isset($_GET['correo']) ? $_GET['correo'] : 'pruebas@expressmg.com.mx';
    /* $correo = "pruebas@expressmg.com.mx"; */
    $asunto = "Cotización servicios Express MG Web";
    
    $mail = new PHPMailer();
		// $mail->IsSMTP();
		$mail->SMTPDebug  = 0;
		$mail->SMTPAuth   = true;
		$mail->Debugoutput = 'html';
		$mail->SMTPSecure = "tls";
		$mail->Port       = 465;
		$mail->Host       = "mail.expressmg.com.mx";
		$mail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => false,
				'verify_peer_name' => false,
				'allow_self_signed' => true
		));
		$mail->Username = "pruebas@expressmg.com.mx";
		$mail->Password = "expressmg2022";
		$mail->setFrom("pruebas@expressmg.com.mx", utf8_decode($titulo_main));
		$mail->IsHTML(true);

    if($_GET['tipo_cotizador'] == 'unidad_completa') {
      $mail->addAddress('pruebas@expressmg.com.mx'); // Correo cotizaciones
       $mail->addAddress('cotizaciones@expressmg.com.mx'); // Correo cotizaciones
    }else {
      $mail->addAddress('pruebas@expressmg.com.mx'); // Correo cotizaciones
      $mail->addAddress($correo);
      $mail->addAddress('paqueteria@expressmg.com.mx');
    }

		$mail->AddAttachment($archivo);
		$mail->Subject = utf8_decode($asunto);
		$mail->Body = utf8_decode("Adjunto a este correo encontrarás la cotización solicitada.");

			if (!$mail->send()) {
				echo 'Hubo un problema al enviar la cotización por correo, por favor intente nuevamente. <br />';
				echo 'Error: ' . $mail->ErrorInfo;
				return false;
			}else {
        include('gracias-1.html');
        // header("Location: " .$redireccion_gracias);
			}
		
?>