<?php

session_start();

?>

<!DOCTYPE html>
<html>
<head>
<title>TM08 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['country']) || 
empty($_POST['occupation']) ||
empty($_POST['addressno']) || 
empty($_POST['addressroad']) || 
empty($_POST['tambon']) || 
empty($_POST['amphoe']) || 
empty($_POST['changwat']) || 
empty($_POST['pcountry']) || 
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['reentry']) || 
empty($_POST['pvisa']) || 
empty($_POST['intto']) || 
empty($_POST['intdepdd']) || 
empty($_POST['intdepyyyy']) || 
empty($_POST['intby']) || 
empty($_POST['intfor']) || 
empty($_POST['intreturndd']) || 
empty($_POST['intreturnmm']) || 
empty($_POST['intreturnyyyy']) || 
empty($_POST['previsaissue']) || 
empty($_POST['previsadd']) || 
empty($_POST['previsamm']) || 
empty($_POST['previsayyyy']) || 
empty($_POST['iarriveddd']) || 
empty($_POST['iarrivedmm']) || 
empty($_POST['iarrivedyyyy']) || 
empty($_POST['permitteddd']) || 
empty($_POST['permittedmm']) || 
empty($_POST['permittedyyyy']) || 
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'] ?? '');

$dd            = (int) ($_POST['dd'] ?? 0);
$mm            = trim($_POST['mm'] ?? '');
$yyyy          = (int) ($_POST['yyyy'] ?? 0);

// Calculate age from birthdate (if valid)
$age = null;
if ($yyyy > 0 && $mm && $dd > 0) {
    try {
        $birthDate = new DateTime("$yyyy-$mm-$dd");
        $today = new DateTime();
        $age = $today->diff($birthDate)->y;
    } catch (Exception $e) {
        $age = null;
    }
}

$placeofbirth  = trim($_POST['placeofbirth'] ?? '');
$nationality   = trim($_POST['nationality'] ?? '');
$country       = trim($_POST['country'] ?? '');
$occupation    = trim($_POST['occupation'] ?? '');
$addressno     = trim($_POST['addressno'] ?? '');
$addressroad   = trim($_POST['addressroad'] ?? '');
$tambon        = trim($_POST['tambon'] ?? '');
$amphoe        = trim($_POST['amphoe'] ?? '');
$changwat      = trim($_POST['changwat'] ?? '');

$pcountry      = trim($_POST['pcountry'] ?? '');
$pno           = trim($_POST['pno'] ?? '');
$pidd          = (int) ($_POST['pidd'] ?? 0);
$pimm          = trim($_POST['pimm'] ?? '');
$piyyyy        = (int) ($_POST['piyyyy'] ?? 0);
$plocation     = trim($_POST['plocation'] ?? '');

// Handle possible NULL string values gracefully
$pvdd          = ($_POST['pvdd'] ?? '') !== "NULL" ? (int) ($_POST['pvdd'] ?? 0) : '';
$pvmm          = ($_POST['pvmm'] ?? '') !== "NULL" ? trim($_POST['pvmm'] ?? '') : '';
$pvyyyy        = ($_POST['pvyyyy'] ?? '') !== "NULL" ? (int) ($_POST['pvyyyy'] ?? 0) : '';

$reentry       = trim($_POST['reentry'] ?? '');
$intto         = trim($_POST['intto'] ?? '');
$intdepdd      = (int) ($_POST['intdepdd'] ?? 0);
$intdepmm      = trim($_POST['intdepmm'] ?? '');
$intdepyyyy    = (int) ($_POST['intdepyyyy'] ?? 0);
$intby         = trim($_POST['intby'] ?? '');
$intfor        = trim($_POST['intfor'] ?? '');

$intreturndd   = (int) ($_POST['intreturndd'] ?? 0);
$intreturnmm   = trim($_POST['intreturnmm'] ?? '');
$intreturnyyyy = (int) ($_POST['intreturnyyyy'] ?? 0);

$pvisa         = trim($_POST['pvisa'] ?? '');
$previsaissue  = trim($_POST['previsaissue'] ?? '');
$previsadd     = (int) ($_POST['previsadd'] ?? 0);
$previsamm     = trim($_POST['previsamm'] ?? '');
$previsayyyy   = (int) ($_POST['previsayyyy'] ?? 0);

$iarriveddd    = (int) ($_POST['iarriveddd'] ?? 0);
$iarrivedmm    = trim($_POST['iarrivedmm'] ?? '');
$iarrivedyyyy  = (int) ($_POST['iarrivedyyyy'] ?? 0);

