<?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");

    $fetch_file = mysqli_query($con, "SELECT bid FROM blog ORDER BY bid DESC");

    // echo "<pre>";print_r($fetch_file);exit();
    // $count = myqsli_num_rows($fetch_file);
    // $count = 1;

    // if ( $count == 0 ) {
    //     $bref = 1;
    // } else {
        $row = mysqli_fetch_assoc($fetch_file);

        $bref = $row["bid"] + 1;
    // }
    

    // $bref = mt_rand()."_".time();
?>
<!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 Article</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>

    <div class="">
        <h3 class="text-center mb-4" style="margin-top: 80px">Write a Article</h3>
        <input type="hidden" name="bref" id="bref" value="<?php echo $bref; ?>">
        <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">  Category
                                    <select name="bcat" id="bcat" class="form-control mb-3">
                                        <option selected disabled> Previous Category : <?php echo $edit_row["cname"]; ?> </option>
                                        <?php
                                           
                                            $sql = "SELECT cname, cid FROM category WHERE catby = '$_SESSION[uid]' 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">
                                Article Title
                                    <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-12 text-center">
                                    <div id="logo_wrapper">
                                                    <img src="<?php echo $edit_row["bimage"]; ?>" style="height:50px;" alt="none" >
                                                </div>
                                </div>
                                 <div class="col-md-12">
                                 Article tag
                                    <input type="text" name="btag" class="form-control mb-3" value="<?php echo $edit_row['btag'];?>">
                                </div>
                               
                                
                            </div>
                            Article 
                            <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">
                            <div class="form-group row">
                                <div class="col-md-3">
                                    <select name="bcat" id="bcat" class="form-control mb-3" required>
                                        <option selected disabled> Select Category </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" id="btitle" class="form-control mb-3" placeholder="Enter Blog Title" required>
                                </div>
                            </div>
                          
                            <!-- <textarea name="content" id="content" class="form-control ckeditor" required></textarea> -->

                            
                            <div class="row mx-0 mt-3">
                                <div class="custom-file" style="height: 134px;">
                                    <!-- <input type="file" class="custom-file-input" id="bimage" name="bimage" required> -->
                                    <input type="file" class="custom-file-input" name="bimage" id="file" accept="image/*" required>
                                    <label class="custom-file-label" for="file" style="height: 100%;margin-top: auto;padding-top: 50px;padding-left: 80px;">Select Article Image</label>
                                </div>
                            </div>
                            <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: 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 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,
                     
                        content: content
                    },
                    success: function (data) {
                        $('#uploadimageModal').modal('hide');
                        $('#uploaded_image').html(data);
                        var bref = $('#bref').val();
                        $(location).attr('href', 'blog2.php?bref='+bref);
                    }
                });
            })
        });
    });
</script>

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

        // $location2 = "";

        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 != '' ) {

            $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,btag, blog, bcat, badmin2, bcreated, bimage) VALUES ('$_SESSION[uid]', '$btitle','$btag', '$blog', '$bcat', '$badmin2', '$currentTime', '$target_dir')";

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

            if(mysqli_query($con, $ins_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"];
          $btag = $_POST["btag"];
      
        $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',btag ='$btag',bupdated='$currentTime,', bimage = '$target_dir' ";

            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"];
        $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')";

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

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

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

        mysqli_query($con, $new_ins_sql);
        header("Location: blog2.php?bref=$bref");

        // 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
        // }
    }
?>