<?php
include "include/db.php";
include "include/auth.php";
if($user_type == 'admin'){
    $active_user_id = "admin_id = $admin_id,";
}elseif($user_type == 'staff'){
    $active_user_id = "employee_id = $employee_id,";
}
$time = date("Y-m-d H:i:s");

if(isset($_REQUEST['invoice_item_i']) && isset($_FILES["uploadImage"])){
    if(strlen($_REQUEST['invoice_item_i'])>0){
        $invoice_item_id = $_REQUEST['invoice_item_i'];
        $err_string = "";
        $images = count($_FILES["uploadImage"]["tmp_name"]);
        $fetch_bid_details12 = "SELECT * FROM invoice_item WHERE is_delete IS NULL AND invoice_item_id = $invoice_item_id";
        $fetch_bid_details_run12 = mysqli_query($conn, $fetch_bid_details12);

        if(mysqli_num_rows($fetch_bid_details_run12) == 1){
            $fetch_bid_details_row12 = mysqli_fetch_array($fetch_bid_details_run12);
            $maps_id = $fetch_bid_details_row12['maps_id'];
            $invoice_id = $fetch_bid_details_row12['invoice_id'];
            $query_fetch_maps_amount = "SELECT * FROM maps WHERE maps_id = $maps_id";
            $run_fetch_maps_amount = mysqli_query($conn, $query_fetch_maps_amount);
            if(mysqli_num_rows($run_fetch_maps_amount) ==1){
                while($row_fetch_maps_amount = mysqli_fetch_array($run_fetch_maps_amount)){
                    $invoice_maps_name = $row_fetch_maps_amount['maps_name'];
                }
            }   
       
            $bid_item_image = "SELECT * FROM invoice_actual_image WHERE item_id = $invoice_item_id";
            $bid_item_image_run = mysqli_query($conn, $bid_item_image);

            $e_count12 = mysqli_num_rows($bid_item_image_run); 

            $e_count = $e_count12; 

            $preview_start = $e_count12 + 1;           
        }else{
            echo 'invalid1';    
        }
        
        $e_count122 = 31 - $e_count12;

        if($images > 0 && $images < $e_count122){                 
            $errors = array();
            $uploadedFiles = array();  
            $err_count = 0;
            $up_count = 0; 
            $pre_array = array();
            
            foreach($_FILES["uploadImage"]["tmp_name"] as $key=>$tmp_name){   
                $temp = $_FILES["uploadImage"]["tmp_name"][$key];
                $name = $_FILES["uploadImage"]["name"][$key];                
                
                $final_res_array = array("bid_item_i"=>"$invoice_item_id");
                
                    $uniqueId= time().'-'.mt_rand();
                    $temp = explode(".", $_FILES["uploadImage"]["name"][$key]);
                    $ref_photo = $uniqueId . '.' . end($temp);

                    $query_act_photo_insert = "INSERT INTO invoice_actual_image SET image_name = '$ref_photo' ,item_id = $invoice_item_id";

                    $run_act_photo_insert = mysqli_query($conn, $query_act_photo_insert);
                    if(mysqli_affected_rows($conn)==0){
                        $err_count++;

                        $err_string = $err_string . " $name not uploaded due to Code x0004. ";
                      
                    }  

                    $target_dir = getcwd().DIRECTORY_SEPARATOR. "maps_act_image/";
                    $target_file = $target_dir . $ref_photo;
                    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

                    $check = getimagesize($_FILES["uploadImage"]["tmp_name"][$key]);
                    if($check !== false) {         

                        if ($_FILES["uploadImage"]["size"][$key] < 2024000) {
                                    
                            if($imageFileType == "jpg" || $imageFileType == "png" || $imageFileType == "jpeg") {  
                                if (move_uploaded_file($_FILES["uploadImage"]["tmp_name"][$key], $target_file)) {
                                    $e_count++;

                                    $path = "maps_act_image.php?i=".$ref_photo;
                                    
                                    $preview = "<img src='$path' style= 'max-height:50px; max-width:150px' />";
                                    $preview++;
                                    $up_count++;                                  
                                    
                                    array_push($pre_array,"$preview");
                                } else {
                                    $ref_photo = "";                                    
                                    
                                    $err_count++;

                                    $err_string = $err_string . " $name not uploaded due to Code x0003";       
                                }    
                            }else{
                                $ref_photo = "";
                               
                                $err_count++;

                                $err_string = $err_string . " $name is not of JPG, JPEG or PNG format."; 
                            }
                                        
                        }else{
                            $ref_photo = "";
                            $err_count++;
                            $err_string = $err_string . " $name file size is larger than 2 MB.";     
                        }
                    } else {
                        $ref_photo = "";                                           
                        $err_count++;
                        $err_string = $err_string . " Upload failed. $name is not a image.";
                    }
            }
           
            $total_up = $up_count + $e_count12;

            $query_insert_log = "INSERT INTO change_log SET $active_user_id change_text = '$up_count images added to $invoice_maps_name', type = 'invoice', item_id = $invoice_id, time = '$time'"; 
            $run_insert_log = mysqli_query($conn, $query_insert_log);

            $err_array = array("err_count"=>"$err_count", "up_count"=>"$up_count","preview_start"=>"$preview_start","err_string"=>"$err_string", "total_up"=>"$total_up");
            $up_array = array("preview" => $pre_array);
            $final_res_array = array_merge($final_res_array, $up_array);
            $final_res_array = array_merge($final_res_array, $err_array);
            echo json_encode($final_res_array);

        }else{
            echo 'invalid3';    
        }       

    }else{
        echo 'invalid2';
    }
}else{
    echo 'invalid1';
}
?>