<?php
    session_start();
   
    include "../../db.php";
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');
   
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <?php include "includes/meta.php"; ?>             
    <?php include "includes/css.php"; ?>
    <link href="css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/alltable.css" rel="stylesheet"> 
    <link rel="stylesheet" href="vendor/croppie/croppie.css" /> 
    
 
    
</head>

<body>

  <!--==========================
  Header
  ============================-->
  
  <?php include "includes/header2.php"; ?>
  <!-- #header -->

  <!--==========================
    Intro Section
  ============================-->
<div class="container">
            <div class="row mx-0 just ify-content-center">
                <div class="col-12 col-sm-12 col-md-12">
                        <div class="card-body">

                        
                            <h1 class="h3 mb-2 text-gray-800 text-center" style="margin-top: 90px">Gallery</h1>
                            <p class="h5 mb-2 text-gray-800 text-center">( Photo Upload )</p>
                            <hr>
              <form method='post' action='' enctype='multipart/form-data'>
               <input type="text" class="form-control mb-2" id="timage" placeholder="Photo Title" name="timage">
                <input type='file' name='image' class="form-control"><br>
                <input type='submit' value='Upload Image' class="btn btn-primary" name='upload'>    
              </form>
<br><hr>
          </div>
        </div>
      </div>
    </div>


<div class="container">
            <div class="row mx-0 just ify-content-center">
                <div class="col-12 col-sm-12 col-md-12">
                            <div class="row m-0">
                             

                                <div class="col-md-12 p-0">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-bordered table-sm" id="thisismytable">
                                            <thead>
                                                <tr>
                                                    <th>No.</th>
                                                    <th>Gallery Index</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                    $sql = "SELECT * FROM gallery WHERE tby = '$_SESSION[uid]' ORDER BY id DESC";
                                                    $run = mysqli_query($con, $sql);

                                                    $c = 1;
                                                    while ( $rows = mysqli_fetch_assoc($run) ) {
                                                                                                            
                                               echo "
                                                        <tr id='$rows[id]'>
                                                            <td>
                                                            <span class='badge badge-info badge-pill'>$c</span>
                                                            </td>
                                                            <td>
                                                            <p class='text-dark mb-0'><b>Title: </b> $rows[timage] </p>
                                                           <br>
                                                            
                                                                <img src='$rows[image]' height='50' data-toggle='modal' data-target='#show-img' class='showModal'>
                                                            </td>
                                                        ";
                                                        ?>
                                                            <td class='text-center align-middle'>
                                                               
                                                                <a href='gallery.php?del_id=<?php echo $rows["id"]; ?>&imgpath=<?php echo $rows["image"]; ?>' class='delete m-2 btn btn-danger btn-sm rounded-circle' title='Click to Delete'> <i class='fas fa-trash'></i> </a>
                                                            </td>
                                                        </tr>
                                                        <?php
                                                        $c++;
                                                    }
                                                ?>
                                            </tbody>
                                        </table><br><br><br><br>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
            </div>
