<?php
    session_start();
    include "../../db.php";
    include "includes/functions.php";

    // if ( !isset($_SESSION['userId']) && !isset($_SESSION['userReference']) && !isset($_SESSION['userType']) && !isset($_COOKIE['loginStatus']) )
    //     header("Location: logout.php");
    // if ( $_COOKIE['loginStatus'] != 1 )
    //     header("Location: logout.php");
    // if ( $_SESSION['userType'] == "customer" || $_SESSION['userType'] == "seller" )
    //     header("Location: logout.php");
    // if ( $_SESSION['userType'] != "admin_4312" )
    //     header("Location: logout.php");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Admin Panel</title>

    <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 href="css/style.css" rel="stylesheet">
</head>
<body id="page-top" class="mt-55">

<div class="overlay"></div>

    <div id="wrapper">

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

        <div id="content-wrapper" class="d-flex flex-column">

            <div id="content">

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

                <div class="container-fluid px-0">

                    <div class="card shadow mb-4">
                        <div class="card-body">

                        
                            <h1 class="h3 mb-2 text-gray-800 text-center text-sm-left">Sliders</h1>
                            <hr>

                            <?php
                                if ( isset($_GET["edit_id"]) ) {
                                    $edit_run = mysqli_query($conn, "SELECT * FROM slider WHERE sliderId = '$_GET[edit_id]'");
                                    $edit_row = mysqli_fetch_assoc($edit_run);

                                    $edit_row["approve"] == 1 ? $liveSlideWarning = '<div class="row m-0"><h4 class="mb-3 badge badge-danger" style="font-size: 20px;">You are editing a Live Slide</h4></div>' : $liveSlideWarning = '';
                                    ?>
                                    <form class="user" method="post" enctype="multipart/form-data">
                                        <h4 class="mb-3 badge badge-secondary">Edit Slide</h4>
                                        <?php echo $liveSlideWarning; ?>
                                        <div class="form-group row">
                                            <div class="col-sm-12 mb-1 mb-sm-0">
                                                <input type="text" class="form-control mb-2" id="sliderLink" placeholder="Link for Slider" name="sliderLink" value="<?php echo $edit_row["sliderLink"]; ?>">
                                                <p class="small text-muted">must provide a valid link</p>
                                            </div>
                                        </div>
                                        <div class="form-group row">
                                            <div class="col-sm-12 mb-1 mb-sm-0">

                                                <img src="<?php echo $edit_row["slidersmimage"]; ?>" alt="sliderImage" height="100" class="mb-2">

                                                <div class="custom-file mb-2">
                                                    <input type="file" class="custom-file-input" name="sliderlgimage" id="file" accept="image/*" onchange="checkFileDetails()" value="">
                                                    <label class="custom-file-label" for="file">Select Slider Image</label>
                                                </div>
                                                <p class="small text-muted">Image should be in JPG / JPEG format & Resolution of <strong>1200 X 512</strong> or <strong>1500 X 640</strong></p>
                                                <p id="fileInfo" class="small"></p>
                                            </div>
                                        </div>
                                        <input type="hidden" name="sliderReference" value="<?php echo $edit_row["sliderReference"]; ?>">
                                        <button type="submit" class="btn btn-success btn-user m-2" name="edit_slide">
                                            <i class="far fa-image"></i> Update Slide
                                        </button>
                                        <a href="slider.php" class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i> Cancel </a>
                                    </form>
                                    <?php
                                } else {
                                    ?>
                                    <form class="user" method="post" enctype="multipart/form-data">
                                        <h4 class="mb-3 badge badge-secondary">Add New Slider</h4>
                                        <div class="form-group row">
                                            <div class="col-sm-12 mb-1 mb-sm-0">
                                                <input type="text" class="form-control mb-2" id="sliderLink" placeholder="Link for Slider" name="sliderLink">
                                                <p class="small text-muted">must provide a valid link</p>
                                            </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/*" onchange="checkFileDetails()" required>
                                                    <label class="custom-file-label" for="file">Select Slider Image</label>
                                                </div>
                                                <p class="small text-muted">Image should be in JPG / JPEG format & Resolution of <strong>1200 X 512</strong> or <strong>1500 X 640</strong></p>
                                                <p id="fileInfo" class="small"></p>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary btn-user m-2" name="new_slide">
                                            <i class="far fa-image"></i> Add New Slider
                                        </button>
                                    </form>
                                    <?php
                                }
                            ?>

                            <hr>

                            <div class="row m-0">
                                <h4 class="mb-3 badge badge-secondary">Sliders</h4>
                                
                                <div class="col-md-12 p-0">
                                    <p class="small">** Drag & Drop sliders to set Position</p>
                                </div>

                                <div class="col-md-12 p-0">
                                    <div class="table-responsive">
                                        <table class="table table-hover table-bordered table-sm" id="dataTable">
                                            <thead>
                                                <tr>
                                                    <th>Position</th>
                                                    <th>Link</th>
                                                    <th>Slide</th>
                                                    <th>Approval</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                    $sql = "SELECT * FROM slider ORDER BY sliderPosition ASC";
                                                    $run = mysqli_query($conn, $sql);

                                                    $c = 1;
                                                    while ( $rows = mysqli_fetch_assoc($run) ) {

                                                        $rows["sliderLink"] == '' ? $sliderLink = "<i class='fas fa-times-circle text-danger'></i>" : $sliderLink = "<a href='$rows[sliderLink]' class='small text-muted' target='_blank' title='Click to check link validation'><i class='fas fa-external-link-alt'></i> $rows[sliderLink]</a>";

                                                        $sliderCreatedOn = $rows['sliderCreatedOn'];
                                                        $sliderCreatedOn = formatTimeString($sliderCreatedOn);

                                                        $sliderUpdatedOn = $rows['sliderUpdatedOn'];
                                                        $sliderUpdatedOn != '' ? $sliderUpdatedOn = formatTimeString($sliderUpdatedOn) : $sliderUpdatedOn = "";
                                                        $sliderUpdatedOn != '' ? $sliderUpdatedOn = "<p class='small text-muted mb-1' title='Slide Updated On'> <i class='fas fa-history'></i> $sliderUpdatedOn</p>" : $sliderUpdatedOn = "";

                                                        $rows["approve"] == 0 ? $showApprove = "<a href='slider.php?approve_id=$rows[sliderId]&approval=$rows[approve]' class='btn btn-sm btn-warning' title='This Slider is NOT live right now'> <i class='fas fa-times-circle'></i> GO Live </a>" : $showApprove = "<a href='slider.php?approve_id=$rows[sliderId]&approval=$rows[approve]' class='btn btn-sm btn-success' title='This Slider is LIVE'> <i class='fas fa-check-circle'></i> Live </a>";

                                                        echo "
                                                        <tr id='$rows[sliderId]'>
                                                            <td><span class='badge badge-info badge-pill'>$rows[sliderPosition]</span></td>
                                                            <td>
                                                                $sliderLink
                                                            </td>
                                                            <td class='text-center align-middle'>
                                                                <img src='$rows[slidersmimage]' height='100' data-toggle='modal' data-target='#show-img' class='showModal'>
                                                            </td>
                                                            <td class='text-center align-middle'>
                                                                <button class='btn btn-light btn-sm'>$rows[sliderReference]</button>
                                                                <br>
                                                                <p class='small text-muted mb-1' title='Slide Added On'> <i class='fas fa-clock'></i> $sliderCreatedOn</p>
                                                                $sliderUpdatedOn
                                                                $showApprove
                                                            </td>
                                                            <td class='text-center align-middle'>
                                                                <a href='slider.php?edit_id=$rows[sliderId]' class='m-2 btn btn-success btn-sm rounded-circle' title='Click to Edit'> <i class='fas fa-pencil-alt'></i> </a>

                                                                <a href='slider.php?del_id=$rows[sliderId]' class='delete m-2 btn btn-danger btn-sm rounded-circle' title='Click to Delete'> <i class='fas fa-trash'></i> </a>
                                                            </td>
                                                        </tr>
                                                        ";
                                                        $c++;
                                                    }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                </div>

            </div>

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

        </div>

    </div>




    <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>




    <script>
        function checkFileDetails() {
            var fi = document.getElementById('file');
            if (fi.files.length > 0) { // FIRST CHECK IF ANY FILE IS SELECTED.

                for (var i = 0; i <= fi.files.length - 1; i++) {
                    var fileName, fileExtension, fileSize, fileType, dateModified;

                    // FILE NAME AND EXTENSION.
                    fileName = fi.files.item(i).name;
                    fileExtension = fileName.replace(/^.*\./, '');

                    // CHECK IF ITS AN IMAGE FILE.
                    // TO GET THE IMAGE WIDTH AND HEIGHT, WE'LL USE fileReader().
                    if (fileExtension == 'png' || fileExtension == 'jpg' || fileExtension == 'jpeg') {
                        readImageFile(fi.files.item(i)); // GET IMAGE INFO USING fileReader().
                    }
                }

                // GET THE IMAGE WIDTH AND HEIGHT USING fileReader() API.
                function readImageFile(file) {
                    var reader = new FileReader(); // CREATE AN NEW INSTANCE.

                    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);
                }
            }
            // document.getElementById("file").value = "";
        }
    </script>




    <script src="../js/jquery.min.js"></script>
    <script src="../js/bootstrap.bundle.min.js"></script>
    <script src="../js/jquery.easing.min.js"></script>
    <script src="js/sb-admin-2.min.js"></script>
    <script src="../vendor/sweetalert2/sweetalert2.min.js"></script>
    <script src="../vendor/datatables/jquery.dataTables.min.js"></script>
    <script src="../vendor/datatables/dataTables.bootstrap4.min.js"></script>
    <script src="../vendor/datatables/datatables.mark.min.js"></script>
    <script src="../vendor/jquery-ui/jquery-ui-custom.min.js"></script>
    <script src="js/custom.js"></script>

    <script>
		$(document).ready(function(){
            // dadatable
            $('#dataTable').DataTable({
                "mark": true
            });

            // image details on modal
            $('#show-img').on('show.bs.modal', function (e) {
                var src = $(e.relatedTarget).attr('src');
                $(this).find('.modal-body > img').attr('src', src);
            });
		});

        var $sortable = $("#dataTable > 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['new_slide'])){
        $sliderLink = mysqli_real_escape_string($conn, strip_tags($_POST['sliderLink']));

        $slicedRandom = rand();
        $customTime = time();
        $sliderReference = $customTime.'_'.$slicedRandom;

        // checking slider position
        $chk_slider_sql = "SELECT sliderPosition FROM slider ORDER BY sliderPosition DESC";
        $chk_slider_run = mysqli_query($conn, $chk_slider_sql);
        $chk_slider_rowCount = mysqli_num_rows($chk_slider_run);

        if ( $chk_slider_rowCount == 0 ) {
            $sliderPosition = 1;
        } else {
            $chk_slider_rows = mysqli_fetch_assoc($chk_slider_run);
            $sliderPosition = $chk_slider_rows["sliderPosition"];
            $sliderPosition += 1;
        }
        // checking slider position

        if( isset($_FILES["sliderlgimage"]) ){

            $file_name = $_FILES["sliderlgimage"]["name"];
            $tmp_name = $_FILES["sliderlgimage"]['tmp_name'];
            $filetype = $_FILES["sliderlgimage"]['type'];
            $fileinfo = getimagesize($tmp_name);
            $filewidth = $fileinfo[0];
            $fileheight = $fileinfo[1];
            $file_array = explode(".", $file_name);
            $file_extension = strtolower(end($file_array));
            $file_name = $sliderReference.'-'. rand().'.'. $file_extension;
            $file_name_thumb = $sliderReference.'-thumb-'. rand().'.'. $file_extension;
            // file upload location
            $location = '../images/2_slider/' . $file_name;
            $location_thumb = '../images/2_slider/' . $file_name_thumb;
            // file compress function
            $filename = compress_image($tmp_name, $location, 90);
            // file thumbnail function
            if($filetype == "image/jpeg" || $filetype == "image/jpg")
            {
                $imagecreate = "imagecreatefromjpeg";
                $imageformat = "imagejpeg";
            }
            if($filetype == "image/png")
            {						 
                $imagecreate = "imagecreatefrompng";
                $imageformat = "imagepng";
            }
            $new_width = "768";
            $new_height = ( $fileheight / $filewidth ) * $new_width;

            $image_p = imagecreatetruecolor($new_width, $new_height);
            $image = $imagecreate($location); //photo
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $filewidth, $fileheight);
            $imageformat($image_p, $location_thumb);//thumb

        }

        $ins_sql = "INSERT INTO slider (sliderLink, sliderlgimage, slidersmimage, sliderPosition, sliderReference, sliderCreatedOn) VALUES ('$sliderLink', '$location', '$location_thumb', '$sliderPosition', '$sliderReference', '$currentTime')";

        if(mysqli_query($conn, $ins_sql)){
            ?>
            <script>
                $(document).ready(function() {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'bottom',
                        showConfirmButton: false,
                        timer: 2000
                    });
                    Toast.fire({
                        type: 'success',
                        title: 'Slide Added'
                    }).then(function(){
                        window.location = 'slider.php';
                    });
                });
            </script>
            <?php
        }
        else{
            ?>
            <script>
                $(document).ready(function() {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'bottom',
                        showConfirmButton: false,
                        timer: 2000
                    });
                    Toast.fire({
                        type: 'error',
                        title: 'OOPS !'
                    }).then(function(){
                        window.location = 'slider.php';
                    });
                });
            </script>
            <?php
        }
    }




    if ( isset($_GET["del_id"]) ) {

        $select_run = mysqli_query($conn, "SELECT sliderlgimage, slidersmimage FROM slider WHERE sliderId = '$_GET[del_id]'");
        $select_row = mysqli_fetch_assoc($select_run);

        $sliderlgimage = $select_row["sliderlgimage"];
        $slidersmimage = $select_row["slidersmimage"];

        unlink($sliderlgimage);
        unlink($slidersmimage);

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

        if ( mysqli_query($conn, $del_sql) ) {
            ?>
            <script>window.location = "slider.php";</script>
            <?php
        } else {
            ?>
            <script>
                $(document).ready(function() {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'bottom',
                        showConfirmButton: false,
                        timer: 2000
                    });
                    Toast.fire({
                        type: 'error',
                        title: 'OOPS'
                    });
                });
                window.location = "slider.php";
            </script>
            <?php
        }
        
    }






    if ( isset($_GET["approve_id"]) && isset($_GET["approval"]) ) {

        $approve = $_GET["approval"];
        $approve == 0 ? $approve = 1 : $approve = 0;

        $del_sql = "UPDATE slider SET approve = '$approve' WHERE sliderId = '$_GET[approve_id]'";

        if ( mysqli_query($conn, $del_sql) ) {
            ?>
            <script>window.location = "slider.php";</script>
            <?php
        } else {
            ?>
            <script>
                $(document).ready(function() {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'bottom',
                        showConfirmButton: false,
                        timer: 2000
                    });
                    Toast.fire({
                        type: 'error',
                        title: 'OOPS'
                    });
                });
                window.location = "slider.php";
            </script>
            <?php
        }
    }





    if(isset($_POST['edit_slide'])){
        $sliderLink = mysqli_real_escape_string($conn, strip_tags($_POST['sliderLink']));

        $sliderReference = $_POST["sliderReference"];

        date_default_timezone_set('Asia/Kolkata');
        $sliderUpdatedOn = date("M j, Y, g:i a");

        $up_sql = "UPDATE slider SET sliderLink = '$sliderLink', sliderUpdatedOn = '$sliderUpdatedOn'";

        if( !empty($_FILES["sliderlgimage"]["name"]) && !empty($_FILES["sliderlgimage"]["tmp_name"]) ){

            $file_name = $_FILES["sliderlgimage"]["name"];
            $tmp_name = $_FILES["sliderlgimage"]['tmp_name'];
            $filetype = $_FILES["sliderlgimage"]['type'];
            $fileinfo = getimagesize($tmp_name);
            $filewidth = $fileinfo[0];
            $fileheight = $fileinfo[1];
            $file_array = explode(".", $file_name);
            $file_extension = strtolower(end($file_array));
            $file_name = $sliderReference.'-'. rand().'.'. $file_extension;
            $file_name_thumb = $sliderReference.'-thumb-'. rand().'.'. $file_extension;
            // file upload location
            $location = '../images/2_slider/' . $file_name;
            $location_thumb = '../images/2_slider/' . $file_name_thumb;
            // file compress function
            $filename = compress_image($tmp_name, $location, 90);
            // file thumbnail function
            if($filetype == "image/jpeg" || $filetype == "image/jpg")
            {
                $imagecreate = "imagecreatefromjpeg";
                $imageformat = "imagejpeg";
            }
            if($filetype == "image/png")
            {						 
                $imagecreate = "imagecreatefrompng";
                $imageformat = "imagepng";
            }
            $new_width = "768";
            $new_height = ( $fileheight / $filewidth ) * $new_width;

            $image_p = imagecreatetruecolor($new_width, $new_height);
            $image = $imagecreate($location); //photo
            imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $filewidth, $fileheight);
            $imageformat($image_p, $location_thumb);//thumb

            // delete previous slide
            $slide_run = mysqli_query($conn, "SELECT sliderlgimage, slidersmimage FROM slider WHERE sliderId = '$_GET[edit_id]'");
            $slide_row = mysqli_fetch_assoc($slide_run);

            unlink($slide_row["sliderlgimage"]);
            unlink($slide_row["slidersmimage"]);

            $up_sql .= ", sliderlgimage = '$location', slidersmimage = '$location_thumb'";

        }

        $up_sql .= " WHERE sliderId = '$_GET[edit_id]'";

        if(mysqli_query($conn, $up_sql)){
            ?>
            <script>
                $(document).ready(function() {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'bottom',
                        showConfirmButton: false,
                        timer: 2000
                    });
                    Toast.fire({
                        type: 'success',
                        title: 'Slide Updated'
                    }).then(function(){
                        window.location = 'slider.php';
                    });
                });
            </script>
            <?php
        }
        else{
            ?>
            <script>
                $(document).ready(function() {
                    const Toast = Swal.mixin({
                        toast: true,
                        position: 'bottom',
                        showConfirmButton: false,
                        timer: 2000
                    });
                    Toast.fire({
                        type: 'error',
                        title: 'OOPS !'
                    }).then(function(){
                        window.location = 'slider.php';
                    });
                });
            </script>
            <?php
        }
    }

?>