<?php

session_start();

?>

<!DOCTYPE html>
<html>
<head>
<title>TM47 Forms |ThaiDocs.online</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" crossorigin="anonymous"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>

<?php


if 
(
empty($_POST['writtenat']) || 
empty($_POST['firstname']) || 
empty($_POST['familyname']) ||
empty($_POST['nationality']) || 
empty($_POST['pno']) || 
empty($_POST['arrivedby']) || 
empty($_POST['doadd']) || 
empty($_POST['doamm']) || 
empty($_POST['doayyyy']) || 
empty($_POST['departurecardno']) ||  
empty($_POST['addressno']) || 
empty($_POST['addressroad']) || 
empty($_POST['tambon']) || 
empty($_POST['amphoe']) || 
empty($_POST['changwat']) || 
empty($_POST['phone']) || 
empty($_POST['captcha']) || 
$_POST['captcha'] != $_SESSION['captcha']['code']
)
{

?>
<br />
<div class="row justify-content-md-center">
    <div class="col-7">
<div class="alert alert-danger" role="alert">
  <h4 class="alert-heading">Whoops!</h4>
  <p>Something went terribly wrong, either you forgot to fill in some details that are clearly marked with an asterisk or you wrote the captcha wrong. In anycase, you can click back to check what is missing, don't worry, you don't lose your information.</p>
</div>
</div>
</div>

<div class="row justify-content-md-center">
    <div class="col-7">
<a class="btn btn-primary" href="#" onclick="window.history.go(-1)" role="button">Just click me, it's completely safe :)</a>
</div>
</div>

<?php
} else {

//require("../utils/mailer/PHPMailerAutoload.php");

// Word Wrapping Function
function wordWrapAnnotation(&$image, &$draw, $text, $maxWidth)
{
    $words = explode(" ", $text);
    $lines = array();
    $i = 0;
    $lineHeight = 0;
    while($i < count($words) )
    {
        $currentLine = $words[$i];
        if($i+1 >= count($words))
        {
            $lines[] = $currentLine;
            break;
        }
        //Check to see if we can add another word to this line
        $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
        while($metrics['textWidth'] <= $maxWidth)
        {
            //If so, do it and keep doing it!
            $currentLine .= ' ' . $words[++$i];
            if($i+1 >= count($words))
                break;
            $metrics = $image->queryFontMetrics($draw, $currentLine . ' ' . $words[$i+1]);
        }
        //We can't add the next word to this line, so loop to the next line
        $lines[] = $currentLine;
        $i++;
        //Finally, update line height
        if($metrics['textHeight'] > $lineHeight)
            $lineHeight = $metrics['textHeight'];
    }
    return array($lines, $lineHeight);
}

// Before we start the Imagick, let's parse the values from the forms from the page before

// Safely extract and sanitize POST inputs
$writtenat       = trim($_POST['writtenat'] ?? '');
$familyname      = trim($_POST['familyname'] ?? '');
$firstname       = trim($_POST['firstname'] ?? '');
$middlename      = trim($_POST['middlename'] ?? '');

$nationality     = trim($_POST['nationality'] ?? '');
$pno             = trim($_POST['pno'] ?? '');
$pvisa           = trim($_POST['pvisa'] ?? '');
$arrivedby       = trim($_POST['arrivedby'] ?? '');

$doadd           = (int) ($_POST['doadd'] ?? 0);
$doamm           = trim($_POST['doamm'] ?? '');
$doayyyy         = (int) ($_POST['doayyyy'] ?? 0);

$departurecardno = trim($_POST['departurecardno'] ?? '');
$addressno       = trim($_POST['addressno'] ?? '');
$addressroad     = trim($_POST['addressroad'] ?? '');
$tambon          = trim($_POST['tambon'] ?? '');
$amphoe          = trim($_POST['amphoe'] ?? '');
$changwat        = trim($_POST['changwat'] ?? '');
$phone           = trim($_POST['phone'] ?? '');


// New Imagick (Page 1 & Page 2)
//$images = array("form_tm7_Page_2.png","form_tm7_Page_1.png");
//$img  = new Imagick($images);

$combined = new Imagick();

$img = new Imagick("form_tm47_Page_1.png");

// Set font properties
$draw = new ImagickDraw();
$draw->setFont('../utils/arial.ttf');
$draw->setFontSize(32);
$draw->setFillColor('black');

// Draw text on the image - Y side to side - X top to bottom
$img->annotateImage($draw, 1000, 420, 0, $writtenat);

$img->annotateImage($draw, 480, 690, 0, strtoupper($firstname));
$img->annotateImage($draw, 780, 690, 0, strtoupper($middlename));
$img->annotateImage($draw, 1080, 690, 0, strtoupper($familyname));

$img->annotateImage($draw, 350, 780, 0, $nationality);

if($pvisa == "tourist") { 

    $img->annotateImage($draw, 905, 792, 0, "x");

} else { 

    $img->annotateImage($draw, 905, 828, 0, "x");

}


$img->annotateImage($draw, 450, 880, 0, $doadd);
$img->annotateImage($draw, 600, 880, 0, $doamm);
$img->annotateImage($draw, 800, 880, 0, $doayyyy);

$img->annotateImage($draw, 1050, 880, 0, $arrivedby);

$img->annotateImage($draw, 420, 970, 0, $pno);
$img->annotateImage($draw, 1020, 970, 0, $departurecardno);

$img->annotateImage($draw, 1010, 1065, 0, $addressno);
$img->annotateImage($draw, 320, 1155, 0, $addressroad);
$img->annotateImage($draw, 690, 1155, 0, $tambon);
$img->annotateImage($draw, 1130, 1155, 0, $amphoe);
$img->annotateImage($draw, 320, 1250, 0, $changwat);

$img->annotateImage($draw, 720, 1250, 0, $phone);

$img->setimageFormat('pdf');

//header('Content-type: image/png');
//header("Content-type:application/pdf");d

// Lets creat a random string to append to the tm07 form entry.
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

$pdfFilename = 'tm47-'.generateRandomString().'.pdf';
//$pdfFilename = 'tm47-test.pdf';

// Write this all out into a nifty .pdf
$img->writeImages('./uploads/'.$pdfFilename.'', true);

/*
//Name of the PDF Attachment
$file = "new_partner.pdf";

//Here comes the Mail message
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'ice.iceservers.net';
$mail->SMTPAuth = true;
$mail->Username = 'postbot@orangewebsite.com';
$mail->Password = 'CDQ9xCypiJHz';
$mail->SMTPSecure = 'ssl';
$mail->Port = '465';

$mail->SetFrom('d3acon85@gmail.com', 'Henri Johannes');
$mail->AddReplyTo('d3acon85@gmail.com', 'Henri Johannes');
//$mail->AddAddress('steini@orangewebsite.com', 'Form Tests');
$mail->AddAddress('wires@europacbank.com', 'EuroPacBank Wires');
$mail->AddCC('dbaldo@europacbank.com');
$mail->AddBCC('invoices@orangewebsite.com', 'Orangewebsite Invoices');

$mail->Subject = '[' .$p_name. '] New Partner form for user: icenetwo';
$mail->Body = 
"Hello,

Attached is a New Partner document, detailing the relationship between IceNetworks and It's client. All details should be properly filled. If there is any issue relating to this partnership document feel free to reply back to " .$email. " with the PDF attached and point out the issue with the document and we will redo the document.

Thank you,
".$name."

Reference Number: #".$invoicenr."";

$mail->AddStringAttachment($output, $file);

if(!$mail->send()) {
  echo 'Message was not sent. Something went wrong<br />';
  //echo 'Mailer Error: ' . $mail->ErrorInfo;
 } else {
*/

?>

<br />

<div class="row justify-content-md-center">
    <div class="col-7">
<div class="alert alert-success" role="alert">
  <h4 class="alert-heading">Success! (But lets still read on..)</h4>
  <p>You have successfully filled in all requirements for the TM47 forms, and the link to your .pdf can be found <a href="./uploads/<?php echo $pdfFilename; ?>" target="blank_">here</a>. However so we don't forget anything, below is a checklist of all things needed to pass the 90 day report process at the Immigration.</p>
  <hr>
  <ul>
  <li><p class="mb-0">1 x Passport (Original)</p></li>
  <li><p class="mb-0">1 x Copy of your Passport Information Page</p></li>
  <li><p class="mb-0">1 x TM06 Departure Card / Photocopy (Better safe than sorry, as it depends on the immigration officer and his or her mood)</p></li>
  <li><p class="mb-0">.. and of course your <a href="./uploads/<?php echo $pdfFilename; ?>" target="blank_">PDF</a> let's not forget that</p></li>
  </ul>
</div>

</div>
</div>

<div class="row justify-content-md-center">
    <div class="col-7">
<a class="btn btn-primary" href="//thaidocs.online">You done?... Click here to go back to the main library</a>
</div>
</div>

</body>
</html>

<?php

}

session_destroy();

?>