<br><br>
               <?php include "includes/ft.php"; ?>
               <?php include "includes/js.php"; ?>

     <script>
        function checkFileDetails() {
            var fi = document.getElementById('file');
            if (fi.files.length > 0) {
                for (var i = 0; i <= fi.files.length - 1; i++) {
                    var fileName, fileExtension, fileSize, fileType, dateModified;
                    fileName = fi.files.item(i).name;
                    fileExtension = fileName.replace(/^.*\./, '');
                    if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
                        readImageFile(fi.files.item(i));
                    }
                }
                function readImageFile(file) {
                    var reader = new FileReader();
                    reader.onload = function (e) {
                        var img = new Image();
                        img.src = e.target.result;
                        img.onload = function () {
                            var imgWidth = this.width;
                            var imgHeight = this.height;

                            if ( imgWidth == 1200 && imgHeight == 512 || imgWidth == 1500 && imgHeight == 640 ) {
                                var imgCheck = "<i class='fas fa-check-circle text-success'></i>";
                            } else {
                                var imgCheck = "<i class='fas fa-times-circle text-danger'></i>";
                            }
                            document.getElementById('fileInfo').innerHTML =
                                document.getElementById('fileInfo').innerHTML + '<br> ' +
                                'Name: <b>' + file.name + '</b> <br>' +
                                'Size: <b>' + Math.round((file.size / 1024)) + '</b> KB <br>' +
                                'Dimension: <b>' + imgWidth + '</b> x <b>' + imgHeight + '</b> ' + imgCheck + ' <br>';
                        }
                    };
                    reader.readAsDataURL(file);
                }
            }
        }
    </script>

   <script>
        $(document).ready(function(){
            $('#thisismytable').DataTable();
            $('#show-img').on('show.bs.modal', function (e) {
                var src = $(e.relatedTarget).attr('src');
                $(this).find('.modal-body > img').attr('src', src);
            });
        });

        var $sortable = $("#thisismytable > tbody");

        $sortable.sortable({
            stop: function ( event, ui ) {
                var parameters = $sortable.sortable( "toArray" );
                $.post("slider_position.php",{value:parameters},function(result){
                    $(document).ready(function() {
                        const Toast = Swal.mixin({
                            toast: true,
                            position: 'bottom',
                            showConfirmButton: false,
                            timer: 2000
                        });
                        Toast.fire({
                            type: 'success',
                            title: result
                        });
                    });
                });
            }
        });
    </script> 
</body>
</html>

<?php
    
   if(isset($_POST['upload'])){

       // Getting file name
       $filename = $_FILES['image']['name'];
         
       // Valid extension
       $valid_ext = array('png','jpeg','jpg');

      
     $photoExt1 = @end(explode('.', $filename)); // explode the image name to get the extension
     $phototest1 = strtolower($photoExt1);
      
     $new_profle_pic = '../upload/gallery/'.time().'.'.$phototest1;
      
       // Location
       $location = "".$new_profle_pic;

       // file extension
       $file_extension = pathinfo($location, PATHINFO_EXTENSION);
       $file_extension = strtolower($file_extension);

       // Check extension
       if(in_array($file_extension,$valid_ext)){  

            // Compress Image
            compressedImage($_FILES['image']['tmp_name'],$location,20);
        
        //Here i am enter the insert code in the step ........

        }
      else
        {
                echo "File format is not correct.";
        }
    
    

   $timage = mysqli_real_escape_string($con, strip_tags($_POST['timage']));

 $ins_sql = "INSERT INTO gallery (image, timage, tby, tcreat)VALUES ('$new_profle_pic','$timage','$_SESSION[uid]','$currentTime')";
 if( mysqli_query($con, $ins_sql) ){
        ?>
        <script>
            alert("Details Sent Successfully");
            window.location = "gallery.php";
        </script>
        <?php
    }
    else{
        ?>
        <script>
            alert("Something's Wrong");
            window.location = "index.php";
        </script>
        <?php
    }
  
  
   }
?>
<?php
  if ( isset($_GET["del_id"]) ) {
           unlink($_GET["imgpath"]);
        $del_sql = "DELETE FROM gallery WHERE id = '$_GET[del_id]'";

        if ( mysqli_query($con, $del_sql) ) {
            ?>
            <script>
            window.location = "gallery.php";</script>
            <?php
        } else {
            ?>
            <script>
                alert('OOPS !!!!');
                setTimeout(() => {
                    window.location = 'gallery.php';
                }, 1200);
            </script>
            <?php
        }
        
    }

   
?>
<?php

// Compress image
    function compressedImage($source, $path, $quality) {

            $info = getimagesize($source);

            if ($info['mime'] == 'image/jpeg') 
                $image = imagecreatefromjpeg($source);

            elseif ($info['mime'] == 'image/gif') 
                $image = imagecreatefromgif($source);

            elseif ($info['mime'] == 'image/png') 
                $image = imagecreatefrompng($source);

            imagejpeg($image, $path, $quality);

    }

?>