<?php
include('/var/www/html/track/server/s_init.php');
include('/var/www/html/track/server/eventos.php');
include('/var/www/html/track/server/s_events.php');
include('/var/www/html/track/func/fn_common.php');
include('/var/www/html/track/func/fn_cleanup.php');
include('/var/www/html/track/tools/gc_func.php');
require_once "/var/www/html/track/tools/FlowApi.class.php";
require_once "/var/www/html/track/func/fn_st_flow_common.php";

if (!isset($_GET["email"]) || trim($_GET["email"]) == "") {
    die("Es necesario pasar el [email] por GET");
}

function serviceCheckObjectDateLimit()
{
    global $ms, $gsValues, $la, $encryptionSeparator;

    $email = $_GET["email"];

    // deactivate expired objects
    $deactivateUpdate = "UPDATE gs_objects
                        SET `active`='false'
                        WHERE `active`='true'
                        AND `object_expire`='true'
                        AND object_expire_dt <= UTC_DATE()";

    mysqli_query($ms, $deactivateUpdate);

    // remind about object expiry
    if ($gsValues['NOTIFY_OBJ_EXPIRE'] == 'true') {
        $userQuery = "SELECT
                        id,
                        email,
                        language
                    FROM `gs_users`
                    WHERE `privileges` NOT LIKE ('%subuser%') and privilegios = 99";

        $userResponse = mysqli_query($ms, $userQuery);

        if (mysqli_errno($ms)) {
            error(500, "Error: ".mysqli_error($ms));
        }

        while ($userRow = mysqli_fetch_array($userResponse)) {
            $notify = false;

            $user_id = $userRow["id"];
            $email = $userRow["email"];

            echo $email;

            $userObjectQuery = "SELECT
                                    imei
                                FROM `gs_user_objects`
                                WHERE `user_id`='" . $user_id . "'";

            $userObjectResponse = mysqli_query($ms, $userObjectQuery);

            if (mysqli_errno($ms)) {
                error(500, "Error: ".mysqli_error($ms));
            }

            while ($userObjectRow = mysqli_fetch_array($userObjectResponse)) {
                $imei = $userObjectRow['imei'];
                
                $objectQuery = "SELECT
                                    object_expire_dt,
                                    plate_number,
                                    notif_status
                                FROM `gs_objects`
                                LEFT JOIN st_object_expiry_notif
                                USING (imei)
                                WHERE `imei`='" . $imei . "'
                                AND `active`='true'
                                AND `object_expire`='true'";
                                
                $objectResponse = mysqli_query($ms, $objectQuery);
                $objectRow = mysqli_fetch_array($objectResponse);

                if ($objectRow)
                {
                    
                    $diff = strtotime($objectRow['object_expire_dt']) - strtotime(gmdate("Y-m-d"));
                    echo "imei = ".$imei;
                    echo "<br/>dif=".$diff;
                    $days = $diff / 86400;
                    echo " <br/>days= " .$days;
                    echo " <br/>";
                    echo $gsValues['NOTIFY_OBJ_EXPIRE_PERIOD'][0];
                    echo " <br/>";
                    echo$objectRow['notif_status'];
                    echo " <br/>";
                    if (in_array($days, $gsValues['NOTIFY_OBJ_EXPIRE_PERIOD']) && in_array($objectRow['notif_status'], [0, 1])) {
                        echo "entra 1 if";
                        echo " <br/>";
                        if ($days == $gsValues['NOTIFY_OBJ_EXPIRE_PERIOD'][0] && $objectRow['notif_status'] > 0) {
                            echo "entra 2 if";
                            echo " <br/>";
                            continue;
                        }

                        $template      = getDefaultTemplate('expiring_objects', $userRow["language"]);
        
                        $subject       = $template['subject'];
                        $message       = $template['message'];
                        $expiryDate    = date_create($objectRow['object_expire_dt']);

                        $url           = $gsValues['URL_PLATE_PAYMENT'];
                        $urlData       = [
                            $email,
                            $objectRow["plate_number"]
                        ];
                        $urlDataString = implode($encryptionSeparator, $urlData);
                        $signature     = shortEncode($urlDataString);

                        $url           = str_replace("%SIGNATURE%", $signature, $url);
    
                        $subject       = str_replace("%PLATE_NUMBER%", $objectRow['plate_number'], $subject);
                        $subject       = str_replace("%PAYMENT_URL%", $url, $subject);
    
                        $message       = str_replace("%PLATE_NUMBER%", $objectRow['plate_number'], $message);
                        $message       = str_replace("%PAYMENT_URL%", $url, $message);
                        $message       = str_replace("%EXPIRY%", date_format($expiryDate, "d/m/Y"), $message);

                        sendEmail($email, $subject, $message);

                        $q = "UPDATE st_object_expiry_notif SET notif_status = notif_status + 1 WHERE imei = ?";
                        $stmt = mysqli_prepare($ms, $q);
                        mysqli_stmt_bind_param($stmt, 's', $imei);
                        mysqli_stmt_execute($stmt);

                        if (mysqli_stmt_errno($stmt)) {
                            error(500, "Error: ".mysqli_stmt_error($stmt));
                        }
                    }
                }
            }
        }
    }
}

serviceCheckObjectDateLimit();