$permitteddd   = (int) ($_POST['permitteddd'] ?? 0);
$permittedmm   = trim($_POST['permittedmm'] ?? '');
$permittedyyyy = (int) ($_POST['permittedyyyy'] ?? 0);

// 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_tm8_Page_1.jpg");
$img2 = new Imagick("form_tm8_Page_2.jpg");

// 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

//THIS IS DONE
$img->annotateImage($draw, 1200, 400, 0, $writtenat);

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

$img->annotateImage($draw, 280, 870, 0, $middlename);
$img->annotateImage($draw, 820, 870, 0, $nationality);
$img->annotateImage($draw, 1100, 870, 0, $age);
$img->annotateImage($draw, 1350, 870, 0, $dd);

$img->annotateImage($draw, 280, 965, 0, $mm);
$img->annotateImage($draw, 530, 965, 0, $yyyy);
$img->annotateImage($draw, 800, 965, 0, $placeofbirth);
$img->annotateImage($draw, 1260, 965, 0, $country);

$img->annotateImage($draw, 280, 1060, 0, $occupation);
$img->annotateImage($draw, 850, 1060, 0, $addressno);
$img->annotateImage($draw, 1200, 1060, 0, $addressroad);

$img->annotateImage($draw, 350, 1160, 0, $tambon);
$img->annotateImage($draw, 820, 1160, 0, $amphoe);
$img->annotateImage($draw, 1180, 1160, 0, $changwat);

if($reentry == "single") { 
        $img->annotateImage($draw, 337, 1394, 0, "X");
} else { 
        $img->annotateImage($draw, 737, 1394, 0, "X");
}

$img->annotateImage($draw, 800, 1475, 0, $intto);

$img->annotateImage($draw, 700, 1565, 0, $intdepdd);
$img->annotateImage($draw, 950, 1565, 0, $intdepmm);
$img->annotateImage($draw, 1300, 1565, 0, $intdepyyyy);

$img->annotateImage($draw, 350, 1655, 0, $intby);
$img->annotateImage($draw, 760, 1655, 0, $intfor);

$img->annotateImage($draw, 650, 1750, 0, $intreturndd);
$img->annotateImage($draw, 950, 1750, 0, $intreturnmm);
$img->annotateImage($draw, 1300, 1750, 0, $intreturnyyyy);

$img->annotateImage($draw, 285, 1955, 0, $pcountry);
$img->annotateImage($draw, 670, 1955, 0, $plocation);
$img->annotateImage($draw, 1000, 1955, 0, $pno);
$img->annotateImage($draw, 1320, 1955, 0, $pidd);

$img->annotateImage($draw, 280, 2050, 0, $pimm);
$img->annotateImage($draw, 620, 2050, 0, $piyyyy);
$img->annotateImage($draw, 950, 2050, 0, $pvdd);
$img->annotateImage($draw, 1100, 2050, 0, $pvmm);
$img->annotateImage($draw, 1350, 2050, 0, $pvyyyy);

// Ends here

if($pvisa == "nonimm") { 
        $img2->annotateImage($draw, 338, 380, 0, "X");
} elseif($pvisa == "tourist") { 
        $img2->annotateImage($draw, 836, 380, 0, "X");
} elseif($pvisa == "transit") { 
        $img2->annotateImage($draw, 1240, 380, 0, "X");
} else {
        $img2->annotateImage($draw, 338, 475, 0, "X");
}

$img2->annotateImage($draw, 300, 555, 0, $previsaissue);
$img2->annotateImage($draw, 780, 555, 0, $previsadd);
$img2->annotateImage($draw, 1030, 555, 0, $previsamm);
$img2->annotateImage($draw, 1330, 555, 0, $previsayyyy);

$img2->annotateImage($draw, 700, 660, 0, $iarriveddd);
$img2->annotateImage($draw, 950, 660, 0, $iarrivedmm);
$img2->annotateImage($draw, 1330, 660, 0, $iarrivedyyyy);

$img2->annotateImage($draw, 580, 765, 0, $permitteddd);
$img2->annotateImage($draw, 775, 765, 0, $permittedmm);
$img2->annotateImage($draw, 1020, 765, 0, $permittedyyyy);



//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 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 = 'tm08-'.generateRandomString().'.pdf';
//$pdfFilename = 'tm08-test.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 TM08 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 re-entry 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 Copy of your visa page</p></li>
    <li><p class="mb-0">1 x Copy of your TM06 Departure Card (White slip)</p></li>
    <li><p class="mb-0">Fee: 1000THB for Single Entry, 3800THB for Multi Entry(Fees at Airport can be higher)</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();

?>