<?php
    session_start();
    include "../../db.php";
    date_default_timezone_set('Asia/Kolkata');
      $currentTime = date('jS  F Y');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) )
        header("Location: logout.php");
?>
<!DOCTYPE html>
<html>

<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>Write a Blog</title>

    <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> -->
    <link href="css/sb-admin-2.min.css" rel="stylesheet">
    <link href="css/all.min.css" rel="stylesheet" type="text/css">
	<link rel="stylesheet" href="vendor/croppie/croppie.css" />


    <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="vendor/croppie/croppie.js"></script>
    <script src="js/custom.js"></script>

    <script src="vendor/ckeditor.js"></script>

    <style>
        .custom-file-label::after {
            height: 8.25rem;
            padding-top: 50px;
        }
        .custom-file-label-edit::after{
            height: 2.25rem;
            padding-top: 5px;
        }
        #uploadimageModal .modal-dialog{
            max-width: 100% !important;
        }
    </style>
</head>

<body>
    <?php include "includes/topbar.php"; ?>
    <div class="">
        <h3 class="text-center mb-4" style="margin-top: 80px">Write a Blog</h3>
        <div class="card">
            <div class="card-body">
                <?php
                    if ( isset($_GET["edit_id"]) ) {
                        $edit_sql = "SELECT * FROM blog AS b INNER JOIN category AS c ON b.bcat = c.cid WHERE bid = '$_GET[edit_id]'";
                        $edit_run = mysqli_query($con, $edit_sql);
                        $edit_row = mysqli_fetch_assoc($edit_run);
                        ?>
                        <form method="post" enctype="multipart/form-data">
                            <div class="form-row">
                                <div class="col-md-3">
                                    <select name="bcat" id="bcat" class="form-control mb-3">
                                        <option selected disabled> Previous Category : <?php echo $edit_row["cname"]; ?> </option>
                                        <?php
                                            $fetch_memby = mysqli_query($con, "SELECT memberby FROM users WHERE uid = '$_SESSION[uid]'");
                                            $memberby_row = mysqli_fetch_assoc($fetch_memby);
                                            $sql = "SELECT cname, cid FROM category WHERE catby = '$memberby_row[memberby]' ORDER BY cname ASC";
                                            $run = mysqli_query($con, $sql);

                                            while ( $cat_rows = mysqli_fetch_assoc($run) ) {
                                                echo '
                                                <option value="'.$cat_rows["cid"].'"> '.$cat_rows["cname"].' </option>
                                                ';
                                            }
                                        ?>
                                    </select>
                                </div>
                                <div class="col-md-9">
                                    <input type="text" name="btitle" class="form-control mb-3" value="<?php echo $edit_row['btitle'];?>">
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-3">
                                    <div class="w-100 text-center py-2">
                                        <img src="<?php echo $edit_row['bimage'] ?>" alt="image" height="80" class="">
                                    </div>
                                    <div class="custom-file">
                                        <input type="file" class="custom-file-input" id="bimage" name="bimage">
                                        <input type="file" class="custom-file-input" name="bimage" id="file" accept="image/*" required>
                                        <label class="custom-file-label custom-file-label-edit" for="bimage" style="">Select Blog Image</label>
                                    </div>
                                </div>

                                <div class="col-md-9">
                                    <textarea name="bdesc" id="bdesc" class="form-control" rows="5" ><?php echo $edit_row["bdesc"]; ?></textarea>
                                </div>
                            </div>
                            <textarea name="content" id="content" class="form-control ckeditor" ><?php echo $edit_row["blog"]; ?></textarea>
                            <hr>
                            <button type="submit" class="btn btn-success my-4" name="update_blog"> <i class="fas fa-cloud-upload-alt"></i> Update </button>

                            <a href="review-blog.php" class="btn btn-warning my-4"> Cancel </a>
                        </form>
                        <?php
                    } else {
                        ?>
                        <form method="post" enctype="multipart/form-data">

                            <textarea name="content" id="content" class="form-control ckeditor" required></textarea>

                            <hr>

                            <button type="submit" class="btn btn-success my-4" name="upload_blog"> <i class="fas fa-cloud-upload-alt"></i> Save Changes </button>

                            <a href="index.php" class="btn btn-warning my-4"> Cancel </a>
                        </form>
                        <?php
                    }
                ?>
            </div>
        </div>
    </div>
</body>
</html>



    <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%;"></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>
    CKEDITOR.replace( 'content', {
        height: 500,
        filebrowserUploadUrl: "upload.php"
    });



    $(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: 400,
                height: 400
            }
        });$('#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 bcat = $('#bcat').val();
            var btitle = $('#btitle').val();
            var bdesc = $('#bdesc').val();
            var content = $('#content').val();
            $image_crop.croppie('result', {
                type: 'canvas',
                size: 'viewport'
            }).then(function (response) {
                $.ajax({
                    url: "blog.php",
                    type: "POST",
                    data: {
                        "image": response,
                        bcat: bcat,
                        btitle: btitle,
                        bdesc: bdesc,
                        content: content
                    },
                    success: function (data) {
                        $('#uploadimageModal').modal('hide');
                        $('#uploaded_image').html(data);
                    }
                });
            })
        });
    });
</script>

