<?php
    session_start();
    include "../../db.php";
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) )
        header("Location: logout.php");
   
?>
<!DOCTYPE html>
<html lang="en">
<head>
 <?php include "includes/meta.php"; ?> 
    

    <link href="css/all.min.css" rel="stylesheet" type="text/css">
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="css/alltable.css" rel="stylesheet">
    <link rel="stylesheet" href="vendor/croppie/croppie.css" />
    <link href="css/style.css" rel="stylesheet">



<!-- Favicons -->
  <link href="img/favicon.png" rel="icon">
  <link href="img/apple-touch-icon.png" rel="apple-touch-icon">

  
  <!-- Bootstrap CSS File -->
  <link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet">

  <!-- Libraries CSS Files -->
  <link href="lib/font-awesome/css/font-awesome.min.css" rel="stylesheet">
 <link rel="stylesheet" href="https://unpkg.com/placeholder-loading/dist/css/placeholder-loading.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

 
    
</head>

<body>

  <!--==========================
  Header
  ============================-->
  

  <!-- #header -->

  <!--==========================
    Intro Section
  ============================-->
<?php include "includes/header2.php"; ?>

       <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">Wallpaper</h1>
                            <p class="h5 mb-2 text-gray-800 text-center">   
                            </p>
                            <hr>

                                  
                                    <form class="user" method="post" enctype="multipart/form-data">
                                        <h4 class="mb-2 badge badge-secondary" data-toggle="collapse" data-target="#target" style="cursor:pointer;">Add New Wallpaper</h4>
                                        <p class="small"> <i class="fas fa-hand-point-up"></i> Tap Here to add New Wallpaper </p>
                                        <div class="collapse" id="target">
                                          
                                            <div class="form-group row">
                                                <div class="col-sm-12 mb-1 mb-sm-0">
                                                    <input type="text" class="form-control mb-2" id="stitle" placeholder="Slider Title" name="stitle">
                                                </div>
                                            </div>
                                            <div class="form-group row">
                                                <div class="col-sm-12 mb-1 mb-sm-0">
                                                    <div class="custom-file mb-2">
                                                        <input type="file" class="custom-file-input" name="sliderlgimage" id="file" accept="image/*" required>
                                                        <label class="custom-file-label" for="file">Select Wallpaper Image *  (Image size- 1500*450/2000*600)</label>
                                                    </div>
                                                </div>
                                            </div>
                                            <!-- <button type="submit" class="btn btn-primary btn-user m-2" name="new_slider">
                                                <i class="fas fa-user-plus"></i> Add New Slider
                                            </button> -->
                                            <a href="#target" data-toggle="collapse" class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i> Cancel </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                                   

