<?php
include("../../connection/Functions.php");
$operation = new Functions();



//add slider image
if(isset($_FILES['picture']) ){
    
    $images = $_FILES['picture']['name'];
    $image=strtolower(pathinfo($images,PATHINFO_EXTENSION));
    $filename=rand(1000, 1000000).".".$image;
    /* Location */
    $location = "../../images/ads/".$filename;
    $uploadOk = 1;
    $imageFileType = pathinfo($location,PATHINFO_EXTENSION);
    /* Valid Extensions */
    $valid_extensions = array("jpg","jpeg","png");
    /* Check file extension */
    if( !in_array(strtolower($imageFileType),$valid_extensions) ) {
       $uploadOk = 0;
    }
    
    
    if($_FILES['picture']['size'] > 3000000 ){
        echo json_encode(array("code"=>2,"msg"=>"✖ File must be less than 3mb!"));
        die();
    }
    
    
    if($uploadOk == 0){
         echo json_encode(array("code"=>2,"msg"=>"✖ File type not supported, try jpg, jpeg or png!"));
    }else{
       /* Upload file */
       if(move_uploaded_file($_FILES['picture']['tmp_name'],$location)){
            
               $table = "adverts";
               $data = [
                 
                   'img_url' => "$filename"  
               ];               
               if($operation->insertData($table,$data) == 1){
                   echo json_encode(array("code"=>1,"msg"=>"Success, redirecting, please wait!"));
               }else{
//                   echo 0;
                   echo json_encode(array("code"=>2,"msg"=>"✖ An error occured while saving, please try again later!"));
               }
               
           
          
       }else{
          echo json_encode(array("code"=>2,"msg"=>"✖ An error occured while saving the picture!"));
       }
    }
    //edit slider image
}elseif(isset($_POST['id']) && !empty($_POST['id'])){
    $id = addslashes($_POST['id']);
    $where = "advert_id = '$id'";
    $table = "adverts";
    //get image name
    $checkImg = $operation->retrieveSingle("SELECT *FROM adverts WHERE advert_id = '$id'");
    
    $directory = "../../images/ads/".$checkImg['img_url'];
   if(unlink($directory)){
        if($operation->deleteData($table,$where) == 1){
            echo json_encode(array("code"=>1,"msg"=>"Success, refreshing, please wait..."));
        }else{
            echo json_encode(array("code"=>2,"msg"=>"An error occured, please try again later"));
        }
   }else{
        echo json_encode(array("code"=>2,"msg"=>"✖ An error occured while saving the picture!"));
   }
    
    
    
}


?>