<?php
require_once('connection.php');
session_start();
$db=$con;
$tableName='gallery';
// upload image on submit
if(isset($_POST['submit'])){ 
    echo upload_image($tableName); 
}
  function upload_image($tableName){
   
    $uploadTo = "uploads/"; 
    $allowedImageType = array('jpg','png','jpeg','gif');
    $imageName = array_filter($_FILES['image_gallery']['name']);
    $imageTempName=$_FILES["image_gallery"]["tmp_name"];
    $tableName= trim($tableName);
if(empty($imageName)){ 
   echo '<script>alert("Nepieciešams izvēlēties bildi")</script>';
}else if(empty($tableName)){
   $error="Nav tabulas nosaukuma";
   return $error;
}else{
   $error=$savedImageBasename='';
   foreach($imageName as $index=>$file){
         
    $imageBasename = basename($imageName[$index]);
    $imagePath = $uploadTo.$imageBasename; 
    $imageType = pathinfo($imagePath, PATHINFO_EXTENSION); 
 if(in_array($imageType, $allowedImageType)){ 
    // Upload image to server 
    if(move_uploaded_file($imageTempName[$index],$imagePath)){ 
        
    // Store image into database table
     $savedImageBasename .= "('".$imageBasename."','".$imagePath."','".$_SESSION['id']."')";     
    }else{ 
     $error = 'Nesanāca ielādēt, pamēģiniet vēlreiz';
  } 
}else{
   echo '<script>alert("Neatļauts faila formāts")</script>';
 }
 }
    save_image($savedImageBasename, $tableName);
}
      
}
    // File upload configuration 
 function save_image($savedImageBasename, $tableName){
      
      global $db;
      if(!empty($savedImageBasename))
      {
      $value = trim($savedImageBasename, ',');
      $id_user=$_SESSION['id'];
      $saveImage="INSERT INTO ".$tableName." (image_name,image_path,id_user) VALUES ".$value."";
      $exec= $db->query($saveImage);
      if($exec){

       }else{
        echo  "Error: " .  $saveImage . "<br>" . $db->error;
       }
       header('Location:image-gallery.php');
      }
    }     
    
?>