<?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>
    <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 rel="stylesheet" href="vendor/croppie/croppie.css" />
    <link href="css/style.css" rel="stylesheet">

    <style>
        #uploadimageModal .modal-dialog{
            max-width: 100% !important;
        }
    </style>
</head>
<body id="page-top" class="mt-55">

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

    <div id="wrapper">

        <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">service</h1>
                            <hr>

                            <?php
                                if ( isset($_GET["edit_id"]) ) {
                                    $edit_run = mysqli_query($con, "SELECT * FROM service WHERE serid = '$_GET[edit_id]'");
                                    $edit_row = mysqli_fetch_assoc($edit_run);
                                    ?>
                                    <form class="user" method="post" enctype="multipart/form-data">
                                        <h4 class="mb-2 badge badge-secondary">Edit service</h4>
                                        <div>
                                            <div class="form-group row">
                                                <div class="col-sm-6 mb-1 mb-sm-0">
service Name
                                                    <input type="text" class="form-control mb-2" id="sername" placeholder="Enter Link for service (Optional)" name="sername" value="<?php echo $edit_row["sername"]; ?>">
                                                </div>
 <div class="col-sm-6 mb-1 mb-sm-0">
service Title
                                                    <input type="text" class="form-control mb-2" id="sertitle" placeholder="Title" name="sertitle" value="<?php echo $edit_row["sertitle"]; ?>">
                                                </div>
                                            </div>
											 <div class="form-group row">
                                               
                                            </div>
											
											 <div class="form-group row">
                                                <div class="col-sm-12 mb-1 mb-sm-0">
service Details
                                                   
 <textarea name="serdis" id="serdis" class="form-control" rows="2" ><?php echo $edit_row["serdis"]; ?></textarea>                                              
  </div>
                                            </div>
											
                                            <div class="form-group row">
                                                <div class="col-sm-12 mb-1 mb-sm-0">
                                                    <img src="<?php echo $edit_row["serlgimage"]; ?>" alt="service" class="img-thumbnail mb-3" style="height:50px;">
                                                    
                                                </div>
                                            </div>
                                            <button type="submit" class="btn btn-success btn-user m-2" name="update_service">
                                                <i class="fas fa-image"></i> Update service
                                            </button>
                                            <a href="service.php" class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i> Cancel </a>
                                        </div>
                                    </form>
                                    <?php
                                } else {
                                    ?>
                                    <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 service</h4>
                                        <p class="small"> <i class="fas fa-hand-point-up"></i> Tap Here to add New service </p>
                                        <div class="collapse" id="target">
                                            <div class="form-group row">
                                                <div class="col-sm-6 mb-1 mb-sm-0">
                                                    <input type="text" class="form-control mb-2" id="sername" placeholder="service Name" name="sername">
                                                </div>
												 <div class="col-sm-6 mb-1 mb-sm-0">
                                                    <input type="text" class="form-control mb-2" id="sertitle" placeholder="service Title" name="sertitle">
                                                </div>
												
                                            </div>
                                            <div class="form-group row">
                                               <div class="col-sm-12 mb-1 mb-sm-0">
                                                 
  <textarea name="serdis" id="serdis" class="form-control" rows="2" placeholder="service  Details" required></textarea>
                                                </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="servicelgimage" id="file" accept="image/*" required>
                                                        <label class="custom-file-label" for="file">Select service Image *</label>
                                                    </div>
                                                </div>
                                            </div>
                                            <!-- <button type="submit" class="btn btn-primary btn-user m-2" name="new_service">
                                                <i class="fas fa-user-plus"></i> Add New service
                                            </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>
                                    <?php
                                }
                            ?>

                            <hr>

                            <div class="row m-0">
                                <h4 class="mb-3 badge badge-secondary">services</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>Name</th>
                                                    <th>Image</th>
                                                    <th>Action</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                    $sql = "SELECT * FROM service WHERE serby = '$_SESSION[uid]' ORDER BY serpos ASC";
                                                    $run = mysqli_query($con, $sql);

                                                    $c = 1;
                                                    while ( $rows = mysqli_fetch_assoc($run) ) {
                                                        $rows["sername"] == "" ? $sername = "<span class='badge badge-danger badge-pill'> <i class='fas fa-times-circle'></i> No Link </span>" : $sername = "<a href='$rows[sername]' target='_blank' class='badge badge-info badge-pill'> $rows[sertitle] <i class='fas fa-share'></i> </a>";
$trimmesertitle = mb_strimwidth($rows['serdis'], 0, 20, "...");                                                       
													   echo "
                                                        <tr id='$rows[serid]'>
                                                            <td>
                                                                <span class='badge badge-info badge-pill'>$c</span>
                                                            </td>
                                                            <td>
                                                            $rows[sername]<br> $rows[sertitle]<br> $trimmesertitle 
                                                            </td>
                                                            <td>
                                                                <img src='$rows[serlgimage]' height='50' data-toggle='modal' data-target='#show-img' class='showModal'>
                                                            </td>
                                                        ";
                                                        ?>
                                                            <td class='text-center align-middle'>
                                                                <a href='service.php?edit_id=<?php echo $rows["serid"]; ?>' class='m-2 btn btn-success btn-sm rounded-circle' title='Click to Edit'> <i class='fas fa-pencil-alt'></i> </a> 

                                                                <a href='service.php?del_id=<?php echo $rows["serid"]; ?>&imgpath=<?php echo $rows["serlgimage"]; ?>' 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>

            </div>

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

        </div>

    </div>




    <div class="modal fade" id="show-img" tabindex="-1" role="dialog" aria-labelleserby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-body">
                    <img src="" alt="serviceImage" 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 col-sm-12 col-12 text-center">
							<div id="image_demo" style="margin-top:10px;height:40%;"></div>
							<p class="small">scroll through mouse to zoom in or out</p>
						</div>
						<div class="col-md-12 col-sm-12 col-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 == 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 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>
		$(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: 300,
					height: 300,
					type: 'square' //circle
				},
				boundary: {
					width: 310,
					height: 310,
				}
			});$('#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 sername = $('#sername').val();
				var serdis = $('#serdis').val();
                var sertitle = $('#sertitle').val();
				
				$image_crop.croppie('result', {
					type: 'canvas',
					size: 'viewport'
				}).then(function (response) {
					$.ajax({
						url: "service.php",
						type: "POST",
						data: {
							"image": response,
                            sername: sername,
							serdis: serdis,
                            sertitle: sertitle
							 
						},
						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("service_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 service WHERE serid = '$_GET[del_id]'";

        if ( mysqli_query($con, $del_sql) ) {
            ?>
            <script>window.location = "service.php";</script>
            <?php
        } else {
            ?>
            <script>
                alert('OOPS !!!!');
                setTimeout(() => {
                    window.location = 'service.php';
                }, 500);
            </script>
            <?php
        }
        
    }
    if(isset($_POST['update_service'])){
        $serref = $_GET["serref"];
        $sername = mysqli_real_escape_string($con, strip_tags($_POST['sername']));
		 $sertitle = mysqli_real_escape_string($con, strip_tags($_POST['sertitle']));
		  $serdis = mysqli_real_escape_string($con, strip_tags($_POST['serdis']));
        $up_sql = "UPDATE service SET sername = '$sername', sertitle = '$sertitle', serdis = '$serdis'";		
		
        if( isset($_FILES["servicelgimage"]["name"]) && !empty($_FILES["servicelgimage"]["tmp_name"]) ){
            $file_name = $_FILES["servicelgimage"]["name"];
            $tmp_name = $_FILES["servicelgimage"]['tmp_name'];
            $filetype = $_FILES["servicelgimage"]['type'];
            $fileinfo = getimagesize($tmp_name);
            $filewidth = $fileinfo[0];
            $fileheight = $fileinfo[1];
            $file_array = explode(".", $file_name);
            $file_extension = strtolower(end($file_array));
            $file_name = $serref.'-'. rand().'.'. $file_extension;
            $location = '../upload/service/'.$file_name;
            move_uploaded_file($tmp_name, $location);
            unlink($_GET["imgpath"]);
            $up_sql .= ", serlgimage = '$location'";
        }
        $up_sql .= " WHERE serid = '$_GET[edit_id]'";

        // $up_sql = "INSERT INTO service (sername, serlgimage, serref, serby, sercreated) VALUES ('$sername', '$location', '$serref', '$_SESSION[uid]', '$currentTime')";

        // echo '<pre>';print_r($ins_sql);exit();

        if(mysqli_query($con, $up_sql)){
            ?>
            <script>window.location = 'service.php';</script>
            <?php
        }
        else{
            ?>
            <script>
                alert('OOPS !!!!');
                setTimeout(() => {
                    window.location = 'service.php';
                }, 1200);
            </script>
            <?php
        }
    }
    if(isset($_POST['edit_cat'])){
        $cname = mysqli_real_escape_string($con, strip_tags($_POST['cname']));
        $up_sql = "UPDATE category SET cname = '$cname' WHERE cid = '$_GET[edit_id]'";

        if(mysqli_query($con, $up_sql)){
            ?>
            <script>window.location = 'category.php';</script>
            <?php
        }
        else{
            ?>
            <script>
                alert('OOPS !!!!');
                setTimeout(() => {
                    window.location = 'category.php?edit_id=<?php echo $_GET["edit_id"]; ?>';
                }, 500);
            </script>
            <?php
        }
    }
    if(isset($_POST["image"]))
    {
        $data = $_POST["image"];
        $sername = $_POST["sername"];
		
        $sertitle = $_POST["sertitle"];
		$serdis = $_POST["serdis"];
		
        $serref = rand()."_".time();

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

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

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

        $imageName = '../upload/service/'.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/service/'.rand() . '.png';
        $d = compress($imageName, $destination_img, 40);
        unlink($imageName);
        $new_ins_sql = "INSERT INTO service (sername, sertitle, serdis, serlgimage, serby, sercreated, serref) VALUES ('$sername', '$sertitle','$serdis', '$destination_img', '$_SESSION[uid]', '$currentTime', '$serref')";

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