<?php
    # Autoload
    require 'vendor/autoload.php';
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\SMTP;
    use PHPMailer\PHPMailer\Exception;
    include('./config.php');

    function getUserIP()
    {
        // Get real visitor IP behind CloudFlare network
        if (isset($_SERVER["HTTP_CF_CONNECTING_IP"])) {
                  $_SERVER['REMOTE_ADDR'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
                  $_SERVER['HTTP_CLIENT_IP'] = $_SERVER["HTTP_CF_CONNECTING_IP"];
        }
        $client  = @$_SERVER['HTTP_CLIENT_IP'];
        $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
        $remote  = $_SERVER['REMOTE_ADDR'];
    
        if(filter_var($client, FILTER_VALIDATE_IP))
        {
            $ip = $client;
        }
        elseif(filter_var($forward, FILTER_VALIDATE_IP))
        {
            $ip = $forward;
        }
        else
        {
            $ip = $remote;
        }
    
        return $ip;
    }

    function genpw($length = 9, $add_dashes = false, $available_sets = 'luds')
    {
        $sets = array();
        if(strpos($available_sets, 'l') !== false)
            $sets[] = 'abcdefghjkmnpqrstuvwxyz';
        if(strpos($available_sets, 'u') !== false)
            $sets[] = 'ABCDEFGHJKMNPQRSTUVWXYZ';
        if(strpos($available_sets, 'd') !== false)
            $sets[] = '23456789';
        if(strpos($available_sets, 's') !== false)
            $sets[] = '!@$%&?';

        $all = '';
        $password = '';
        foreach($sets as $set)
        {
            $password .= $set[array_rand(str_split($set))];
            $all .= $set;
        }

        $all = str_split($all);
        for($i = 0; $i < $length - count($sets); $i++)
            $password .= $all[array_rand($all)];

        $password = str_shuffle($password);

        if(!$add_dashes)
            return $password;

        $dash_len = floor(sqrt($length));
        $dash_str = '';
        while(strlen($password) > $dash_len)
        {
            $dash_str .= substr($password, 0, $dash_len) . '-';
            $password = substr($password, $dash_len);
        }
        $dash_str .= $password;
        return $dash_str;
    }

    $bodytemplate = file_get_contents("mailtemplate_on.html");
    $daten = json_decode(file_get_contents('php://input'), true);
    //var_dump($daten);

    $name = $daten["name"]; // vorname/nachname
    $ignite = $daten["ignite"]; 
    $pw = genpw();
    $daten["passwort"]              = $pw;
    $daten["vorname"]               = $name["vorname"];
    $daten["nachname"]              = $name["nachname"];
    $daten["mitarbeitertyp"]        = ( ($daten["anrede"]=="Frau") ? " eine neue Mitarbeiterin " : " ein neuer Mitarbeiter "  );
    $daten["banrede"]               = ( ($daten["anrede"]=="Frau") ? " eine neue Mitarbeiterin " : " ein neuer Mitarbeiter " );
    $daten["mykenejanein"]          = ( ( array_key_exists("mykene", $daten) ) ? "<font style='color:green;'><b>Ja</b></font>" : "<font style='color:red;'><b>Nein</b></font>" );
    $daten["ip"]                    = getUserIP();
    $daten["date"]                  = date("d.m.Y");
    $daten["time"]                  = date("H:i");
    $daten["passwort"]              = $pw;
    $daten["ignite-telefon"]        = ( ( in_array("telefon", $ignite) ) ? "Ja" : "Nein"  );
    $daten["ignite-email"]          = ( ( in_array("email", $ignite) ) ? "Ja" : "Nein"  );
    $daten["agentengruppen_list"]   = implode(",", $daten["agentengruppen"]);
    $daten["infos"]                 = nl2br($daten["infos"]);

    $body = $bodytemplate;
    $forjson = [];
    $groups = "";
    foreach($daten as $key => $value) 
    {
        // if ( !in_array($key,['name', 'ignite', 'agentengruppen']) ) 
        echo $key . " -> " .  gettype($value);
        if ( in_array(gettype($value), ["string","integer", "double"]) )
        {
            $body = str_replace("%".$key."%", $value, $body );
            $forjson[$key] = $value;
        }
    }
    if ( !array_key_exists("mykene", $daten) ) { $body = preg_replace("/<ul id='mykene'>/ims", '<ul style="display:none;">', $body); }
    
    // Daten lokal ablegen:
    //$date = new DateTimeImmutable('2000-01-01');
    $filename = date("YmdHis") . "_" . $daten["nachname"];
    file_put_contents("auftraege/on_".$filename.'.json', json_encode($forjson, JSON_UNESCAPED_UNICODE), FILE_APPEND | LOCK_EX);

    // Welcome PDF erstellen
    $pdfvorlage = file_get_contents("./xtend_welcome.html");
    foreach($daten as $key => $value) 
    {
        // if ( !in_array($key,['from','to','q','name']) ) 
        if ( in_array(gettype($value), ["string","integer", "double"]) )
        {
            $pdfvorlage = str_replace("%".$key."%", $value, $pdfvorlage );
        }
    }
    file_put_contents("auftraege/on_".$filename.'.html', $pdfvorlage);

    // erstmal per mail
    try {
        // Versuch, eine neue Instanz der Klasse PHPMailer zu erstellen
        $mail = new PHPMailer (true);
        //$mail->SMTPDebug = SMTP::DEBUG_SERVER;
        $mail->isSMTP();
        $mail->Host = "postfix";
        $mail->Port = "25";
        $mail->SMTPAuth = false;
        $mail->CharSet = 'UTF-8';
        $mail->Encoding = 'base64';
        $mail->setFrom($config['mailfrom'], 'dialog-it Xtend');
        $mail->addAddress($config['mailto'], 'Support');
        $mail->isHTML(true);
        $mail->Subject = (($daten["anrede"]=="Frau") ? "Neue Mitarbeiterin" : "Neuen Mitarbeiter" ). " anlegen: " . $daten["vorname"] . " " . $daten["nachname"];
        $mail->Body = $body;
        // Anhang hinzufügen
        $mail->addAttachment("auftraege/on_".$filename.".json", $filename.".json");
        $mail->addAttachment("auftraege/on_".$filename.".html", $filename.".html");

        $mail->send();
        echo "
        Auftrag für " . (($daten["anrede"]=="Frau") ? "neue Mitarbeiterin" : "neuen Mitarbeiter" ). " " . $daten["vorname"] . " " . $daten["nachname"] . " erteilt.<br/>
        Die Auftragsbestätigung erhalten sie über unser Ticketsystem per eMail.
        ";
        return true;
    } catch (Exception $e) {
        echo "<h2>Fehler beim Senden...</h2>";
        return false;
    }

?>
