<?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 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" /> 
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
 <style>
.items-mobile {
margin: 30px 0 0;
border: 2px solid #adadad;
padding: 10px 0;
height: 150px;
background-color: #fff;
}.items-mobile .project-name p {
font-weight: bold;
font-size: 12px;
margin: 12px 0;
}.icon-wrapper i{
    font-size: 82px;
}
.items-mobile:hover {
box-shadow: 0 0.25rem 0.5rem #6e8ca5;
}
        </style>
        
        <style>
body {
  font-family: "Lato", sans-serif;
}

.sidenav {
  height: 100%;
  width: 0;
  position: fixed;
  z-index: 1;
  top: 0;
  left: 0;
  background-color: #111;
  overflow-x: hidden;
  transition: 0.5s;
  padding-top: 60px;
}

.sidenav a {
  padding: 8px 8px 8px 32px;
  text-decoration: none;
  font-size: 25px;
  color: #818181;
  display: block;
  transition: 0.3s;
}

.sidenav a:hover {
  color: #f1f1f1;
}

.sidenav .closebtn {
  position: absolute;
  top: 0;
  right: 25px;
  font-size: 36px;
  margin-left: 50px;
}

@media screen and (max-height: 450px) {
  .sidenav {padding-top: 15px;}
  .sidenav a {font-size: 18px;}
}
</style>
<style>
* {box-sizing: border-box}

/* Set height of body and the document to 100% */
body, html {
  height: 100%;
  margin: 0;
  font-family: Arial;
}

/* Style tab links */
.tablink {
  background-color: #555;
  color: white;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  font-size: 17px;
  width: 50%;
}

.tablink:hover {
  background-color: #777;
}

/* Style the tab content (and add height:100% for full page content) */
.tabcontent {
  color: white;
  display: none;
  padding: 100px 20px;
  height: 100%;
}

#Home {background-color: #D1D0C0;}
#News {background-color: #D1D0C0;}

</style>
    <style>
    /* sign in FORM */
    #logreg-forms {
        width: 412px;
        margin: 10vh auto;
        background-color: #f3f3f3;
        box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
        transition: all 0.3s cubic-bezier(.25, .8, .25, 1);
    }

    #logreg-forms form {
        width: 100%;
        max-width: 410px;
        padding: 15px;
        margin: auto;
    }

    #logreg-forms .form-control {
        position: relative;
        box-sizing: border-box;
        height: auto;
        padding: 10px;
        font-size: 16px;
    }

    #logreg-forms .form-control:focus {
        z-index: 2;
    }

    #logreg-forms .form-signin input[type="email"] {
        margin-bottom: -1px;
        border-bottom-right-radius: 0;
        border-bottom-left-radius: 0;
    }

    #logreg-forms .form-signin input[type="password"] {
        border-top-left-radius: 0;
        border-top-right-radius: 0;
    }

    #logreg-forms .social-login {
        width: 390px;
        margin: 0 auto;
        margin-bottom: 14px;
    }

    #logreg-forms .social-btn {
        font-weight: 100;
        color: white;
        width: 190px;
        font-size: 0.9rem;
    }

    #logreg-forms a {
        display: block;
        padding-top: 10px;
        color: lightseagreen;
    }

    #logreg-form .lines {
        width: 200px;
        border: 1px solid red;
    }


    #logreg-forms button[type="submit"] {
        margin-top: 10px;
    }

    #logreg-forms .facebook-btn {
        background-color: #3C589C;
    }

    #logreg-forms .google-btn {
        background-color: #DF4B3B;
    }

    #logreg-forms .form-reset,
    #logreg-forms .form-signup {
        display: none;
    }

    #logreg-forms .form-signup .social-btn {
        width: 210px;
    }

    #logreg-forms .form-signup input {
        margin-bottom: 2px;
    }

    .form-signup .social-login {
        width: 210px !important;
        margin: 0 auto;
    }

    /* Mobile */

    @media screen and (max-width:500px) {
        #logreg-forms {
            width: 300px;
        }

        #logreg-forms .social-login {
            width: 200px;
            margin: 0 auto;
            margin-bottom: 10px;
        }

        #logreg-forms .social-btn {
            font-size: 1.3rem;
            font-weight: 100;
            color: white;
            width: 200px;
            height: 56px;

        }

        #logreg-forms .social-btn:nth-child(1) {
            margin-bottom: 5px;
        }

        #logreg-forms .social-btn span {
            display: none;
        }

        #logreg-forms .facebook-btn:after {
            content: 'Facebook';
        }

        #logreg-forms .google-btn:after {
            content: 'Google+';
        }
    }
    </style>
    
    
        <style>
        .content {
            position: absolute;
            top: 300px;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.5);
            color: #f1f1f1;
            padding: 20px;
            border-radius: 5px;
            width: 300px;
            height:400px;
        }
        @media(max-width:500px){
            .content {
                left: 50%;
                width: 100%;
            }
        }
        .content3{
            background: #000;
            color:#fff;
            padding:20px;
        }
        .testing{
            text-align: right;
        }
        @media(max-width:768px){
            .testing{
                text-align: left;
            }
        }
    </style>
    
</head>

<body>

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

  <!--==========================
    Intro Section
  ============================-->

    <div class="">
        <h3 class="text-center mb-4" style="margin-top: 80px">Write a Aricle</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>

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

 <!--==========================
    Footer
  ============================-->

  
  <!-- #footer -->

    
 
    <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="vendor/ckeditor.js"></script>
     <script src="js/mobile-nav/mobile-nav.js"></script>

</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: 600,
        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 = 'review-blog.php.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
        }
    }
?>