<?php
    date_default_timezone_set('Europe/Zagreb');
    
    use PHPMailer\PHPMailer\PHPMailer;
    use PHPMailer\PHPMailer\Exception;
    use PHPMailer\PHPMailer\SMTP;

    require '../mailer/Exception.php';
    require '../mailer/PHPMailer.php';
    require '../mailer/SMTP.php';

    $filename = $_GET['filename'];
    $month = $_GET['month'];
    $year = $_GET['year'];
    $filenameOriginal =  "narudzbe_".$month."_".$year.".pdf";

    $smtpUsername = 'kriklunch@gmail.com';
    $smtpPassword = 'llyimaxhzyysuaej';

    $emailFrom = 'kriklunch@gmail.com';
    $emailFromName = 'Lunch Statistika';
    
    $emailTo = 'mario@krikstudio.com';
    //$emailToName = 'Mario';
    
    $email_body = "
        <head>
            <meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
        </head>
        <div>
            <div>
                <p>U prilogu je statistika narudžbi za ".$month."/".$year.".</p>
            </div>
            <div><br/></div>
        </div>
    ";
    
    $mail = new PHPMailer;
    $mail->CharSet = 'UTF-8';
    $mail->Encoding = 'base64';
    $mail->isSMTP(); 
    $mail->SMTPDebug = 0; // 0 = off (for production use) - 1 = client messages - 2 = client and server messages
    $mail->Host = "smtp.gmail.com";
    $mail->Port = 587; // TLS only
    $mail->SMTPSecure = 'tls';
    $mail->SMTPAuth = true;
    $mail->Username = $smtpUsername;
    $mail->Password = $smtpPassword;
    $mail->setFrom($emailFrom, $emailFromName);
    $mail->addAddress($emailTo);
    $mail->Subject = 'Lunch statistika za '.$month.'/'.$year.'';
    $mail->msgHTML($email_body);
    $mail->AddAttachment('../pdfs/'.$filename.'', ''.$filenameOriginal.'');
    $mail->AltBody = 'HTML messaging not supported';
    
    if(!$mail->send()){
        echo "We are sorry, but the email did not go through.";
    } else {
        $files = glob('../pdfs/*');
        foreach($files as $file) {
            if(is_file($file)) {
                unlink($file);
            }
        }
        header('Location: ../statistika');
    }
?>