<?php

session_start();

?>

<!DOCTYPE html>
<html>
<head>
<title>TM07 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['familyname']) || 
empty($_POST['firstname']) || 
empty($_POST['dd']) || 
empty($_POST['mm']) || 
empty($_POST['yyyy']) || 
empty($_POST['placeofbirth'])|| 
empty($_POST['nationality']) || 
empty($_POST['pno']) || 
empty($_POST['pidd']) || 
empty($_POST['pimm']) || 
empty($_POST['piyyyy']) || 
empty($_POST['plocation']) || 
empty($_POST['pvdd']) || 
empty($_POST['pvmm']) || 
empty($_POST['pvyyyy']) || 
empty($_POST['pvisa']) || 
empty($_POST['arrivedby']) || 
empty($_POST['fromwhere']) || 
empty($_POST['portofarrival']) || 
empty($_POST['doadd']) || 
empty($_POST['doamm']) || 
empty($_POST['doayyyy']) || 
empty($_POST['departurecardno']) || 
empty($_POST['howmany']) || 
empty($_POST['addressthai']) || 
empty($_POST['writtenby']) || 
empty($_POST['addressno']) || 
empty($_POST['addressroad']) || 
empty($_POST['tambon']) || 
empty($_POST['amphoe']) || 
empty($_POST['changwat']) || 
empty($_POST['captcha']) || 
!isset($_SESSION['captcha']['code']) || 
$_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

// Lets bring into the page the processed Variables
$writtenat   = htmlspecialchars(trim($_POST['writtenat'] ?? ''), ENT_QUOTES, 'UTF-8');
$familyname  = htmlspecialchars(trim($_POST['familyname'] ?? ''), ENT_QUOTES, 'UTF-8');
$firstname   = htmlspecialchars(trim($_POST['firstname'] ?? ''), ENT_QUOTES, 'UTF-8');
$middlename  = htmlspecialchars(trim($_POST['middlename'] ?? ''), ENT_QUOTES, 'UTF-8');

$dd   = filter_var($_POST['dd'] ?? 0, FILTER_SANITIZE_NUMBER_INT);
$mm   = htmlspecialchars(trim($_POST['mm'] ?? ''), ENT_QUOTES, 'UTF-8');
$yyyy = filter_var($_POST['yyyy'] ?? 0, FILTER_SANITIZE_NUMBER_INT);

// Calculate age safely
try {
    $date1 = new DateTime();
    $date2 = new DateTime(sprintf('%04d-%02d-%02d', $yyyy, $mm, $dd));
    $age = $date1->diff($date2)->format('%y');
} catch (Exception $e) {
    $age = '';
}

$placeofbirth = htmlspecialchars(trim($_POST['placeofbirth'] ?? ''), ENT_QUOTES, 'UTF-8');
$nationality  = htmlspecialchars(trim($_POST['nationality'] ?? ''), ENT_QUOTES, 'UTF-8');

$pno       = htmlspecialchars(trim($_POST['pno'] ?? ''), ENT_QUOTES, 'UTF-8');
$pidd      = filter_var($_POST['pidd'] ?? 0, FILTER_SANITIZE_NUMBER_INT);
$pimm      = htmlspecialchars(trim($_POST['pimm'] ?? ''), ENT_QUOTES, 'UTF-8');
$piyyyy    = filter_var($_POST['piyyyy'] ?? 0, FILTER_SANITIZE_NUMBER_INT);
$plocation = htmlspecialchars(trim($_POST['plocation'] ?? ''), ENT_QUOTES, 'UTF-8');

// Optional previous visa date fields
$pvdd = (!isset($_POST['pvdd']) || $_POST['pvdd'] === "NULL") ? "" :
         filter_var($_POST['pvdd'], FILTER_SANITIZE_NUMBER_INT);

$pvmm = (!isset($_POST['pvmm']) || $_POST['pvmm'] === "NULL") ? "" :
         htmlspecialchars(trim($_POST['pvmm']), ENT_QUOTES, 'UTF-8');

$pvyyyy = (!isset($_POST['pvyyyy']) || $_POST['pvyyyy'] === "NULL") ? "" :
           filter_var($_POST['pvyyyy'], FILTER_SANITIZE_NUMBER_INT);

$pvisa          = htmlspecialchars(trim($_POST['pvisa'] ?? ''), ENT_QUOTES, 'UTF-8');
$arrivedby      = htmlspecialchars(trim($_POST['arrivedby'] ?? ''), ENT_QUOTES, 'UTF-8');
$fromwhere      = htmlspecialchars(trim($_POST['fromwhere'] ?? ''), ENT_QUOTES, 'UTF-8');
$portofarrival  = htmlspecialchars(trim($_POST['portofarrival'] ?? ''), ENT_QUOTES, 'UTF-8');

$doadd   = filter_var($_POST['doadd'] ?? 0, FILTER_SANITIZE_NUMBER_INT);
$doamm   = htmlspecialchars(trim($_POST['doamm'] ?? ''), ENT_QUOTES, 'UTF-8');
$doayyyy = filter_var($_POST['doayyyy'] ?? 0, FILTER_SANITIZE_NUMBER_INT);

