<?php

//var_dump($_FILES);
//echo $_GET["appid"];
//die();

if (isset($_FILES['files']) && !empty($_FILES['files'])) {
    
    $no_files = count($_FILES["files"]['name']);
    $filelist="";

    include('../db_con.php');

    $result0 = mysqli_query($con,"SELECT refer_no FROM applicant_table WHERE app_id='".$_GET['appid']."'");
    $row0 = mysqli_fetch_array($result0);
    $uid=$row0["refer_no"];
    
    if($_GET["dtype"]==1) {
        
        $folder="uploads/passportcopy/";
    }

    if($_GET["dtype"]==2) {
        
        $folder="uploads/visaappform/";
    }

    for ($i = 0; $i < $no_files; $i++) {
        
        if ($_FILES["files"]["error"][$i] > 0) {
            echo "Error: " . $_FILES["files"]["error"][$i] . "<br>";
        } 
        else {

            
            $file=$_FILES["files"]["name"][$i];
            $file = $uid."-".str_replace(' ', '_', $file);
            $allowed =  array('jpg','jpeg','pdf','doc','docx','zip');           
            $ext = pathinfo($file, PATHINFO_EXTENSION);
            
            if(!in_array($ext,$allowed)){
                echo "Unsupported filetype uploaded.\n";
                
            }

            elseif (filesize($_FILES["files"]["tmp_name"][$i]) > 3000000) {
                echo "Sorry, your file is too large.\n";
                //$uploadOk = 0;
                }

            elseif (file_exists($folder . $file)) {
                echo 'File already exists : '. $file;
            }

            else {
                                
                move_uploaded_file($_FILES["files"]["tmp_name"][$i], $folder.$file);

                $sql = "insert into app_docu_table (vr_id, vrcreate_datetime, doc_name, file, doc_type, app_id) values ('', '$now', '$file', '$file', '$_GET[dtype]', '$_GET[appid]')";                              
                $filelist=$filelist."#".$file." ";//var_dump($sql) or die();
                                    //echo $sql;
                $result = mysqli_query($con,$sql);
                
                if($i==$no_files-1){
                    echo "<span style='color:green;'>All Files successfully uploaded</span> <button class='btn btn-primary btn-xs' onclick='reloadFunction()''>View files</button>";
                    
                    include 'methodlist.php';
                    session_start();

                    if($_GET["dtype"]==1) $doctype="Passport copy";
                    if($_GET["dtype"]==2) $doctype="Visa Application Form";

                    ver_update_history('<b>'.$no_files.' '.$doctype.' </b>('.$filelist.') have been uploaded by', $_GET["appid"], $con);


                }
            }
        }
    }
} 
else {
    echo '<span style=color:red;>Please choose at least one file</span>';
}
    
/* 
 * End of script
 */
?>