<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Student']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['ucontact'])  && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    $edit_run = mysqli_query($con, "SELECT * FROM users WHERE uid = '$_SESSION[uid]'");
    $edit_row = mysqli_fetch_assoc($edit_run);

    if (!empty($edit_row["uphoto"])) {
        $img = "../upload/profile_img/".$edit_row["uphoto"];
    }else{
        $img = "../upload/profile_img/default.jpg";
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <link rel="stylesheet" href="vendor/croppie/croppie.css" />
</head>

<body>
    <!--  Header -->
    <?php 
    include "include/header.php"; 
    ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-container">
            <div class="container-fluid">
                <div class="card m-2">
                    <div class="card-header">
                        <h4 class="text-center">Profile</h4>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 mb-3 order-lg-2">
                                <h4 class="mb-3">Profile Photo</h4>
                                <form method="post" enctype="multipart/form-data">
                                    <div class="col-md-12 text-center mb-2">
                                        <img src="<?php echo $img; ?>" width="150" height="150">
                                    </div>
                                    <div class="col-md-12 position-relative">
                                        <input type="file" class="form-control" name="facilitylgimage" id="file"
                                            accept="image/*" required>
                                        <label class="form-control position-absolute" for="file"
                                            style="color: green;top:0;">Select profile
                                            Image
                                            *</label>
                                    </div>
                                </form>

                                <form method="post" enctype="multipart/form-data">
                                    <div class="col-sm-12" style="margin-top: 10px;">
                                        <h4 class="mb-3">Login Password</h4>
                                        <input type="text" class="form-control mb-2" id="upass" placeholder="Password *"
                                            name="upass" value="<?php echo $edit_row["upass"]; ?>" required>
                                        <button type="submit" class="btn btn-success btn-user" name="edit_cat">
                                            <i class="fa fa-image"></i> Update Password
                                        </button>
                                        <a href="index.php" class="btn btn-warning btn-user m-2"> <i
                                                class="fa fa-ban"></i>
                                            Cancel </a>
                                    </div>
                                </form>
                            </div>
                            <div class="col-md-8 mb-3 order-lg-1">
                                <h4 class="mb-3">Personal Details</h4>

                                <p class="mb-2"><b>Name : </b>
                                    <?php echo $edit_row["uname"]; ?></p>

                                <p class="mb-2"><b>Contact No. : </b>
                                    <?php echo $edit_row["ucontact"]; ?></p>

                                <p class="mb-2"><b>UserId : </b>
                                    <?php echo $edit_row["uref_code"]; ?></p>

                                <h4 class="mb-3">Address</h4>

                                <p class="mb-2">
                                    <?php echo $edit_row["saddress"]; ?></p>

                                <p class="mb-2">
                                    <?php
                                    $dist_sql = mysqli_query($con, "SELECT * FROM dist WHERE id = '$edit_row[dist]'");
                                    if($dist_row = mysqli_fetch_assoc($dist_sql)){
                                        echo $dist_name = $dist_row["distName"];
                                    }
                                    ?>
                                </p>
                                <p class="mb-2">
                                    <?php
                                    $state_sql = mysqli_query($con, "SELECT * FROM state WHERE id = '$edit_row[state]'");
                                    if($state_row = mysqli_fetch_assoc($state_sql)){
                                        echo $state_name = $state_row["name"];
                                    }
                                    ?>
                                </p>

                                <p class="mb-2">
                                    <?php echo $edit_row["pin"]; ?></p>

                            </div>
                        </div>
                    </div>
                </div>
                <?php
                $sql = "SELECT * FROM data WHERE data_catagory = 'Documents' AND data_up_for = '{$_SESSION["uid"]}' AND data_recycle = '1' ORDER BY data_sl_no DESC";
                $run = mysqli_query($con, $sql);
                if(mysqli_num_rows($run)>0){
                ?>
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between mb-3">
                            <div>
                                <h3>Uploaded Documents</h3>
                            </div>
                        </div>
                        <div class="row justify-content-center">
                            <?php
                                $c = 1;
                                while ( $rows = mysqli_fetch_assoc($run) ) {
                                ?>
                            <div class="col-md-3 mb-2">
                                <a href="<?php echo $rows["data_img"];?>" target="_blank" style="text-decoration:none;">
                                    <div class="blog-preview">
                                        <img src="<?php echo $rows["data_img"];?>" class="img-fluid"
                                            alt="<?php echo $rows['data_title']; ?>">
                                        <h6 class="m-0"><?php echo $rows['data_title']; ?></h6>
                                    </div>
                                </a>
                            </div>
                            <?php $c++; }?>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>
    <script src="vendor/croppie/croppie.js"></script>

    <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 type="text/javascript">
    $(document).ready(function() {
        $('#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="fa fa-spinner fa-pulse"></i>');
            $image_crop.croppie('result', {
                type: 'canvas',
                size: 'viewport'
            }).then(function(response) {
                $.ajax({
                    url: "profile.php",
                    type: "POST",
                    data: {
                        "image": response
                    },
                    success: function(data) {
                        $('#uploadimageModal').modal('hide');
                        $('#uploaded_image').html(data);
                    }
                });
            })
        });
    });
    </script>

</body>

</html>


<?php
    if(isset($_POST['edit_cat'])){
        $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));
        $up_sql = "UPDATE users SET upass = '$upass' WHERE uid = '$_SESSION[uid]'";

        $_SESSION["uname"] = $uname;
        if(mysqli_query($con, $up_sql)){
            ?>
<script>
window.location = 'profile.php';
</script>

<?php
        }
        else{
            ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'profile.php';
}, 500);
</script>
<?php
        }
    }
?>

<?php 
    if(isset($_POST["image"]))
    {

        $data = $_POST["image"];

        $faciref = rand()."_".time();

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

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

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

        $imageSource = '../upload/profile_img/'.rand() . '.png';

        file_put_contents($imageSource, $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;
        }
        $imageName = rand() . '.png';
        $destination_img = '../upload/profile_img/'.$imageName;
        $d = compress($imageSource, $destination_img, 40);
        unlink($imageSource);
        $sql_update = "UPDATE users set uphoto= '$imageName' WHERE uid = '$_SESSION[uid]'"; 
        mysqli_query($con, $sql_update);
    }
 ?>