<?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_id = $_GET["edit_id"];
                    $edit_run = mysqli_query($con, "SELECT * FROM dist WHERE id = '$edit_id'");
                    if($edit_row = mysqli_fetch_assoc($edit_run)){

                        $sql2 = "SELECT * FROM state WHERE id  ='$edit_row[stateId]' ";
                        $run2 = mysqli_query($con, $sql2);
                        $rows2 = mysqli_fetch_assoc($run2);

                        $stateName  =  $rows2['name'] ;
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit City Name</h5>
                    <div class="card-body" style="height: calc(100vh - 160px);">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <div class="from-group">
                                        <label>Edit State Name</label>
                                        <select name="stateId" id="stateId" class="form-control" required>
                                            <option value="<?php echo $edit_row["stateId"]; ?>">
                                                <?php echo $stateName ; ?></option>
                                            <?php
                                                $sql = "SELECT * FROM state  ORDER BY id ASC";
                                                $run = mysqli_query($con, $sql);

                                                while ( $state_rows = mysqli_fetch_assoc($run) ) {
                                                    echo '
                                                    <option value="'.$state_rows["id"].'"> '.$state_rows["name"].' </option>
                                                    ';
                                                }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <div class="from-group">
                                        <label>Edit City Name</label>
                                        <input type="text" class="form-control mb-2" id="distName"
                                            placeholder="Name of City *" name="distName"
                                            value="<?php echo $edit_row["distName"]; ?>" required>
                                    </div>
                                </div>
                            </div>
                            <div class="from-group">
                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="edit_submit">
                                    <i class="fa fa-plus"></i> Edit City
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <?php } } else{?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add City</h5>
                    <div class="card-body">
                        <form method="POST">
                            <div class="row">
                                <div class="col-md-6 mb-2">
                                    <div class="from-group">
                                        <label>Select State Name</label>
                                        <select name="stateId" class="form-control" id="state">
                                            <option value="">Select State</option>
                                            <?php 
                                                $sql = "SELECT name, id FROM state ORDER BY id DESC";
                                                $res = mysqli_query($con,$sql);
                                                while ($row = mysqli_fetch_assoc($res)) {
                                                    $sid = $row['id'];
                                                    $state = $row['name'];
                                            ?>
                                            <option value="<?php echo $sid;?>">
                                                <?php echo $state;?>
                                            </option>
                                            <?php }?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <div class="from-group">
                                        <label>Enter City Name</label>
                                        <input type="text" class="form-control" id="distName"
                                            placeholder="Enter City Name" name="distName" required>
                                    </div>
                                </div>
                            </div>
                            <div class="from-group">
                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="submit">
                                    <i class="fa fa-plus"></i> Add City
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }?>
                <?php if(!isset($_GET["edit_id"])){?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <div class="col-md-6 col-4">
                                <h4 class="m-0 text-dark font-weight-bold">City List</h4>
                            </div>
                            <div class="col-md-6 col-8">
                                <div class="d-flex justify-content-end">
                                    <div class="d-flex">
                                        <div class="form-group">
                                            <input type="text" list="First" placeholder="Search State Name"
                                                class="form-control" id="FirstFilterValue">
                                            <datalist id="First">
                                                <?php 
                                                    $sql = "SELECT name, id FROM state ORDER BY id ASC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['name']; ?>">
                                                    <?php echo $row['name']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                        <div class="form-group">
                                            <input type="text" list="Second" placeholder="Search District Name"
                                                class="form-control" id="SecondFilterValue">
                                            <datalist id="Second">
                                                <?php 
                                                    $dsql = "SELECT distName, id FROM dist ORDER BY id ASC";
                                                    $dres = mysqli_query($con,$dsql);
                                                    while ($drow = mysqli_fetch_assoc($dres)) {
                                                ?>
                                                <option value="<?php echo $drow['distName']; ?>">
                                                    <?php echo $drow['distName']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                    </div>
                                    <div class="#">
                                        <button type="button" id="filter" class="btn btn-primary"> Search </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <!--loader -->
                            <div class="col-12" id='loader'>
                                <ul style="list-style: none; padding: 0;">
                                    <?php 
                                    for ($count = 0; $count < 4; $count++) {
                                        echo '<li>
                                            <div class="ph-item">
                                            <div class="ph-row">
                                            <div class="ph-col-12 big"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            <div class="ph-col-12"></div>
                                            </div>
                                            </div>
                                            </li>';
                                        }
                                    ?>
                                </ul>
                            </div>
                            <!-- loader -->
                            <div class="col-12" id="full-table">
                                <ul class="timeline" id="full-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>
                            <div class="col-12" id="filter-table" style="display: none;">
                                <ul class="timeline" id="filter-table-data" style="list-style: none; padding: 0;">
                                    </>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                <?php }?>
            </div>
        </div>

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

    <!-- JavaScript Libraries -->

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

    <script>
    $(document).ready(function() {
        var load_filter_flag = 0;
        var load_flag = 0;
        var FirstFilterValue = '';
        var SecondFilterValue = '';

        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            load_filter_flag = 0;

            if (FirstFilterValue !== '' || SecondFilterValue !== '') {
                $.ajax({
                    url: 'district-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        start: load_filter_flag
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);
                        load_filter_flag += 10;
                    },
                    complete: function() {
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Plz Select an Option');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        function loadMoreFilter(start) {
            if (load_filter_flag >= 0) {
                $.ajax({
                    url: 'district-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        start: start
                    },
                    success: function(result) {
                        $('#filter-table-data').append(result);
                        load_filter_flag += 10;
                    }
                });
            }
        }

        function loadMore(start) {
            $.ajax({
                url: 'district-Ajax.php',
                type: 'POST',
                data: {
                    start: start
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    load_flag += 10;
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        $('#inner-body').scroll(function() {
            if ($('#inner-body').scrollTop() + $('#inner-body').height() >= $('#inner-body')[0]
                .scrollHeight) {
                if (load_filter_flag > 0) {
                    loadMoreFilter(load_filter_flag);
                } else {
                    loadMore(load_flag);
                }
            }
        });
        // Initial load
        loadMore(load_flag);
    });
    </script>



</body>

</html>

<?php
if(isset($_POST['submit'])){
    $stateId = mysqli_real_escape_string($con, strip_tags($_POST['stateId']));
    $distName = mysqli_real_escape_string($con, strip_tags($_POST['distName']));

    $ins_sql = "INSERT INTO dist (stateId, distName) VALUES ( '$stateId' , '$distName')";
    if(mysqli_query($con, $ins_sql)){
        ?>
<script>
window.location = 'district.php';
</script>
<?php
    }
    else{
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'district.php';
}, 1200);
</script>
<?php
    }
}

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

if(isset($_POST['edit_submit'])){
    $stateId = mysqli_real_escape_string($con, strip_tags($_POST['stateId']));
    $distName = mysqli_real_escape_string($con, strip_tags($_POST['distName']));

    $up_sql = "UPDATE dist SET stateId = '$stateId' , distName = '$distName' WHERE id = '$_GET[edit_id]'";

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