<?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();
    }

    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/header2.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 users WHERE uid = '$_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 Teacher Details</h5>
                    <div class="card-body" style="height: calc(100vh - 160px);">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-12">
                                    <label for="Name">Teacher Name</label>
                                    <input type="text" class="form-control" name="uname" placeholder="Enter Name"
                                        value="<?php echo $edit_row['uname']; ?>">
                                </div>
                            </div>
                            <div class="row mb-2 mt-2">
                                <div class="col-md-6">
                                    <label for="phoneNo">Phone No</label>
                                    <input type="number" class="form-control" name="ucontact"
                                        placeholder="Enter Phone Number*" value="<?php echo $edit_row['ucontact']; ?>">
                                </div>
                                <div class="col-md-6">
                                    <label for="qualification">Qualification</label>
                                    <input type="text" class="form-control" name="uqualification"
                                        placeholder="Enter Qualification*"
                                        value="<?php echo $edit_row['uqualification']; ?>">
                                </div>
                            </div>
                            <div class="row mb-2">
                                <div class="col-md-3 mb-2">
                                    <label for="state">State</label>
                                    <input type="hidden" name="state" id="state-id"
                                        value="<?php echo $edit_row["state"];?>">
                                    <?php
                                    $state_sql = mysqli_query($con, "SELECT * FROM state WHERE id = '$edit_row[state]' ");
                                    if($state_row = mysqli_fetch_assoc($state_sql)){
                                        $state_name = $state_row["name"];
                                    }
                                    ?>
                                    <input type="text" list="state" class="form-control" id="state-input"
                                        value="<?php echo $state_name;?>">
                                    <datalist id="state">
                                        <?php 
                                            $sql = "SELECT id, name FROM state ORDER BY id ASC";
                                            $res = mysqli_query($con, $sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                        ?>
                                        <option data-id="<?php echo $row['id']; ?>" value="<?php echo $row['name']; ?>">
                                            <?php echo $row['name']; ?></option>
                                        <?php } ?>
                                    </datalist>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="dist">Select District</label>
                                    <input type="hidden" name="dist" id="district-id"
                                        value="<?php echo $edit_row["dist"];?>">
                                    <?php
                                        $dist_sql = mysqli_query($con, "SELECT * FROM dist WHERE id = '$edit_row[dist]' ");
                                        if($dist_row = mysqli_fetch_assoc($dist_sql)){
                                            $dist_name = $dist_row["distName"];
                                        }
                                        ?>
                                    <input type="text" list="district-list" class="form-control" id="district-input"
                                        value="<?php echo $dist_row["distName"];?>" required>
                                    <datalist id="district-list"></datalist>
                                </div>
                                <div class="col-md-2">
                                    <label for="pinCode">Edit Pin Code</label>
                                    <input type="number" class="form-control" name="pin" placeholder="Pin*"
                                        value="<?php echo $edit_row['pin']?>">
                                </div>
                                <div class="col-md-4">
                                    <label for="address">Edit Address</label>
                                    <input type="text" class="form-control" name="saddress"
                                        placeholder="Enter Your Street Address*"
                                        value="<?php echo $edit_row['saddress']?>">
                                </div>
                            </div>
                            <h6 class="badge-dark">Login Details</h6>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="loginNumber">Login Number</label>
                                    <input type="text" class="form-control" name="uphone" placeholder="Enter User Name"
                                        value="<?php echo $edit_row['uphone']?>">
                                </div>
                                <div class="col-md-6">
                                    <label for="passWOrd">Password</label>
                                    <input type="password" class="form-control" name="upass"
                                        placeholder="Enter Password" value="<?php echo $edit_row['upass']?>">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-success" name="edit_users">
                                UPDATE
                            </button>

                            <a href="view-teacher.php" class="btn btn-warning"> <i class="fas fa-ban"></i>
                                Cancel
                            </a>
                        </form>
                    </div>
                </div>
                <?php }
                } else{?>
                <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="text-gray-800">All Teachers List</h4>
                            </div>
                            <div class="col-md-6 col-8 d-flex justify-content-end">
                                <div class="d-flex">
                                    <div style="margin-left:18px; display:flex;">
                                        <div class="form-group">
                                            <input type="text" list="Third" class="form-control" id="ThirdFilterValue"
                                                placeholder="Search By District">
                                            <datalist id="Third">
                                                <?php 
                                                    $sql = "SELECT DISTINCT distName FROM dist ORDER BY id ASC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['distName']; ?>">
                                                    <?php echo $row['distName']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                        <div class="form-group">
                                            <input type="text" list="Second" class="form-control" id="SecondFilterValue"
                                                placeholder="Search By State">
                                            <datalist id="Second">
                                                <?php 
                                                    $sql = "SELECT DISTINCT name 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="First" class="form-control" id="FirstFilterValue"
                                                placeholder="Search By Name">
                                            <datalist id="First">
                                                <?php 
                                                    $sql = "SELECT DISTINCT uname FROM users  WHERE utype = 'Teacher'  AND udisplay ='disable' ORDER BY uname ASC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['uname']; ?>">
                                                    <?php echo $row['uname']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                        <input type="hidden" class="form-control" value="">
                                    </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-left: 0;">
                                    <?php
                                    for ($count = 0; $count < 4; $count++) {
                                        echo '<li>
                                        <div class="ph-item">
                                        <div cl ass="ph-test">
                                        <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>
                                        </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"; ?>

    <!-- Modal Structure -->
    <div class="modal fade" id="teacherDetailsModal" data-bs-backdrop="static" tabindex="-1" role="dialog"
        aria-labelledby="modelTitleId" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 style="color:orange;font-size: 20px"> <i class="fa fa-user-circle"></i> <span
                            id="modalName"></span>
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6 col-6 text-end">
                            <h5 class="modal-css">User ID : </h5>
                            <h5 class="modal-css">Password : </h5>
                            <h5 class="modal-css">Qualification : </h5>
                            <h5 class="modal-css">Address : </h5>
                            <h5 class="modal-css">State : </h5>
                            <h5 class="modal-css">Dist : </h5>
                            <h5 class="modal-css">Pin : </h5>
                            <h5 class="modal-css">Date : </h5>
                        </div>
                        <div class="col-md-6 col-6">
                            <h5 class="modal-id" id="modalId"></h5>
                            <h5 class="modal-id" id="modalPass"></h5>
                            <h5 class="modal-css" id="modalqualification"></h5>
                            <h5 class="modal-css" id="modalAddress"></h5>
                            <h5 class="modal-css" id="modalState"></h5>
                            <h5 class="modal-css" id="modalDist"></h5>
                            <h5 class="modal-css" id="modalPin"></h5>
                            <h5 class="modal-css" id="modalDate"></h5>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    <script>
    $(document).ready(function() {
        $('#state-input').on('change', function() {
            var state = $(this).val();
            if (state !== '') {
                // Fetch state ID
                $.ajax({
                    url: 'fetch-state-id.php',
                    type: 'POST',
                    data: {
                        state: state
                    },
                    success: function(data) {
                        $('#state-id').val(
                            data); // Set the hidden input field with the fetched state ID
                    },
                    error: function() {
                        alert('Error fetching state ID. Please try again.');
                    }
                });

                // Fetch districts
                $.ajax({
                    url: 'fetch-district.php',
                    type: 'POST',
                    data: {
                        state: state
                    },
                    success: function(data) {
                        $('#district-list').html(
                            data); // Populate the district datalist with the fetched data
                    },
                    error: function() {
                        alert('Error loading districts. Please try again.');
                    }
                });
            } else {
                $('#state-id').val(''); // Clear the hidden input field if no state is selected
                $('#district-list').html(''); // Clear the district list if no state is selected
            }
        });

        $('#district-input').on('change', function() {
            var districtName = $(this).val();
            var districtOption = $('#district-list option').filter(function() {
                return this.value === districtName;
            });

            if (districtOption.length > 0) {
                $('#district-id').val(districtOption.data(
                    'id')); // Set the hidden input field with the district ID
            } else {
                $('#district-id').val(''); // Clear the hidden input if the selection is not valid
            }
        });
    });
    </script>

    <script>
    //dropdown TWO filter Start//
    $(document).ready(function() {
        var load_filter_flag = '';
        var FirstFilterValue = '';
        var SecondFilterValue = '';
        var ThirdFilterValue = '';

        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            ThirdFilterValue = $('#ThirdFilterValue').val();
            load_filter_flag = 0;
            if (FirstFilterValue != '' || SecondFilterValue != '' || ThirdFilterValue != '') {
                //alert(name);
                $.ajax({
                    url: 'view-teacher-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        ThirdFilterValue: ThirdFilterValue,
                        start: load_filter_flag
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);
                        load_filter_flag += 10;
                    },
                    complete: function(data) {
                        /* Hide loader container */
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Plz Select an Option');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        function loadMoreFilter(start) {
            console.log('Filter' + start);
            if (load_filter_flag > 0) {
                //alert(name);
                $.ajax({
                    url: 'view-teacher-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        ThirdFilterValue: ThirdFilterValue,
                        start: start
                    },
                    success: function(result) {
                        $('#filter-table-data').append(result);
                        load_filter_flag += 10;
                    }
                });
            }
        }
        // Scroll Loading of Full Data //
        var load_flag = 0;
        loadMore(load_flag);

        function loadMore(start) {
            //console.log('total'+start);
            $.ajax({
                url: 'view-teacher-Ajax.php',
                type: 'POST',
                data: 'start=' + start,
                success: function(result) {
                    $('#full-table-data').append(result);
                    load_flag += 10;
                },
                complete: function(data) {
                    /* Hide loader container */
                    $("#loader").hide();
                }
            });
        }

        $('#inner-body').scroll(function() {
            if ($('#inner-body').scrollTop() >= $(document).height() - $('#inner-body').height()) {
                //console.log('call');
                if (load_filter_flag > 0) {
                    loadMoreFilter(load_filter_flag);
                } else {
                    loadMore(load_flag);
                }
            }
        });
    });
    </script>

</body>

</html>


<?php
if(isset($_POST['submit'])){
    $uname = mysqli_real_escape_string($con, strip_tags($_POST['uname']));
    $ucontact = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $uqualification = mysqli_real_escape_string($con, strip_tags($_POST['uqualification']));
    $saddress = mysqli_real_escape_string($con, strip_tags($_POST['saddress']));
    $state = mysqli_real_escape_string($con, strip_tags($_POST['state']));
    $dist = mysqli_real_escape_string($con, strip_tags($_POST['dist']));
    $pin = mysqli_real_escape_string($con, strip_tags($_POST['pin']));
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['uphone']));
    $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));
    $admin_ref = $_SESSION['uref'];

    // created user reference code
        $firstTwoDigitMobileNumber = substr($ucontact, 0, 2);
        $lastTwoDigitMobileNumber = substr($ucontact, -2);
        $upperUserStr = strtoupper($uname);
        $firstTwoCharactersOfUser = substr($upperUserStr, 0, 4);
        $ref_code = rand().$firstTwoCharactersOfUser.time();

    // $uabout = mysqli_real_escape_string($con, strip_tags($_POST['uabout']));
    $chk_ph = mysqli_query($con, "SELECT uphone FROM users WHERE uphone = '$uphone'");
    $chk_ph_count = mysqli_num_rows($chk_ph);
    if ( $chk_ph_count < 1 ) {
        
        $uref = rand().'_'.time();

        $ins_sql = "INSERT INTO users (uname,uref_code, ucontact, uqualification, saddress, state, dist, pin, uphone, upass, uref, utype, admin_ref, ucreated) VALUES ('$uname','$ref_code', '$ucontact', '$uqualification', '$saddress', '$state', '$dist', '$pin', '$uphone', '$upass', '$uref', 'Admin', '$admin_ref', '$currentTime')";

        //  echo "<pre>";print_r($ins_sql);exit();

        if(mysqli_query($con, $ins_sql)){
            ?>
<script>
window.location = 'view-teacher.php';
</script>
<?php
        }
        else{
            ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-teacher.php?add_admin';
}, 1200);
</script>
<?php
        }
    } else {
        ?>
<script>
alert('Mobile Number Exists');
setTimeout(() => {
    window.location = 'view-teacher.php?add_admin';
}, 500);
</script>
<?php
    }
}
?>

