<?php
if (isset($_POST['apply'])) {
    $total = count($_FILES['vfile']['name']);
    $fname = $_POST['fname'];
    $mname = $_POST['mname'];
    $lname = $_POST['lname'];
    $vdate = $_POST['vdate'];
    $vemail = $_POST['vemail'];
    $vnum = $_POST['vnum'];
    // $vsub = $_POST['vsub'];
    $message = $_POST['message'];

    // Loop through each file
    $urls = array();
    for ($i = 0; $i < $total; $i++) {

        //Get the temp file path
        $tmpFilePath = $_FILES['vfile']['tmp_name'][$i];
        $filename = $_FILES['vfile']['name'][$i];

        //Make sure we have a file path
        if ($tmpFilePath != "") {
            $rnd = bin2hex(random_bytes(10));
            $ext = pathinfo($filename, PATHINFO_EXTENSION);
            if ($ext == 'pdf' || $ext == 'doc' || $ext == 'jpg') {
                $newFilePath = "uploads/" . $rnd . "." . $ext;
                if (move_uploaded_file($tmpFilePath, $newFilePath)) {
                    array_push($urls, $newFilePath);
                }
            } elseif ($ext == 'png' || $ext == 'jpeg' || $ext == 'docx') {
                $newFilePath = "uploads/" . $rnd . "." . $ext;
                if (move_uploaded_file($tmpFilePath, $newFilePath)) {
                    array_push($urls, $newFilePath);
                }
            } else {
                header("Location: ../visa-application.php?status=unsupported");
                exit();
            }
        }
    }


    $to = "vinaychaudhary.sps@gmail.com";
    $subject = "Visa Application [$fname]";

    $message = "
    <html>
    <head>
    <title>Visa Application</title>
    </head>
    <body>
    <p>
    Visa Application :
    <br>
    name : $fname<br>
    middle:  $mname<br>
    Last: $lname <br>
    Date: $vdate<br>
    Email: $vemail<br>
    Number: $vnum<br>
    Message: $message<br>
    
    
    ";
    foreach ($urls as $value) {
        $message .=  "File Url: $value <br>";
    }
    $message .= "</p>
    </body>
    </html>";

    // Always set content-type when sending HTML email
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

    // More headers
    $headers .= 'From: noreply@dubaitourvisa.com' . "\r\n";
    $headers .= 'Cc: myboss@example.com' . "\r\n";

    $run = mail($to, $subject, $message, $headers);
    if ($run) {
        header("Location: ../visa-application.php?status=submitted");
    } else {
        // foreach ($urls as $value) {
        //     if (is_file($value))
        //         unlink($value);
        // }
        header("Location: ../visa-application.php?status=failed");
    }
}
