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

        exit();

    }



    $page_type = $_GET['sec'];

    $page_url = 't1d1i1.php?sec='.$page_type ;

    $pageHeaderSql = "SELECT * FROM nav_page_type_master WHERE page_type = '$page_type' ";

    $pageHeaderRun = mysqli_query($con, $pageHeaderSql);

    $pageHeaderRow = mysqli_fetch_assoc($pageHeaderRun);

    $pageHeaderRun = mysqli_num_rows($pageHeaderRun) ;

    $pageHeaderName = $pageHeaderRow['page_header_name'] ;

?>

<script>
var page_url = '<?=$page_url?>';
</script>



<!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" />
</head>



<body id="page-top" class="mt-55">
    <?php include "includes/header2.php"; ?>
    <div class="container">
        <div class="row mx-0 just ify-content-center">
            <div class="col-12 col-sm-12 col-md-12">
                <div class="card-body">
                    <h1 class="h2 mb-2 text-gray-800 text-sm-center" style="margin-top: 70px">
                        <?php echo $pageHeaderName ; ?></h1>
                    <hr>
                    <?php
                                if ( isset($_GET["edit_id"]) ) {
                                     $edit_run = mysqli_query($con, "SELECT * FROM data_table WHERE refid = '$_GET[edit_id]' ");
                                     $edit_row = mysqli_fetch_assoc($edit_run);
                                    ?>
                    <form class="user" method="post" enctype="multipart/form-data">
                        <h4 class="mb-3 badge badge-secondary">Edit <?php echo $pageHeaderName ; ?></h4>

                        <div class="form-group row">



                            <div class="col-md-12">

                                <label color="black">Title</label>

                                <input type="text" name="title" class="form-control mb-3" placeholder="Enter title *"
                                    value="<?php echo $edit_row['title']; ?>" required>

                            </div>

                            <div class="col-md-12">

                                <label color="black">First Short Description</label>

                                <textarea name="short_des" class="form-control mb-3"
                                    placeholder="Enter a short description"><?php echo $edit_row['short_des']; ?></textarea>

                            </div>


                            <div class="col-md-4 mt-4">

                                <?php 

                                    if (!empty($edit_row['image_one'])) {
                                    $edit_image_one_url = $edit_row['image_one'] ;
                                    }else{
                                    $edit_image_one_url = '../upload/blog/image.png' ;
                                    }
                                ?>

                                <label color="black">Upload Image 1</label>

                                <img id="profile" src="<?php echo $edit_image_one_url ; ?>" class="mb-2"
                                    alt="your image" width="100%" height="200px" />

                                <input type="file" name="image_one" class="mt-3"
                                    onchange="document.getElementById('profile').src = window.URL.createObjectURL(this.files[0])">

                            </div>

                        </div>

                        <button type="submit" class="btn btn-success btn-user m-2" name="edit_submit">

                            <i class="far fa-image"></i> Update <?php echo $pageHeaderName ; ?>

                        </button>

                        <a href="<?php echo $page_url ;?>" class="btn btn-warning btn-user m-2"> <i
                                class="fas fa-ban"></i> Cancel </a>

                    </form>

                    <?php

                                }  elseif(isset($_GET["view_id"]) ) {

                                     $view_run = mysqli_query($con, "SELECT * FROM data_table WHERE refid = '$_GET[view_id]' ");

                                     $view_row = mysqli_fetch_assoc($view_run);

                                ?>

                    <h4 class="mb-3 badge badge-secondary">View <?php echo $pageHeaderName ; ?> Details</h4>

                    <div class="form-group row">



                        <div class="col-md-12">

                            <label color="black">Title</label> : <?php echo $view_row['title']; ?>

                        </div>

                        <div class="col-md-12">

                            <label color="black">Short Description</label> : <?php echo $view_row['short_des']; ?>

                        </div>
                        <?php 

                            if (!empty($view_row['up_date'])) {

                        ?>

                        <div class="col-md-12">

                            <label color="black">Upload Date</label> :
                            <?php echo date('d-m-Y',strtotime($view_row['up_date'])) ; ?>

                        </div>

                        <?php

                            }

                            if (!empty($view_row['edit_date'])) {

                        ?>

                        <div class="col-md-12">

                            <label color="black">Last Modification Date</label> :
                            <?php echo date('d-m-Y',strtotime($view_row['edit_date'])) ; ?>

                        </div>

                        <?php

                            }

                            if (!empty($view_row['image_one'])) {

                          ?>

                        <div class="col-md-3  mt-2">

                            <label color="black">Upload Image 1</label>

                            <img id="prof" src="<?php echo $view_row['image_one'] ; ?>" class="mb-2" alt="image"
                                width="100%" />

                        </div>

                        <?php

                            }

                        ?>

                    </div>

                    <a href="<?php echo $page_url ;?>" class="btn btn-warning btn-user m-2"> <i class="fas fa-ban"></i>
                        Cancel </a>



                    <?php

                                } else {

                                ?>

                    <form class="user" method="post" enctype="multipart/form-data">

                        <h4 class="mb-1 badge badge-secondary" data-toggle="collapse" data-target="#target"
                            style="cursor:pointer;">Add New <?php echo $pageHeaderName ; ?></h4>

                        <p class="small"> <i class="fas fa-hand-point-up"></i> Tap Here to add New
                            <?php echo $pageHeaderName ; ?> </p>

                        <div class="collapse" id="target">

                            <div class="form-group row">

                                <div class="col-md-12">

                                    <label color="black">Title</label>

                                    <input type="text" name="title" class="form-control mb-3"
                                        placeholder="Enter title *">

                                </div>
                                <div class="col-md-12">

                                    <label color="black">First Short Description</label>

                                    <textarea type="text" name="short_des" class="form-control mb-3"
                                        placeholder="Enter a short description *"></textarea>

                                </div>
                                <div class="col-md-6">

                                    <label color="black">Upload Image 1</label>

                                    <img id="profile" class="mb-2" alt="your image" src="../upload/blog/image.png"
                                        width="auto" height="200" />

                                    <input type="file" name="image_one"
                                        onchange="document.getElementById('profile').src = window.URL.createObjectURL(this.files[0])">

                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary btn-user m-1" name="add_submit">

                                <i class="fas fa-user-plus"></i> Add New <?php echo $pageHeaderName ; ?>

                            </button>

                            <a href="#target" data-toggle="collapse" class="btn btn-warning btn-user m-1"> <i
                                    class="fas fa-ban"></i> Cancel </a>

                        </div>

                    </form>

                    <?php

                                }

                            ?>

                    <hr>
                    <!-- Active & Inactive Listing Table ../start -->

                    <?php 

                            if (!empty($_GET['data']) && $_GET['data'] == 'inactive') {

                            ?>

                    <div class="row m-0">

                        <div class="col-md-12 p-0">

                            <div class="well well-sm">

                                <b class="text-center">Inactive <?php echo $pageHeaderName ; ?> List</b>

                                <a href="<?php echo $page_url ;?>" class="btn btn-primary btn-sm float-right"
                                    style=" margin-top:-5px;">

                                    View Active <?php echo $pageHeaderName ; ?> List

                                </a>

                            </div>

                        </div>

                        <div class="col-md-12 p-0">

                            <div class="table-responsive">

                                <table class="table table-hover table-bordered table-sm" id="thisismytable2">

                                    <thead>

                                        <tr>

                                            <th>Sl.no.</th>

                                            <th>All Details</th>

                                            <th>Action</th>

                                        </tr>

                                    </thead>

                                    <tbody>

                                        <?php

                                                    $sql = "SELECT * FROM data_table  WHERE page_type = '$page_type' AND up_by = '$_SESSION[uid]' && recycle = '0' ORDER BY id DESC";

                                                    $run = mysqli_query($con, $sql);

                                                    $c = 1;                                                  

                                                    while ( $rows = mysqli_fetch_assoc($run) ){

                                                        echo "

                                                        <tr id='$rows[id]'>

                                                            <td>

                                                                <span class='badge badge-info badge-pill'>$c</span>

                                                            </td>

                                                            <td class='text-left align-middle'>

                                                                <b>Title:</b> $rows[title] <br>

                                                            </td>

                                                            <td class='text-center align-middle'>

                                                                <a href='$page_url&data=inactive&restore_id=$rows[refid]' class='m-2 btn btn-warning btn-sm rounded-circle' title='Click to Restore'> <i class='fas fa-recycle'></i> </a>

                                                                <a href='$page_url&data=inactive&del_id=$rows[refid]' class='m-2 btn btn-warning btn-sm rounded-circle' title='Click to Delete'> <i class='fas fa-trash'></i> </a>

                                                            </td>

                                                        </tr>

                                                        ";

                                                        $c++;

                                                    }

                                                ?>

                                    </tbody>

                                </table>

                            </div>

                        </div>

                    </div>

                    <?php

                            }else{

                            ?>

                    <div class="row m-0">

                        <div class="col-md-12 p-0">

                            <div class="well well-sm justify-content-center">

                                <b class="text-center"><?php echo $pageHeaderName ; ?> List</b>

                                <a href="<?php echo $page_url.'&data=inactive' ;?>"
                                    class="btn btn-primary btn-sm float-right" style=" margin-top:-5px;">

                                    View In-Active <?php echo $pageHeaderName ; ?> List

                                </a>

                            </div>

                        </div>

                        <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>Sl.no.</th>

                                            <th>All Details</th>

                                            <th>Action</th>

                                        </tr>

                                    </thead>

                                    <tbody>

                                        <?php

                                                    $sql = "SELECT * FROM data_table  WHERE page_type = '$page_type' AND up_by = '$_SESSION[uid]' && recycle = '1' ORDER BY position ASC";

                                                    $run = mysqli_query($con, $sql);

                                                    $c = 1;                                                  

                                                    while ( $rows = mysqli_fetch_assoc($run) ){

                                                        echo "

                                                        <tr id='$rows[id]'>

                                                            <td>

                                                                <span class='badge badge-info badge-pill'>$c</span>

                                                            </td>

                                                            <td class='text-left align-middle'>

                                                                <b>Title:</b> $rows[title] <br>

                                                                <b>View:</b> $rows[view_count] <br>

                                                            </td>

                                                            <td class='text-center align-middle'>



                                                                <a href='$page_url&view_id=$rows[refid]' class='m-2 btn btn-success btn-sm rounded-circle' title='Click to Edit'> <i class='fas fa-eye'></i> </a>



                                                                <a href='$page_url&edit_id=$rows[refid]' class='m-2 btn btn-success btn-sm rounded-circle' title='Click to Edit'> <i class='fas fa-pencil-alt'></i> </a>



                                                                <a href='$page_url&recycle_id=$rows[refid]' 

                                                                class='m-2 btn btn-warning btn-sm rounded-circle' title='Move to Recycle'> <i class='fas fa-recycle'></i> </a> <br>
                                                            </td>

                                                        </tr>

                                                        ";

                                                        $c++;

                                                    }

                                                ?>

                                    </tbody>

                                </table>

                            </div>

                        </div>

                    </div>

                    <?php

                            }

                            ?>

                    <!-- Active & Inactive Listing Table --/end -->

                </div>

            </div>



        </div>



    </div>





    <!--============modal================== -->



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

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

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





    <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>
    $(document).ready(function() {

        $('#thisismytable2').DataTable();

    });



    $(document).ready(function() {

        $('#thisismytable').DataTable();

    });

    var $sortable = $("#thisismytable > tbody");



    $sortable.sortable({

        stop: function(event, ui) {

            var parameters = $sortable.sortable("toArray");

            $.post("active_list_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

                    });

                });

            });

        }

    });
    </script>



