<?php

date_default_timezone_set('Asia/Kolkata');

$currentDT = date('M j, Y g:i a');



if (isset($_POST['img_submit'])) {



    $sh_ref =$_SESSION['uid'].'-'.$_GET['h_ref'];

    $sh_id =$_SESSION['uid'];

    $teacher_id = $_POST['teacher_id'];



    if (empty($_POST['content']) AND empty($_FILES['file']['name'][0])) {

        ?>

            <script>

                alert('Empty Data');

            </script>

        <?php

        die();

    }

    

    $c_result = mysqli_query($con,"SELECT * FROM homework_img WHERE sh_id = '$_SESSION[uid]', hi_ref = '$_GET[h_ref]'");



    if (mysqli_num_rows($c_result)>0) {

        ?>

            <script>

                alert('Already Submitted. You Can Edit only.');

            </script>

        <?php

        die();

    }





    $j = 0;



    for ($i = 0; $i < count($_FILES['file']['name']); $i++) {//loop to get individual element from the array

        if ($j == 0) {

            $j = $j + 1;

            $content = $_POST['content'];

            insertImageDB($con,$j,$content,$_GET['h_ref'],$sh_ref,$sh_id,$teacher_id,$currentDT);

        }

        if ($j > 0) {

            $target_path = "../upload/homework_submit/"; //Declaring Path for uploaded images

            $validextensions = array("jpeg", "jpg", "png", "gif");  //Extensions which are allowed

            $ext = explode('.', basename($_FILES['file']['name'][$i]));//explode file name from dot(.) 

            $file_extension = end($ext); //store extensions in the variable



            $new_name = md5(uniqid()) . "." . $ext[count($ext) - 1];//set a new name of image



            $target_path = $target_path .$new_name ;//set the target path with a new name of image



            $j = $j + 1;//increment the number of uploaded images according to the files in array       

            

          if (($_FILES["file"]["size"][$i] < 1000000) && in_array($file_extension, $validextensions))  //Approx. 1000kb files can be uploaded.

          {



                $temp_name = $_FILES['file']['tmp_name'][$i];//set a Temp name of image

                $imageQuality= 20;



                if (compress_image($temp_name, $target_path, $imageQuality)) {//if Compressed file moved to uploads folder



                    insertImageDB($con,$j,$new_name,$_GET['h_ref'],$sh_ref,$sh_id,$teacher_id,$currentDT);



                    echo $j. ').<span id="noerror">Image uploaded successfully!.</span><br/><br/>';

                } else {//if file was not moved.

                    echo $j. ').<span id="error">please try again!.</span><br/><br/>';

                }





            } else {//if file size and file type was incorrect.

                echo $j. ').<span id="error">***Invalid file Size or Type***</span><br/><br/>';

            }

        }

       



    }



}



function compress_image($tempPath, $originalPath, $imageQuality){

  

    // Get image info 

    $imgInfo = getimagesize($tempPath); 

    $mime = $imgInfo['mime']; 

     

    // Create a new image from file 

    switch($mime){ 

        case 'image/jpeg': 

            $image = imagecreatefromjpeg($tempPath); 

            break; 

        case 'image/png': 

            $image = imagecreatefrompng($tempPath); 

            break; 

        case 'image/gif': 

            $image = imagecreatefromgif($tempPath); 

            break; 

        default: 

            $image = imagecreatefromjpeg($tempPath); 

    } 

     

    // Save image 

    imagejpeg($image, $originalPath, $imageQuality);    

    // Return compressed image 

    return $originalPath; 



}



function insertImageDB($con,$pos,$insImg,$homeworkRef,$sh_ref,$sh_id,$teacher_id,$currentDT){  



      echo  $img_sql = "INSERT INTO homework_img (hi_name,hi_pos, hi_ref, sh_ref, sh_id, teacher_id,hi_submitDT) VALUES ('$insImg','$pos','$homeworkRef','$sh_ref', '$sh_id' , '$teacher_id','$currentDT')";

        if(mysqli_query($con, $img_sql)){

            ?>

            <script>

                alert('Submit Successfully');

                window.location = 'submit-homework.php';

            </script>

            <?php

        }

}



?>