<?php

class cron
{
    public static function ifLocalHost(){
        return $_SERVER['SERVER_ADDR'] === $_SERVER['REMOTE_ADDR'] ? TRUE : FALSE;
    }

    public static function sendMailAssignDocument(){
        foreach (document::assignMailDocument() as $assign) {
            if(self::checkParameter($assign["id"])){
                document::sendEmailCronAssign($assign);
            }
        }
    }

    public static function insertParameter(array $_array = NULL){

        $userId = session::getId();

        db::query("DELETE FROM " . DB_T_ALERTES_EMAILS . " WHERE id_user = :id_user");
        db::bind(':id_user', $userId);
        db::execute();

        if(!is_null($_array)){
            foreach ($_array as $heure => $tmp) { 
                foreach ($tmp as $jour => $value) {
                    db::query("INSERT INTO " . DB_T_ALERTES_EMAILS . " (id, id_user, heure, jour) VALUES (:id, :id_user, :heure, :jour)");
                    db::bind(':id', $userId."#".$heure."#".$jour);
                    db::bind(':id_user', $userId);
                    db::bind(':heure', $heure);
                    db::bind(':jour', $jour);
                    
                    try {
                        db::execute();
                    } catch (Exception $ex) {
                        alert::recError("Erreur d'enregistrement des alertes");
                        return FALSE;
                    }
                }
            }
            alert::recSuccess("Enregistrement pris en compte");
            return TRUE;
        } else {
            alert::recSuccess("Vous n'avez plus de plages horaires enregistrées");
            return TRUE;
        }
        
    }

    public static function getParameter(float $_id = NULL){
        $userId = is_null($_id) ? session::getId() : $_id;

        db::query("SELECT "
            . "" . DB_T_ALERTES_EMAILS . ".heure, "
            . "" . DB_T_ALERTES_EMAILS . ".jour "
            . "FROM " . DB_T_ALERTES_EMAILS . " "
            . "WHERE id_user = :id_user");
        db::bind(':id_user', $userId);
        $tmp = db::resultset();

        if(isset($tmp)){
            $return = [];
            foreach ($tmp as $value) {
                $return[$value["heure"]][$value["jour"]] = 1;
            }
            return $return;
        } else {
            return NULL;
        }
        
    }

    public static function checkParameter(float $_id){
        $data = self::getParameter($_id);
        $jourSemaineOriginal = date('w');
        $jourSemaineAdjuste = ($jourSemaineOriginal + 6) % 7; // Pour que le Lundi soit le numéro 0
        return isset($data[date('G')][$jourSemaineAdjuste]) ? TRUE : FALSE;
    }
}