<?php
    // session_start();
    include "../../db.php";
    require '../../auth.php';
    restrictAccess(['master_admin']);
    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();
    }

    if ( $_SESSION['utype'] != 'master_admin' && $_SESSION['uref'] != 'fssdf4543frts' ) {
        header("Location: logout.php");
        exit();
    }
?>

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

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
</head>

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

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php if(isset($_GET["edit_id"])){
                    $edit_run = mysqli_query($con, "SELECT s_name FROM status WHERE s_id = '$_GET[edit_id]'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit status</h5>
                    <div class="card-body" style="height: calc(100vh - 160px);">
                        <form method="POST">
                            <div class="from-group">
                                <label for="s_name">Edit Country Name</label>
                                <input type="text" class="form-control mb-2" id="s_name" placeholder="Name of status *"
                                    name="s_name" value="<?php echo $edit_row["s_name"]; ?>" required>
                            </div>
                            <div class="from-group">
                                <button type="submit" class="btn btn-success text-sm-center mt-4 text-white"
                                    name="edit_cat">
                                    <i class="fa fa-plus"></i> Update status
                                </button>
                                <a href="status.php" class="btn btn-warning btn-user mt-4"> <i
                                        class="fas fa-arrow-left"></i>
                                    Back
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }
                } else{?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark text-center font-weight-bold">Status</h5>
                    <div class="card-body">
                        <h4 class="mb-2 btn btn-primary m-3" data-bs-toggle="collapse" data-bs-target="#target"
                            style="cursor:pointer;">
                            Add New Status
                        </h4>

                        <div class="collapse m-3" id="target">
                            <div class="card shadow p-3">
                                <form action="" method="POST">
                                    <div class="form-group row">
                                        <div class="col-sm-12 mb-1 mb-sm-0">
                                            <input type="text" class="form-control mb-2" id="s_name"
                                                placeholder="Enter status Name *" name="s_name" required>
                                        </div>
                                    </div>

                                    <button type="submit" class="btn btn-primary btn-user mt-2" name="new_status">
                                        <i class="fa fa-plus"></i> Add New Status
                                    </button>

                                    <a href="#" class="btn btn-warning btn-user m-4" id="cancelBtn">
                                        <i class="fas fa-ban"></i> Cancel
                                    </a>
                                </form>
                            </div>
                        </div>

                        <div class="row mx-0 justify-content-center mt-4">
                            <div class="col-12">
                                <div class="row m-0">
                                    <h4 class="mb-3 text-white"
                                        style="background: #827f7f;padding: 5px;border-radius: 7px;">Status List :</h4>
                                    <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>Index</th>
                                                        <th>Action</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php
                                                $sql = "SELECT * FROM status WHERE s_by = '$_SESSION[uref]' ORDER BY s_pos ASC";
                                                $run = mysqli_query($con, $sql);
                                                $c = 1;

                                                while ($rows = mysqli_fetch_assoc($run)) {
                                                    echo "
                                                    <tr id='$rows[s_id]'>
                                                        <td>
                                                            <span class='badge bg-info rounded-pill' style='background:lightblue;'>Status Id: $rows[s_id]</span><br>
                                                            <span class=''>$c) </span> $rows[s_name]
                                                        </td>

                                                        <td class='text-center align-middle'>";
                                                        
                                                        if ($rows['s_name'] != 'Pending') {
                                                            echo "
                                                                <a href='status.php?edit_id=$rows[s_id]' class='m-2 btn btn-success btn-sm rounded-circle' title='Click to Edit'>
                                                                    <i class='fas fa-pencil-alt'></i>
                                                                </a>

                                                                <a href='status.php?del_id=$rows[s_id]' class='delete m-2 btn btn-danger btn-sm rounded-circle' title='Click to Delete'>
                                                                    <i class='fas fa-trash'></i>
                                                                </a>";
                                                        }

                                                        echo "
                                                        </td>
                                                    </tr>";
                                                    $c++;
                                                }
                                                ?>
                                                </tbody>
                                            </table><br>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <!-- JavaScript Libraries -->

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

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>

    <script>
    // toggle js
    document.addEventListener("DOMContentLoaded", function() {
        const collapseElement = document.getElementById("target");
        const cancelButton = document.getElementById("cancelBtn");

        cancelButton.addEventListener("click", function(event) {
            event.preventDefault(); // Prevent default link behavior
            let bsCollapse = new bootstrap.Collapse(collapseElement, {
                hide: true
            });
            bsCollapse.hide();
        });
    });
    </script>
    <script>
    $(document).ready(function() {
        // Initialize DataTable
        var table = $('#thisismytable').DataTable({
            paging: true, // Enable pagination
            searching: true, // Enable search box
            ordering: false, // Disable automatic ordering (manual sorting instead)
            lengthChange: true, // Show "Show Entries" dropdown
            dom: '<"row mb-3"<"col-md-6 d-flex align-items-center"l><"col-md-6 d-flex justify-content-end"f>>tip'
        });

        // Enable row sorting with jQuery UI
        var $sortable = $("#thisismytable tbody");

        $sortable.sortable({
            stop: function(event, ui) {
                var parameters = $sortable.sortable("toArray");
                $.post("status_position.php", {
                    value: parameters
                }, function(result) {
                    console.log("Position Updated Successfully");
                });
            }
        });

        // Ensure DataTable updates when sorting manually
        table.on('draw.dt', function() {
            $sortable.sortable("refresh");
        });
    });
    </script>


</body>

</html>


<?php
if(isset($_POST['new_status'])){
    $s_name = mysqli_real_escape_string($con, strip_tags($_POST['s_name']));
    $sql = "SELECT * FROM `status` WHERE `s_by`='$_SESSION[uref]' AND `s_name`='$s_name'";
    $run = mysqli_query($con, $sql);

    // $rows = mysqli_fetch_assoc($run);

    $num = mysqli_num_rows($run);

    if($num <= 0){
        $ins_sql = "INSERT INTO status (s_name, s_by) VALUES ('$s_name', '$_SESSION[uref]')";
        if(mysqli_query($con, $ins_sql)){

            ?>

<script>
window.location = 'status.php';
</script>
<?php
        }
        else{
            ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'status.php';
}, 1200);
</script>
<?php
        }
    }else{
        ?>
<script>
alert('This state already exist.');
setTimeout(() => {
    window.location = 'status.php';
}, 1200);
</script>
<?php
    }
}

if ( isset($_GET["del_id"]) ) {
    $del_sql = "DELETE FROM status WHERE s_id = '$_GET[del_id]'";
    if ( mysqli_query($con, $del_sql) ) {
    ?>
<script>
window.location = "status.php";
</script>
<?php
    } else {
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'status.php';
}, 500);
</script>
<?php
    }  
}

if(isset($_POST['edit_cat'])){
    $s_name = mysqli_real_escape_string($con, strip_tags($_POST['s_name']));
    $up_sql = "UPDATE status SET s_name = '$s_name' WHERE s_id = '$_GET[edit_id]'";

    if(mysqli_query($con, $up_sql)){
        ?>
<script>
window.location = 'status.php';
</script>
<?php
    }
    else{
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'status.php?edit_id=<?php echo $_GET["edit_id"]; ?>';
}, 500);
</script>
<?php
    }
}
?>