<?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;

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

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

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

        $sinuso = (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 per&iacute;odos prolongados sin uso.</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'] . ' <span style="font-size:30px;">Hr</span></strong></span></p>';
        $sinuso_title = (is_null($results['overspeedCount'])) ? '' : 'Per&iacute;odos prolongados<br>sin uso';
        $tot_arboles_cosechados = (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'] . '</strong></span></p>';
        $tot_arboles_cosechados_title = (is_null($results['overspeedCount'])) ? '' : '&Aacute;rboles cosechados<br>por flota';

        $total_horas_trabajadas = $hr_flota;
        $porcentaje_horas_trabajadas = $dHr;
        $promedio_horas_trabajadas = $results['km']['avgKm'];

        $maq_mas_horas = $results['km']['maxKmUnit'];
        $maq_mas_horas_matricula = ($results['km']['maxKmUnitMatricula']) ? ' (' . $results['km']['maxKmUnitMatricula'] . ')' : $results['km']['maxKmUnitMatricula'];
        $maq_mas_horas_cantidad = $results['km']['maxKm'];
        $maq_menos_horas = $results['km']['minKmUnit'];
        $maq_menos_horas_matricula = ($results['km']['minKmUnitMatricula']) ? ' (' . $results['km']['minKmUnitMatricula'] . ')' : $results['km']['minKmUnitMatricula'];
        $maq_menos_horas_cantidad = $results['km']['minKm'];

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

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

        if ($hr_flota > 0 && $totUnits > 0) {
            $avg_hrs_x_maq = $hr_flota / $totUnits;
            $texto_promedio = ($totUnits == 1) ? '' : 'El promedio de horas trabajadas por cada m&aacute;quina en este per&iacute;odo fue de ' . round($avg_hrs_x_maq, 0) . ' Hr.<br>';
        } else {
            $texto_promedio = '';
        }

        $resumen = 'Esta semana tu flota acumul&oacute; ' . $total_horas_trabajadas . ' Hr, ' . $resumenPorcent . ' realizando en promedio ' . $promedio_horas_trabajadas . ' Hr diarias. <br><br>';
        $resumen .= ($totUnits == 1) ? '' : 'La m&aacute;quina que m&aacute;s horas trabaj&oacute; es "' . $maq_mas_horas . '" ' . $maq_mas_horas_matricula . ', con ' . $maq_mas_horas_cantidad . ' Hr y la que menos trabaj&oacute; es 
                "' . $maq_menos_horas . '"' . $maq_menos_horas_matricula . ', con ' . $maq_menos_horas_cantidad . ' Hr.<br><br>' . $texto_promedio;

        $horas_trabajadas_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'];

            $horas_trabajadas_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 . ' Hr</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: #1eb93b; line-height:5px;"></td>
                                                                            </tr>
                                                                        </tbody>    
                                                                    </table>
                                                                </td>
                                                            </tr>
                                                        </tbody>    
                                                    </table>
                                                </td>
                                            </tr>';
        }

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

            foreach ($results['overspeedCount']['details'] as $overSpd) {
                $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'];

                //PERIODO SIN USO
                $periodosinuso_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 . ' Hr</span></strong>
                                                                        </p>
                                                                    </div>
                                                                </div>
                                                            </td>
                                                        </tr>
                                                    </table>
                                                </td>
                                            </tr>';
            }
        } else {
            $periodosinuso_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;">No se registraron per&iacute;odos sin uso..</span>
                                                                    </p>
                                                                </div>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                </table>
                                            </td>
                                        </tr>';
        }

        $reportHtml = file_get_contents("template/forestracking/reporte_semanal_f.html");

        $imgLogo = '<img src="http://www.forestracking.com/images/logo-forestracking.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}', $hr_flota, $reportHtml);
        $reportHtml = str_replace('{hr_flota_porcentaje}', $hr_flota_porcentaje, $reportHtml);
        $reportHtml = str_replace('{hr_flota_porcentaje_color}', $hr_flota_porcentaje_color, $reportHtml);
        $reportHtml = str_replace('{excesos}', $sinuso, $reportHtml);
        $reportHtml = str_replace('{excesos_title}', $sinuso_title, $reportHtml);
        $reportHtml = str_replace('{tot_arboles_cosechados}', $tot_arboles_cosechados, $reportHtml);
        $reportHtml = str_replace('{tot_arboles_cosechados_title}', $tot_arboles_cosechados_title, $reportHtml);
        $reportHtml = str_replace('{arboles_flota_porcentaje}', $arboles_flota_porcentaje, $reportHtml);
        $reportHtml = str_replace('{arboles_flota_porcentaje_color}', $arboles_flota_porcentaje_color, $reportHtml);

        $reportHtml = str_replace('{horas_trabajadas_container}', $horas_trabajadas_container, $reportHtml);
        $reportHtml = str_replace('{periodosinuso_container}', $periodosinuso_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="http://www.forestracking.com/images/logo-forestracking.png" style="display: block; height: auto; border: 0; width: 207px; max-width: 207px;" width="207">', $imgLogo, $reportHtml);

        echo $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;
    }
}