<hr>
   <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">
                                <h4 class="mb-3 badge badge-secondary">Sliders</h4>

                                <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>Slider Index</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                    $sql = "SELECT * FROM slider WHERE sby = '$_SESSION[uid]' ORDER BY spos ASC";
                                                    $run = mysqli_query($con, $sql);

                                                    $c = 1;
                                                    while ( $rows = mysqli_fetch_assoc($run) ) {
                                                        $rows["slink"] == "" ? $slink = "<span class='badge badge-danger badge-pill'> <i class='fas fa-times-circle'></i> No Link </span>" : $slink = "<a href='$rows[slink]' target='_blank' class='badge badge-info badge-pill'> $rows[stitle] <i class='fas fa-share'></i> </a>";
                                                                $trimmedTitle = mb_strimwidth($rows['stitle'], 0, 20, "...");                                                       
                                                       echo "
                                                        <tr id='$rows[sid]'>
                                                            <td>
                                                            <p class='text-dark mb-0'><b>$c </b></p>
                                                            </td>
                                                            <td>
                                                            <p class='text-dark mb-0'><b>Title: </b>$trimmedTitle </p>
                                                               
                                                                <br>
                                                                <img src='$rows[slgimage]' height='50' data-toggle='modal' data-target='#show-img' class='showModal'>
                                                            </td>
                                                        ";
                                                        ?>
                                                            <td class='text-center align-middle'>
                                                                <!-- <a href='slider2.php?edit_id=$rows[sid]&sref=$rows[sref]&imgpath=$rows[slgimage]' class='m-2 btn btn-success btn-sm rounded-circle' title='Click to Edit'> <i class='fas fa-pencil-alt'></i> </a> -->

                                                                <a href='slider2.php?del_id=<?php echo $rows["sid"]; ?>&imgpath=<?php echo $rows["slgimage"]; ?>' 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>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>


            <?php include "includes/ft.php"; ?>



    <div class="modal fade" id="show-img" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <img src="" alt="sliderImage" id="image_modal" class="w-100">
                    <p class="small mt-3 mb-2" id="dimension"> <span class="font-weight-bold"> Name </span> : </p>
                    <p class="small mb-2" id="dimension"> <span class="font-weight-bold"> Dimension </span> : </p>
                    <p class="small mb-2" id="dimension"> <span class="font-weight-bold"> Size </span> : </p>
                </div>
                <div class="modal-footer">
                    <button type="close" class="btn btn-secondary" data-dismiss="modal"> Close </button>
                </div>
            </div>
        </div>
    </div>



    <div id="uploadimageModal" class="modal" role="dialog">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">

                <div class="modal-header">
                    <h4 class="modal-title"> Upload & Crop Image </h4>
                </div>

                <div class="modal-body">
                    <div class="row mx-0">
                        <div class="col-md-12 text-center">
                            <div id="image_demo" style="margin-top:10px;height:40%;width:1px;"></div>
                            <p class="small">scroll through mouse to zoom in or out</p>
                        </div>
                        <div class="col-md-12 text-center">
                            <button class="btn btn-success crop_image" id="cropppp">Crop & Upload Image</button>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" data-dismiss="modal">Close</button>
                </div>

            </div>
        </div>
    </div>




    <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 == 1500 && imgHeight == 450 || imgWidth == 2000 && imgHeight == 600 ) {
                                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 src="js/jquery.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="js/sweetalert2.min.js"></script>
    <script src="js/jquery.dataTables.min.js"></script>
    <script src="js/dataTables.bootstrap4.min.js"></script>
    <script src="js/datatables.mark.min.js"></script>
    <script src="vendor/croppie/croppie.js"></script>
    <script src="js/jquery-ui-custom.min.js"></script>
    <script src="js/custom.js"></script>
     <script src="js/mobile-nav/mobile-nav.js"></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);
            });$image_crop = $('#image_demo').croppie({
                enableExif: true,
                viewport: {
                    width: 2000,
                    height: 600,
                    type: '' //circle
                },
                boundary: {
                    width: 2015,
                    height: 615,
                }
            });$('#file').on('change', function () {
                var reader = new FileReader();
                reader.onload = function (event) {
                    $image_crop.croppie('bind', {
                        url: event.target.result
                    }).then(function () {
                        console.log('jQuery bind complete');
                    });
                }
                reader.readAsDataURL(this.files[0]);
                $('#uploadimageModal').modal('show');
            });$('.crop_image').click(function (event) {
                $('#cropppp').html('uploading <i class="fas fa-spinner fa-pulse"></i>');
                
                var stitle = $('#stitle').val();
                $image_crop.croppie('result', {
                    type: 'canvas',
                    size: 'viewport'
                }).then(function (response) {
                    $.ajax({
                        url: "slider2.php",
                        type: "POST",
                        data: {
                            "image": response,
                           
                            stitle: stitle
                        },
                        success: function (data) {
                            $('#uploadimageModal').modal('hide');
                            $('#uploaded_image').html(data);
                        }
                    });
                })
            });
        });

        // var $sortableCat = $("#catsList");

        // $sortableCat.sortable({
        //     stop: function ( event, ui ) {
        //         var parameters = $sortableCat.sortable( "toArray" );
        //         $.post("categories_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
        //                 });
        //             });
        //         });
        //     }
        // });

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

        $sortable.sortable({
            stop: function ( event, ui ) {
                var parameters = $sortable.sortable( "toArray" );
                $.post("slider_position.php",{value:parameters},function(result){
                    console.log("Position Complete");
                });
            }
        });
    </script>

</body>
</html>



<?php
    if ( isset($_GET["del_id"]) ) {

        unlink($_GET["imgpath"]);

        $del_sql = "DELETE FROM slider WHERE sid = '$_GET[del_id]'";

        if ( mysqli_query($con, $del_sql) ) {
            ?>
            <script>window.location = "slider2.php";</script>
            <?php
        } else {
            ?>
            <script>
                alert('OOPS !!!!');
                setTimeout(() => {
                    window.location = 'slider2.php';
                }, 500);
            </script>
          
            <?php
        }
    }
    if(isset($_POST["image"]))
    {
        $data = $_POST["image"];
       
        $stitle = $_POST["stitle"];
        $sref = rand()."_".time();

        $image_array_1 = explode(";", $data);

        $image_array_2 = explode(",", $image_array_1[1]);

        $data = base64_decode($image_array_2[1]);

        $imageName = '../upload/slider/'.rand() . '.png';

        file_put_contents($imageName, $data);
        function compress($source, $destination, $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, $destination, $quality);
            return $destination;
        }
        $destination_img = '../upload/slider/'.rand() . '.png';
        $d = compress($imageName, $destination_img, 40);
        unlink($imageName);
        $new_ins_sql = "INSERT INTO slider ( stitle, slgimage, sby, screated, sref) VALUES ( '$stitle', '$destination_img', '$_SESSION[uid]', '$currentTime', '$sref')";

        // echo "<pre>";print_r($new_ins_sql);exit();
        
        mysqli_query($con, $new_ins_sql);
    }
?>