<?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 lead_source_form_name FROM `lead_source` WHERE 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 Lead Source</h5>

                    <div class="card-body" style="height: calc(100vh - 160px);">

                        <form method="POST">

                            <div class="from-group">

                                <label for="lead_source_form_name">Edit Country Name</label>

                                <input type="text" class="form-control form-control-sm mb-2" id="lead_source_form_name"

                                    placeholder="Name of Lead Source *" name="lead_source_form_name"

                                    value="<?php echo $edit_row["lead_source_form_name"]; ?>" required>

                            </div>

                            <div class="from-group">

                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="edit_cat">

                                    <i class="fa fa-plus"></i> Update Lead Source

                                </button>

                                <a href="lead_source.php" class="btn btn-warning btn-user mt-4 text-white"> <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">Lead Source</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 Lead Source

                        </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="lead_source_form_name"

                                                placeholder="Enter Lead Source Name *" name="lead_source_form_name"

                                                required>

                                        </div>

                                    </div>



                                    <button type="submit" class="btn btn-primary btn-user mt-2" name="new_lead_source">

                                        <i class="fa fa-plus"></i> Add New Lead Source

                                    </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;">Lead Source 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 `lead_source` WHERE upload_by = '$_SESSION[uref]'  ORDER BY pos 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' style='background:lightblue;'>Lead Source Id : $rows[id]</span><br>

                                                            <span class=''>$c) </span>

                                                            $rows[lead_source_form_name]

                                                            </td>

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

                                                            ";

                                                            echo "

                                                                <a href='lead_source.php?edit_id=$rows[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='lead_source.php?del_id=$rows[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("lead_source_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_lead_source'])){

    $lead_source_form_name = mysqli_real_escape_string($con, strip_tags($_POST['lead_source_form_name']));



    $sql = "SELECT * FROM `lead_source` WHERE `upload_by`='$_SESSION[uref]' AND `lead_source_form_name`='$lead_source_form_name'";

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



    // $rows = mysqli_fetch_assoc($run);

    $num = mysqli_num_rows($run);



    if($num <= 0){



        $ins_sql = "INSERT INTO `lead_source` (`lead_source_form_name`, `upload_by`) VALUES ('$lead_source_form_name', '$_SESSION[uref]')";



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



        ?>

<script>

window.location = 'lead_source.php';

</script>

<?php

        }

        else{

        ?>

<script>

alert('OOPS !!!!');

setTimeout(() => {

    window.location = 'lead_source.php';

}, 1200);

</script>

<?php

        }

    }else{

        ?>

<script>

alert('This state already exist.');

setTimeout(() => {

    window.location = 'lead_source.php';

}, 1200);

</script>

<?php

    }

}





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



    $del_sql = "DELETE FROM `lead_source` WHERE id = '$_GET[del_id]'";



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

        ?>

<script>

window.location = "lead_source.php";

</script>

<?php

    } else {

        ?>

<script>

alert('OOPS !!!!');

setTimeout(() => {

    window.location = 'lead_source.php';

}, 500);

</script>

<?php

    }

}



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

    $lead_source_form_name = mysqli_real_escape_string($con, strip_tags($_POST['lead_source_form_name']));



    $up_sql = "UPDATE `lead_source` SET `lead_source_form_name` = '$lead_source_form_name' WHERE id = '$_GET[edit_id]'";



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

        ?>

<script>

window.location = 'lead_source.php';

</script>

<?php

    }

    else{

        ?>

<script>

alert('OOPS !!!!');

setTimeout(() => {

    window.location = 'lead_source.php?edit_id=<?php echo $_GET["edit_id"]; ?>';

}, 500);

</script>

<?php

    }

}

?>