<?php
if(isset($_POST['edit_users'])){
    $uname = mysqli_real_escape_string($con, strip_tags($_POST['uname']));
    $ucontact = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $uqualification = mysqli_real_escape_string($con, strip_tags($_POST['uqualification']));
    $saddress = mysqli_real_escape_string($con, strip_tags($_POST['saddress']));
    $state = mysqli_real_escape_string($con, strip_tags($_POST['state']));
    $dist = mysqli_real_escape_string($con, strip_tags($_POST['dist']));
    $pin = mysqli_real_escape_string($con, strip_tags($_POST['pin']));
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['uphone']));
    $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));

    $up_sql = "UPDATE users SET uname = '$uname', ucontact = '$ucontact', uqualification = '$uqualification',  saddress = '$saddress', state = '$state', dist = '$dist', pin = '$pin',  uphone = '$uphone', upass = '$upass', ucreated = '$currentTime' WHERE uid = '$_GET[edit_id]'";

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

<?php
if ( isset($_GET["del_id"]) ) {
$disable_sql = "UPDATE users SET udisplay='' WHERE uid = '$_GET[del_id]'";
    if ( mysqli_query($con, $disable_sql) ) {
        ?>
<script>
window.location = "view-teacher.php";
</script>
<?php
    } else {
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-teacher.php';
}, 1200);
</script>
<?php
    }
}
?>