</body>

</html>



<?php



    if(isset($_POST['add_submit'])){



        // User Input

        $title = $_POST["title"];
        $short_des = $_POST["short_des"];


        // Auto Input

        $up_date = date("Y-m-d");

        $up_ip = $_SERVER['REMOTE_ADDR'];

        $up_by = $_SESSION['uid'] ;

        $refid = $up_by. "digix" . mt_rand(0, 9999) . substr(time(), -5);



        // Image Upload

            if (!empty($_FILES["image_one"]["name"])) {

                $image = $_FILES["image_one"]["name"];

                // Valid extension

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

                $photoExt1 = @end(explode('.', $image)); // explode the image name to get the extension

                $phototest1 = strtolower($photoExt1);

                $new_profle_pic = '../upload/blog/'.time(). mt_rand(0, 9999).'.'.$phototest1;

                // Location

                $location = "".$new_profle_pic;

                // Check extension

                if(in_array($phototest1,$valid_ext)){  

                    // upload images

                    move_uploaded_file($_FILES["image_one"]["tmp_name"],$location);

                     

                }else{

                        echo "File format is not correct.";

                }

            }else{

                $new_profle_pic = '';

            }

        $ins_sql = "INSERT INTO `data_table` 

                    (`refid`, `title`, `page_type`, `short_des`, `image_one`, `up_by`, `up_date`, `up_ip`) 

                    VALUES ('$refid', '$title', '$page_type', '$short_des', '$new_profle_pic', '$up_by', '$up_date', '$up_ip');";

        if(mysqli_query($con, $ins_sql)){

            ?>

<script>
alert('success');

window.location = page_url;
</script>

<?php

        }else{

            ?>

<script>
alert('OOPS !!!!');

setTimeout(() => {

    window.location = page_url;

}, 500);
</script>

<?php

        }

    }

    if (isset($_GET["recycle_id"])) {

        $recycle_sql = "UPDATE data_table SET recycle = '0' WHERE refid = '$_GET[recycle_id]'";

        if (mysqli_query($con, $recycle_sql)) {

            ?>

<script>
alert('Successfully recycled');

window.location = page_url;
</script>

<?php

        } else {

        ?>

<script>
alert('OOPS !!!!');

setTimeout(() => {

    window.location = page_url;

}, 1200);
</script>

<?php

        }

    }


    if (isset($_GET["restore_id"])) {
        $recycle_sql = "UPDATE data_table SET recycle = '1' WHERE refid = '$_GET[restore_id]'";

        if (mysqli_query($con, $recycle_sql)) {

            ?>

<script>
alert('Successfully Restored');

window.location = page_url + '&data=inactive';
</script>

<?php

        } else {

        ?>

<script>
alert('OOPS !!!!');

setTimeout(() => {

    window.location = page_url + '&data=inactive';

}, 1200);
</script>

<?php

        }

    }

    

    if (isset($_GET["del_id"])) {



        $recycle_sql = "DELETE FROM data_table WHERE refid = '$_GET[del_id]'";



        if (mysqli_query($con, $recycle_sql)) {

            ?>

<script>
alert('Successfully Deleted');

window.location = page_url + '&data=inactive';
</script>

<?php

        } else {

        ?>

<script>
alert('OOPS !!!!');

setTimeout(() => {

    window.location = page_url + '&data=inactive';

}, 1200);
</script>

<?php
        }
    }

    if(isset($_POST['edit_submit'])){
        $pre_sql = "SELECT * FROM data_table WHERE refid = '$_GET[edit_id]' ";

        $pre_result = mysqli_query($con, $pre_sql); // Execute the SELECT query

        $pre_row = mysqli_fetch_assoc($pre_result); // Fetch the row from the result set



        $pre_image_one = $pre_row["image_one"];

        if(!empty($pre_row)){



            // User Input

            $title = $_POST["title"];
            $short_des = $_POST["short_des"];


            // Auto Input

            $edit_date = date("Y-m-d");
            $edit_ip = $_SERVER['REMOTE_ADDR'];


            // Image Upload

            if (!empty($_FILES["image_one"]["name"])) {



                $image = $_FILES["image_one"]["name"];

                // Valid extension

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

                $photoExt1 = @end(explode('.', $image)); // explode the image name to get the extension

                $phototest1 = strtolower($photoExt1);

                $new_profle_pic = '../upload/blog/'.time(). mt_rand(0, 9999).'.'.$phototest1;

                // Location

                $location = "".$new_profle_pic;

                // Check extension

                if(in_array($phototest1,$valid_ext)){  

                    // upload images

                    move_uploaded_file($_FILES["image_one"]["tmp_name"],$location);

                    // Delete the old image if it exists

                    if (!empty($pre_image_one)) {

                        unlink($pre_image_one);

                    } 

                }else{

                        echo "File format is not correct.";

                }

            }else{

                $new_profle_pic = $pre_image_one;

            }


            $up_sql = "UPDATE data_table SET title = '$title', short_des = '$short_des', edit_date = '$edit_date', edit_ip = '$edit_ip', image_one = '$new_profle_pic' WHERE refid = '$_GET[edit_id]'";

            if(mysqli_query($con, $up_sql)){

                ?>

<script>
alert('Update Success');

window.location = page_url;
</script>

<?php

            }else{

                ?>

<script>
alert('OOPS !!!!');

setTimeout(() => {

    window.location = page_url;

}, 500);
</script>

<?php

            }

        }

    }

?>