<?php
    if(isset($_POST['upload_blog'])){
        $blog = $_POST["content"];

        if ( $blog != '' ) {

            // $fetch_memby = mysqli_query($con, "SELECT memberby FROM users WHERE uid = '$_SESSION[uid]'");
            // $memberby_row = mysqli_fetch_assoc($fetch_memby);
            // $badmin2 = $memberby_row["memberby"];

            // $ins_sql = "INSERT INTO blog (bby, btitle, blog, bcat, badmin2, bcreated, bimage, bdesc) VALUES ('$_SESSION[uid]', '$btitle', '$blog', '$bcat', '$badmin2', '$currentTime', '$target_dir', '$bdesc')";

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

            $up_sql = "UPDATE blog SET blog = '$blog' WHERE bid = '$_GET[bref]'";

            if(mysqli_query($con, $up_sql)){
                ?>
                <script>window.location = 'review-blog.php';</script>
                <?php
            }
            else{
                ?>
                <script>
                    alert('OOPS !!!!');
                    setTimeout(() => {
                        window.location = 'blog.php';
                    }, 500);
                </script>
                <?php
            }
        } else {
            ?>
            <script>
                alert('Content is Empty');
                setTimeout(() => {
                    window.location = 'blog.php';
                }, 500);
            </script>
            <?php
        }
    }
    if(isset($_POST['update_blog'])){
        $blog = $_POST["content"];
        $btitle = $_POST["btitle"];
        $bdesc = $_POST["bdesc"];
        $target_dir = $edit_row["bimage"];
        // 
        if ( isset($_FILES["bimage"]["name"]) && !empty($_FILES["bimage"]["tmp_name"]) ) {
            $file = $_FILES['bimage'];
            $fileName = $_FILES['bimage']['name'];
            $fileTmpName = $_FILES['bimage']['tmp_name'];
            $fileSize = $_FILES['bimage']['size'];
            $fileError = $_FILES['bimage']['error'];
            $fileType = $_FILES['bimage']['type'];

            $fileOldExt = explode('.', $fileName);
            $fileActualExt = strtolower(end($fileOldExt));

            $allowed = array('jpg', 'jpeg', 'png');

            if ( in_array($fileActualExt, $allowed) ) {
                if ( $fileError === 0 ) {
                    if ( $fileSize < 3000000 ) {
                        $fileNewName = mt_rand().".".$fileActualExt;
                        $target_dir = '../upload/'.$fileNewName;
                        move_uploaded_file($fileTmpName, $target_dir);

                        // $upd_sql = "UPDATE user SET u_img = '$target_dir' WHERE u_ref = '$_SESSION[uref]'";
                        //  echo "<pre>";print_r($upd_sql);exit();
                    } else {
                        ?>
                        <script>
                            alert("Max file size : 3 MB");
                            window.location = "blog.php";
                        </script>
                        <?php
                        exit();
                    }                
                } else {
                    ?>
                    <script>
                        alert("Something Happened");
                        window.location = "blog.php";
                    </script>
                    <?php
                    exit();
                }            
            } else {
                ?>
                <script>
                    alert("Cannot Upload this file Type");
                    window.location = "blog.php";
                </script>
                <?php
                exit();
            }
        }
        if ( $blog != '' ) {
            // $ins_sql = "INSERT INTO blog (bby, blog, bcat, bcreated) VALUES ('$_SESSION[uid]', '$blog', '$bcat', '$currentTime')";
            $up_sql = "UPDATE blog SET blog = '$blog', btitle ='$btitle', bimage = '$target_dir', bdesc = '$bdesc' ";

            if ( isset($_POST["bcat"]) ) {
                $bcat = $_POST["bcat"];
                $up_sql .= ", bcat = '$bcat'";
            }

            $up_sql .= " WHERE bid = '$_GET[edit_id]'";
            if(mysqli_query($con, $up_sql)){
                ?>
                <script>window.location = 'review-blog.php';</script>
                <?php
            }
            else{
                ?>
                <script>
                    alert('OOPS !!!!');
                    setTimeout(() => {
                        window.location = 'blog.php';
                    }, 500);
                </script>
                <?php
            }
        } else {
            ?>
            <script>
                alert('Content is Empty');
                setTimeout(() => {
                    window.location = 'blog.php';
                }, 500);
            </script>
            <?php
        }
    }
    if(isset($_POST["image"]))
    {
        $data = $_POST["image"];
        $bref = mt_rand()."_".time();

        $content = $_POST["content"];
        $bdesc = $_POST["bdesc"];
        $btitle = $_POST["btitle"];
        $bcat = $_POST["bcat"];

        $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/'.rand() . '.jpg';

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

        // $new_ins_sql = "INSERT INTO blog (bby, btitle, blog, bcat, badmin2, bcreated, bimage, bdesc) VALUES ('$_SESSION[uid]', '$btitle', '$blog', '$bcat', '$badmin2', '$currentTime', '$target_dir', '$bdesc')";

        $new_ins_sql = "INSERT INTO blog (bimage, blog, bcreated, bdesc, bcat, btitle, bref) VALUES ('$destination_img', '$content', '$currentTime', '$bdesc', '$bcat', '$btitle', '$bref')";

        // echo "<pre>";print_r($new_ins_sql);exit();

        if(mysqli_query($con, $new_ins_sql)){
            ?>
            <script>window.location = 'blog2.php?bref=<?php echo $bref; ?>';</script>
            <?php
        }
        else{
            ?>
            <script>
                alert('OOPS !!!!');
                setTimeout(() => {
                    window.location = 'blog.php';
                }, 500);
            </script>
            <?php
        }
    }
?>