$departurecardno = htmlspecialchars(trim($_POST['departurecardno'] ?? ''), ENT_QUOTES, 'UTF-8');
$howmany         = filter_var($_POST['howmany'] ?? 0, FILTER_SANITIZE_NUMBER_INT);
$reason          = htmlspecialchars(trim($_POST['reason'] ?? ''), ENT_QUOTES, 'UTF-8');
$addressthai     = htmlspecialchars(trim($_POST['addressthai'] ?? ''), ENT_QUOTES, 'UTF-8');
$writtenby       = htmlspecialchars(trim($_POST['writtenby'] ?? ''), ENT_QUOTES, 'UTF-8');
$addressno       = htmlspecialchars(trim($_POST['addressno'] ?? ''), ENT_QUOTES, 'UTF-8');
$addressroad     = htmlspecialchars(trim($_POST['addressroad'] ?? ''), ENT_QUOTES, 'UTF-8');
$tambon          = htmlspecialchars(trim($_POST['tambon'] ?? ''), ENT_QUOTES, 'UTF-8');
$amphoe          = htmlspecialchars(trim($_POST['amphoe'] ?? ''), ENT_QUOTES, 'UTF-8');
$changwat        = htmlspecialchars(trim($_POST['changwat'] ?? ''), ENT_QUOTES, 'UTF-8');


// 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_tm7_Page_1.png");
$img2 = new Imagick("form_tm7_Page_2.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, 1200, 380, 0, $writtenat);

$img->annotateImage($draw, 670, 740, 0, $familyname);
$img->annotateImage($draw, 1150, 740, 0, $firstname);

$img->annotateImage($draw, 280, 840, 0, $middlename);
$img->annotateImage($draw, 780, 840, 0, $age);
$img->annotateImage($draw, 1050, 840, 0, $dd);
$img->annotateImage($draw, 1190, 840, 0, $mm);
$img->annotateImage($draw, 1450, 840, 0, $yyyy);

$img->annotateImage($draw, 320, 936, 0, $placeofbirth);
$img->annotateImage($draw, 1220, 936, 0, $nationality);

$img->annotateImage($draw, 820, 1032, 0, $pno);
$img->annotateImage($draw, 1320, 1032, 0, $pidd);
$img->annotateImage($draw, 280, 1128, 0, $pimm);
$img->annotateImage($draw, 570, 1128, 0, $piyyyy);
$img->annotateImage($draw, 800, 1128, 0, $plocation);
$img->annotateImage($draw, 1320, 1128, 0, $pvdd);
$img->annotateImage($draw, 280, 1224, 0, $pvmm);
$img->annotateImage($draw, 570, 1224, 0, $pvyyyy);
$img->annotateImage($draw, 850, 1224, 0, $pvisa);

$img->annotateImage($draw, 420, 1320, 0, $arrivedby);
$img->annotateImage($draw, 920, 1320, 0, $fromwhere);

$img->annotateImage($draw, 380, 1416, 0, $portofarrival);
$img->annotateImage($draw, 920, 1416, 0, $doadd);
$img->annotateImage($draw, 1130, 1416, 0, $doamm);
$img->annotateImage($draw, 1400, 1416, 0, $doayyyy);
$img->annotateImage($draw, 730, 1512, 0, $departurecardno);

$img->annotateImage($draw, 1190, 1652, 0, $howmany);

//Apply the line height so that the reasoning can't go out of frame.
list($lines, $lineHeight) = wordWrapAnnotation($img, $draw, $reason, 1350);
for($i = 0; $i < count($lines); $i++)
    $img->annotateImage($draw, 200, 1795 + $i*$lineHeight, 0, $lines[$i]);

// Lets draw on Page 2
$img2->annotateImage($draw, 470, 240, 0, $addressthai);
$img2->annotateImage($draw, 600, 350, 0, $writtenby);
$img2->annotateImage($draw, 350, 450, 0, $addressno);
$img2->annotateImage($draw, 680, 450, 0, $addressroad);
$img2->annotateImage($draw, 1100, 450, 0, $tambon);
$img2->annotateImage($draw, 320, 555, 0, $amphoe);
$img2->annotateImage($draw, 950, 555, 0, $changwat);

// Lets combine Image 1 and Image 2 into one and set the file format
$combined->addImage($img);
$combined->addImage($img2);
$combined->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 = 'tm07-'.generateRandomString().'.pdf';

// Write this all out into a nifty .pdf
$combined->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 TM07 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 extension process at the Immigration.</p>
  <hr>
  <ul>
  <li><p class="mb-0">1 x Passport (Original)</p></li>
  <li><p class="mb-0">2 x Passport Photos</p></li>
  <li><p class="mb-0">1 x Copy of your Passport Information Page</p></li>
  <li><p class="mb-0">1 x Copy of your last entry stamp</p></li>
  <li><p class="mb-0">1 x 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">1 x Copy of your Visa (If you have one)</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>
  <p><b>NOTE:</b> This is a 2 page printout, remember to set your printer to print on both sides, Immigration may not be okay with 2 pieces of paper when they expect only 1 paper with 2 sides printed on.</p>
</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();

?>