<?php
set_include_path("../");
include_once("server/class/BackOfficeManager.php");
include_once("server/class/User.php");

use PHPMailer\PHPMailer\PHPMailer;

//@session_start();

header("Content-Type: text/html;charset=utf-8");

/*
$to = filter_input(INPUT_GET, 'to', FILTER_VALIDATE_INT);
$lapse = filter_input(INPUT_GET, 'lapse', FILTER_VALIDATE_INT);
*/
$to = getLastSaturdaysTimestamp();
$lapse = 7;

$u = new User();
//$usersWithEmail = $u->getUsersWithEmailPrueba();
$usersWithEmail = $u->getUsersWithEmail();

if (is_array($usersWithEmail) && count($usersWithEmail)) {

    for ($i = 0; $i < count($usersWithEmail); $i++) {

        $u->setUserId($usersWithEmail[$i]['id_usuario']);
        //$userEmailToSend = $u->getEmailPrueba(); 
        $userEmailToSend = $u->getEmail();
        $userName = ($u->getUserName()) ? $u->getUserName() : '';
        //echo $email;

        $borr = new BackofficeManager($u);
        $borr->setRange($to, $lapse);

        $results = $borr->getKmFlota();
        $fd0 = date("Y-m-d", $to);
        $fechaDesde = strtotime('- 7 day', $to);
        $fechaDesde = date('d-m-Y', $fechaDesde);

        $fechaHasta = gmdate("d-m-Y", $to);
        $reporte_rango_fechas = 'Desde el ' . $fechaDesde . ' al ' . $fechaHasta;

        $km_flota = $results['km']['totKm'];

        $dKm = $results['km']['dKm'];
        if ($dKm < 0) {
            $km_flota_porcentaje = '&darr; ' . abs($dKm) . '%';
            $km_flota_porcentaje_color = '#dc3338'; //rojo    
        } else if ($dKm > 0) {
            $km_flota_porcentaje = '&uarr; ' . $dKm . '%';
            $km_flota_porcentaje_color = '#1b9a18'; //verde
        } else {
            $km_flota_porcentaje = '';
            $km_flota_porcentaje_color = '';
        }

        //$excesos = (is_null($results['overspeedCount'])) ? '<p style="margin: 0; font-size: 16px; text-align: center; mso-line-height-alt: 19.2px; margin-top: 5px">No tiene activadas las alertas de excesos de velocidad.</p>' : $results['overspeedCount']['totals']['count'];
        $excesos = (is_null($results['overspeedCount'])) ? '<p style="margin: 0; font-size: 16px; text-align: center; mso-line-height-alt: 19.2px; margin-top: 5px">No tiene activadas las alertas de excesos de velocidad.</p>' : '<p style="margin: 0; font-size: 16px; text-align: center; mso-line-height-alt: 19.2px;"><span style="font-size:42px;"><strong>' . $results['overspeedCount']['totals']['count'] . '</strong></span></p>';
        $excesos_title = (is_null($results['overspeedCount'])) ? '' : 'Excesos de veolcidad';
        $vel_max = (is_null($results['overspeedCount'])) ? '' : '<p style="margin: 0; font-size: 16px; text-align: center; mso-line-height-alt: 19.2px;"><span style="font-size:42px;"><strong>' . $results['overspeedCount']['totals']['maxSpeed'] . ' <span style="font-size:30px;">Km/h</span></strong></span></p>';
        $vel_max_unit_matricula = (is_null($results['overspeedCount']['totals']['maxSpeedUnitMatricula'])) ? '' : '<br> (' . $results['overspeedCount']['totals']['maxSpeedUnitMatricula'] . ')';
        //$vel_max_unit = (is_null($results['overspeedCount'])) ? '<p style="margin: 0; font-size: 16px; text-align: center; mso-line-height-alt: 19.2px; margin-top: 5px">No hay registros</p>' : $results['overspeedCount']['totals']['maxSpeedUnit'] . $vel_max_unit_matricula;
        $vel_max_unit = (is_null($results['overspeedCount'])) ? '' : $results['overspeedCount']['totals']['maxSpeedUnit'] . $vel_max_unit_matricula;
        $vel_max_title = (is_null($results['overspeedCount'])) ? '' : 'Velocidad m&aacute;xima registrada';
        $vel_max_unit_date = '';

        $total_viajes = $km_flota;
        $porcentaje_viajes = $dKm;
        $promedio_viajes_diarios = $results['km']['avgKm'];

        $vehiculo_mas_viajes = $results['km']['maxKmUnit'];
        $vehiculo_mas_viajes_matricula = ($results['km']['maxKmUnitMatricula']) ? ' (' . $results['km']['maxKmUnitMatricula'] . ')' : $results['km']['maxKmUnitMatricula'];
        $vehiculo_mas_viajes_cantidad = $results['km']['maxKm'];
        $vehiculo_menos_viajes = $results['km']['minKmUnit'];
        $vehiculo_menos_viajes_matricula = ($results['km']['minKmUnitMatricula']) ? ' (' . $results['km']['minKmUnitMatricula'] . ')' : $results['km']['minKmUnitMatricula'];
        $vehiculo_menos_viajes_cantidad = $results['km']['minKm'];

        if ($dKm < 0) {
            $resumenPorcent = 'un ' . abs($porcentaje_viajes) . '% menos que la semana pasada,';
        } else if ($dKm > 0) {
            $resumenPorcent = 'un ' . $porcentaje_viajes . '% m&aacute;s que la semana pasada,';
        } else {
            $resumenPorcent = '';
        }

        $totUnits = count($results['details']);

        if ($km_flota > 0 && $totUnits > 0) {
            $promedio_km_vehiculos = $km_flota / $totUnits;
            $texto_promedio = ($totUnits == 1) ? '' : 'El promedio de kil&oacute;metros recorrido por cada veh&iacute;culo en este per&iacute;odo fue de ' . round($promedio_km_vehiculos, 0) . ' Km.<br>';
        } else {
            $texto_promedio = '';
        }

        $resumen = 'Esta semana tu flota acumul&oacute; ' . $total_viajes . ' Km, ' . $resumenPorcent . ' realizando en promedio ' . $promedio_viajes_diarios . ' Km diarios. <br><br>';
        $resumen .= ($totUnits == 1) ? '' : 'El veh&iacute;culo que m&aacute;s kil&oacute;metros recorri&oacute; es "' . $vehiculo_mas_viajes . '" ' . $vehiculo_mas_viajes_matricula . ', con ' . $vehiculo_mas_viajes_cantidad . ' Km y el que menos kil&oacute;metros recorri&oacute; es 
"' . $vehiculo_menos_viajes . '"' . $vehiculo_menos_viajes_matricula . ', con ' . $vehiculo_menos_viajes_cantidad . ' Km.<br><br>' . $texto_promedio;


        $km_recorrido_container = '';


        foreach ($results['details'] as $unit) {
            $kmr_unit = $unit['machineName'];
            $kmr_unit_matricula = ($unit['machineMatricula']) ? ' (' . $unit['machineMatricula'] . ')' : $unit['machineMatricula'];
            $kmr_km = $unit['recorrido'];
            $kmr_porcentaje = $unit['kmPct'];

            $km_recorrido_container .= '
        <tr>
            <td class="column column-1" width="70%"
                style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-left: 10px; padding-right: 10px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                <table class="text_block block-1" width="100%" border="0"
                    cellpadding="10" cellspacing="0" role="presentation"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                    <tr>
                        <td class="pad">
                            <div style="font-family: sans-serif">
                                <div class
                                    style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                    <p dir="ltr"
                                        style="margin: 0; font-size: 12px; text-align: left; mso-line-height-alt: 14.399999999999999px;">
                                        <span style="font-size:14px;">' . $kmr_unit . $kmr_unit_matricula . '</span>
                                    </p>
                                </div>
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
            <td class="column column-2" width="30%"
                style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                <table class="text_block block-1" width="100%" border="0"
                    cellpadding="10" cellspacing="0" role="presentation"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                    <tr>
                        <td class="pad">
                            <div style="font-family: sans-serif">
                                <div class
                                    style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                    <p dir="ltr"
                                        style="margin: 0; font-size: 12px; text-align: right; mso-line-height-alt: 14.399999999999999px;">
                                        <strong><span
                                                style="font-size:14px;">' . $kmr_km . ' Km</span></strong>
                                    </p>
                                </div>
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
        <tr>
            <td class="column column-12" colspan="2" width="100%" style="background-color: #ffffff; padding: 0px 10px 15px 20px;">
                <table class="text_block block-1" width="100%" border="0" cellpadding="0" cellspacing="0" role="presentation" style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                    <tbody>    
                        <tr>
                            <td width="100%" height="5px" style="background-color: #bebebe; line-height:5px;">
                                <table class="text_block block-1" width="' . $kmr_porcentaje . '%" border="0" cellpadding="0" cellspacing="0" role="presentation" style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                                    <tbody>    
                                        <tr>
                                            <td height="5px" style="background-color: #dc3338; line-height:5px;"></td>
                                        </tr>
                                    </tbody>    
                                </table>
                            </td>
                        </tr>
                    </tbody>    
                </table>
            </td>
        </tr>
    ';
        }

        $overspeed_container = '';
        $maxspeed_container = '';

        if (!is_null($results['overspeedCount'])) {

            foreach ($results['overspeedCount']['details'] as $overSpd) {
                //for ($i = 0; $i < $totUnits; $i++) {
                $ovrspd_unit = $overSpd['machineName']; // $results['details'][$i]['machineName'];
                $ovrspd_unit_matricula = ($overSpd['machineMatricula']) ? ' (' . $overSpd['machineMatricula'] . ')' : '';
                $ovrspd_count = $overSpd['count']; //$results['details'][$i]['recorrido'];

                $maxSpeed = $overSpd['max'];
                //$kmr_porcentaje = $overSpd['kmPct']; // $results['details'][$i]['kmPct'];
                //echo $results['details']['1265']['machineName'];

                $overspeed_container .= '
            <tr>
                <td class="column column-1" width="70%"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-left: 10px; padding-right: 10px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                    <table class="text_block block-1" width="100%" border="0"
                        cellpadding="10" cellspacing="0" role="presentation"
                        style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                        <tr>
                            <td class="pad">
                                <div style="font-family: sans-serif">
                                    <div class
                                        style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                        <p dir="ltr"
                                            style="margin: 0; font-size: 12px; text-align: left; mso-line-height-alt: 14.399999999999999px;">
                                            <span style="font-size:14px;">' . $ovrspd_unit . $ovrspd_unit_matricula . '</span>
                                        </p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </td>
                <td class="column column-2" width="30%"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                    <table class="text_block block-1" width="100%" border="0"
                        cellpadding="10" cellspacing="0" role="presentation"
                        style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                        <tr>
                            <td class="pad">
                                <div style="font-family: sans-serif">
                                    <div class
                                        style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                        <p dir="ltr"
                                            style="margin: 0; font-size: 12px; text-align: right; mso-line-height-alt: 14.399999999999999px;">
                                            <strong><span
                                                    style="font-size:14px;">' . $ovrspd_count . '</span></strong>
                                        </p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        ';

                $maxspeed_container .= '
            <tr>
                <td class="column column-1" width="70%"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-left: 10px; padding-right: 10px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                    <table class="text_block block-1" width="100%" border="0"
                        cellpadding="10" cellspacing="0" role="presentation"
                        style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                        <tr>
                            <td class="pad">
                                <div style="font-family: sans-serif">
                                    <div class
                                        style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                        <p dir="ltr"
                                            style="margin: 0; font-size: 12px; text-align: left; mso-line-height-alt: 14.399999999999999px;">
                                            <span style="font-size:14px;">' . $ovrspd_unit . $ovrspd_unit_matricula . '</span>
                                        </p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </td>
                <td class="column column-2" width="30%"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                    <table class="text_block block-1" width="100%" border="0"
                        cellpadding="10" cellspacing="0" role="presentation"
                        style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                        <tr>
                            <td class="pad">
                                <div style="font-family: sans-serif">
                                    <div class
                                        style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                        <p dir="ltr"
                                            style="margin: 0; font-size: 12px; text-align: right; mso-line-height-alt: 14.399999999999999px;">
                                            <strong><span
                                                    style="font-size:14px;">' . $maxSpeed . '</span></strong>
                                        </p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        ';
            }
        } else {
            $overspeed_container .= '<tr>
                <td class="column column-1" width="100%"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-left: 10px; padding-right: 10px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                    <table class="text_block block-1" width="100%" border="0"
                        cellpadding="10" cellspacing="0" role="presentation"
                        style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                        <tr>
                            <td class="pad">
                                <div style="font-family: sans-serif">
                                    <div class
                                        style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                        <p dir="ltr"
                                            style="margin: 0; font-size: 12px; text-align: left; mso-line-height-alt: 14.399999999999999px;">
                                            <span style="font-size:14px;">Para activar las alertas de exceso de velocidad, comun&iacute;quese con nuestro departamento comercial.</span>
                                        </p>
                                    </div>
                                </div>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>';
            $maxspeed_container .= '<tr>
            <td class="column column-1" width="100%"
                style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; font-weight: 400; text-align: left; background-color: #ffffff; padding-bottom: 0px; padding-left: 10px; padding-right: 10px; padding-top: 5px; vertical-align: top; border-top: 0px; border-right: 0px; border-bottom: 0px; border-left: 0px;">
                <table class="text_block block-1" width="100%" border="0"
                    cellpadding="10" cellspacing="0" role="presentation"
                    style="mso-table-lspace: 0pt; mso-table-rspace: 0pt; word-break: break-word;">
                    <tr>
                        <td class="pad">
                            <div style="font-family: sans-serif">
                                <div class
                                    style="font-size: 12px; font-family: \'Roboto\', Tahoma, Verdana, Segoe, sans-serif; mso-line-height-alt: 14.399999999999999px; color: #4b4b4d; line-height: 1.2;">
                                    <p dir="ltr"
                                        style="margin: 0; font-size: 12px; text-align: left; mso-line-height-alt: 14.399999999999999px;">
                                        <span style="font-size:14px;">Para activar las alertas de exceso de velocidad, comun&iacute;quese con nuestro departamento comercial.</span>
                                    </p>
                                </div>
                            </div>
                        </td>
                    </tr>
                </table>
            </td>
            </tr>';
        }

        $reportHtml = file_get_contents("template/protracking/reporte_semanal.html");
        //$reportHtml = file_get_contents("app/content/reporte_semanal.html");

        //$img = file_get_contents("../images/logo-protracking.png");
        //$imgdata = base64_encode($img);
        //$imgLogo = '<img src="data:image/x-icon;base64,' . $imgdata . '" style="display: block; height: auto; border: 0; width: 207px; max-width: 100%;">';
        $imgLogo = '<img src="https://www.protracking.com.uy/images/logo-protracking.png" style="display: block; height: auto; border: 0; width: 207px; max-width: 207px;" width="207">';

        $reportHtml = str_replace('{logo_image}', $imgLogo, $reportHtml);
        $reportHtml = str_replace('{logo_image1}', $imgLogo, $reportHtml);
        $reportHtml = str_replace('{reporte_rango_fechas}', $reporte_rango_fechas, $reportHtml);
        $reportHtml = str_replace('{km_flota}', $km_flota, $reportHtml);
        $reportHtml = str_replace('{km_flota_porcentaje}', $km_flota_porcentaje, $reportHtml);
        $reportHtml = str_replace('{km_flota_porcentaje_color}', $km_flota_porcentaje_color, $reportHtml);
        $reportHtml = str_replace('{excesos}', $excesos, $reportHtml);
        $reportHtml = str_replace('{excesos_title}', $excesos_title, $reportHtml);
        $reportHtml = str_replace('{vel_max}', $vel_max, $reportHtml);
        $reportHtml = str_replace('{vel_max_unit}', $vel_max_unit, $reportHtml);
        $reportHtml = str_replace('{vel_max_title}', $vel_max_title, $reportHtml);
        $reportHtml = str_replace('{vel_max_unit_date}', $vel_max_unit_date, $reportHtml);
        $reportHtml = str_replace('{km_recorrido_container}', $km_recorrido_container, $reportHtml);
        $reportHtml = str_replace('{overspeed_container}', $overspeed_container, $reportHtml);
        $reportHtml = str_replace('{maxspeed_container}', $maxspeed_container, $reportHtml);
        $reportHtml = str_replace('{resumen}', $resumen, $reportHtml);

        //registro el reporte
        $reportId = $borr->registerSending("SEM", $reportHtml);

        $imgLogo = '<img src="https://www.protracking.com.uy/app/getLogoImage.php?uid=' . $usersWithEmail[$i]['id_usuario'] . '&rid=' . $reportId . '" style="display: block; height: auto; border: 0; width: 207px; max-width: 207px;" width="207">';
        $reportHtml = str_replace('<img src="https://www.protracking.com.uy/images/logo-protracking.png" style="display: block; height: auto; border: 0; width: 207px; max-width: 207px;" width="207">', $imgLogo, $reportHtml);

        require_once "../PHPMailer/Exception.php";
        require_once "../PHPMailer/PHPMailer.php";
        require_once "../PHPMailer/SMTP.php";

        $mail = new PHPMailer();

        //Server settings
        $mail->isSMTP();
        //$mail->SMTPDebug = 1;
        $mail->Host = 'smtpout.secureserver.net';
        $mail->SMTPAuth = true;
        $mail->Username = 'noresponder@protracking.com.uy';
        $mail->Password = 'NoResponder1024!';
        $mail->SMTPSecure = 'smtp';
        $mail->Port = 80;                                    // TCP port to connect to

        //Recipients
        $mail->setFrom("noresponder@protracking.com.uy", "Protracking");
        $mail->addAddress($userEmailToSend, $userName);
        $mail->clearReplyTos();
        $mail->addReplyTo("comercial@protracking.com.uy", "Protracking");

        // Content
        $mail->isHTML(true);
        $mail->Subject = 'Reporte semanal Protracking - ' . $userName;
        $mail->Body = $reportHtml;

        $mail->AltBody = 'Reporte semanal Protracking - ' . $userName;

        if (!$mail->send()) {
            $borr->registerSendingResult($reportId, false);
            echo "Error al enviar a: " . $userEmailToSend . "<br>";
        } else {
            $borr->registerSendingResult($reportId, true);
            echo "Enviado a: " . $userEmailToSend . "<br>";
        }
    }
}

function getLastSaturdaysTimestamp()
{
    $hoy = strtotime('today');          // Obtener la fecha de hoy a las 0 horas
    $diaSemana = date('N', $hoy);       // Obtener el número del día de la semana (1 para lunes, 7 para domingo)                                  
    if ($diaSemana == 6) {              // Si hoy es sábado, devolver el timestamp de hoy mismo a las 0 horas
        return $hoy;
    } else {                            // Obtener el timestamp del sábado anterior
        $sabadoAnterior = strtotime('last Saturday', $hoy);
        return $sabadoAnterior;
    }
}
