<?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"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</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 users WHERE uid = '$_GET[edit_id]'");
                    
                    if($edit_row = mysqli_fetch_assoc($edit_run)){
                        $country_sql = mysqli_query($con, "SELECT * FROM countries WHERE id = '$edit_row[ucountry]' ");
                        if($country_row = mysqli_fetch_assoc($country_sql)){
                            $country_name = $country_row["name"];
                        }
                        $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"];
                        }
                        $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"];
                        }
                    ?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Edit Employee Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row mb-2 mt-2">
                                <div class="col-md-8 mb-2">
                                    <label for="Name">Employee Name</label>
                                    <input type="text" class="form-control" name="uname"
                                        pattern="^[A-Za-z]+(?:\s[A-Za-z]+)*$"
                                        title="Only alphabets and space between two word are allowed, and extra space not allowed."
                                        value="<?php echo $edit_row['uname']; ?>">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="uType" class="">Employee Type</label>
                                    <select class="form-control" name="utype" required>
                                        <option value="<?php echo$edit_row["utype"];?>"><?php echo$edit_row["utype"];?>
                                        </option>
                                        <option value="Employee">Employee</option>
                                        <!--<option value="Manager">Manager</option>-->
                                    </select>
                                </div>
                                <div class="col-md-4">
                                    <label for="phoneNo">Phone No</label>
                                    <input type="number" class="form-control" name="ucontact"
                                        placeholder="Enter Phone Number*" value="<?php echo $edit_row['ucontact']; ?>"
                                        minlength="10" maxlength="10" oninput="this.value=this.value.slice(0,10)">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="whatsapp">Whatsapp Number</label>
                                    <input type="number" class="form-control" name="whatsapp"
                                        value="<?php echo $edit_row["uwhatsapp"];?>" required minlength="10"
                                        maxlength="10" oninput="this.value=this.value.slice(0,10)">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="email">Email Id</label>
                                    <input type="email" class="form-control" name="email"
                                        value="<?php echo $edit_row["uemail"];?>" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="country">Edit Country:</label>
                                    <input type="hidden" name="country" id="country-id"
                                        value="<?php echo $edit_row["ucountry"];?>">
                                    <input type="text" list="country-list" class="form-control" id="country-input"
                                        value="<?php echo $country_name;?>">
                                    <datalist id="country-list">
                                        <?php 
                                            $sql = "SELECT id, name FROM countries ORDER BY name 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-4 mb-2">
                                    <label for="state">Edit State:</label>
                                    <input type="hidden" name="state" id="state-id"
                                        value="<?php echo $edit_row["state"];?>">
                                    <input type="text" list="state-list" class="form-control" id="state-input"
                                        value="<?php echo $state_name;?>">
                                    <datalist id="state-list">
                                        <?php
                                            if (!empty($edit_row["state"])) {
                                                echo "<option data-id='{$edit_row["state"]}' value='{$state_name}'>{$state_name}</option>";
                                            }
                                        ?>
                                    </datalist>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label for="dist">Edit District:</label>
                                    <input type="hidden" name="dist" id="district-id"
                                        value="<?php echo $edit_row["dist"];?>">
                                    <input type="text" list="district-list" class="form-control" id="district-input"
                                        value="<?php echo $dist_name;?>" required>
                                    <datalist id="district-list">
                                        <?php
                                            if (!empty($edit_row["dist"])) {
                                                echo "<option data-id='{$edit_row["dist"]}' value='{$dist_name}'>{$dist_name}</option>";
                                            }
                                        ?>
                                    </datalist>
                                </div>
                                <div class="col-md-6">
                                    <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 class="col-md-3">
                                    <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-3 mb-2">
                                    <label for="logo">Profile Image <a target="_blank"
                                            href="<?php echo $edit_row["ulogo"];?>"><i class="fa fa-eye"></i>
                                            view</a></label>
                                    <input type="file" name="logo" class="form-control" placeholder="Upload logo">
                                    <input type="hidden" name="logoOld" class="form-control"
                                        value="<?php echo $edit_row["ulogo"]?>">
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="about">About Employee</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"><?php echo $edit_row["uabout"];?></textarea>
                                </div>
                            </div>
                            <h6 class="badge-dark">Login Details</h6>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="passWOrd">Password</label>
                                    <input type="text" 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-employee.php" class="btn btn-warning text-white"> <i
                                    class="fa fa-arrow-left"></i>
                                Back
                            </a>
                        </form>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["add_employee"])){?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add Employee</h5>
                    <div class="card-body">
                        <form method="POST" enctype="multipart/form-data">
                            <div class="row mb-3">
                                <div class="col-md-8 mb-2">
                                    <label for="uName" class="">Employee Name</label>
                                    <input type="text" class="form-control" name="uname"
                                        pattern="^[A-Za-z]+(?:\s[A-Za-z]+)*$"
                                        title="Only alphabets and space between two word are allowed, and extra space not allowed."
                                        placeholder="Enter Name" required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="uType" class="">Employee Type</label>
                                    <select class="form-control" name="utype" required>
                                        <option value="Employee">Employee</option>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="phoneNo">Phone No</label>
                                    <input type="number" class="form-control" name="ucontact" id="ucontact"
                                        placeholder="Enter Your phone Number" oninput="validateWhatsAppNumber()"
                                        required>
                                    <small id="ucontact-error" style="color: red; display: none;">Please enter a valid
                                        10-digit number.</small>

                                    <script>
                                    function validateWhatsAppNumber() {
                                        const input = document.getElementById('ucontact');
                                        const error = document.getElementById('ucontact-error');

                                        // Convert input value to string for consistent length checking
                                        const number = input.value.toString();

                                        if (number.length === 10 && /^[0-9]+$/.test(number)) {
                                            error.style.display = 'none'; // Hide error if valid
                                        } else {
                                            error.style.display = 'block'; // Show error if invalid
                                        }
                                    }
                                    </script>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="whatsapp">Whatsapp Number</label>
                                    <input type="number" class="form-control" name="whatsapp"
                                        placeholder="Enter Whatsapp Number*" required minlength="10" maxlength="10"
                                        oninput="this.value=this.value.slice(0,10)">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="email">Email Id</label>
                                    <input type="email" class="form-control" name="email" placeholder="Enter Email Id*"
                                        required>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="country">Country</label>
                                    <input type="hidden" name="country" id="country-id" value="">
                                    <input type="text" list="country-list" class="form-control" id="country-input"
                                        placeholder="Select from the list">
                                    <datalist id="country-list">
                                        <?php 
                                            $sql = "SELECT id, name FROM countries ORDER BY name 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-4 mb-2">
                                    <label for="state">State</label>
                                    <input type="hidden" name="state" id="state-id" value="">
                                    <input type="text" list="state-list" class="form-control" id="state-input"
                                        placeholder="Select from the list">
                                    <datalist id="state-list"></datalist>
                                </div>

                                <div class="col-md-4 mb-2">
                                    <label for="dist">District</label>
                                    <input type="hidden" name="dist" id="district-id" value="">
                                    <input type="text" list="district-list" class="form-control" id="district-input"
                                        placeholder="Select from the list">
                                    <datalist id="district-list"></datalist>
                                </div>
                                <div class="col-md-6 mb-2">
                                    <label for="address">Address</label>
                                    <input type="text" class="form-control" name="saddress"
                                        placeholder="Enter Your Street Address*" required>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="pinCode">Pin Code</label>
                                    <input type="number" class="form-control" name="pin" placeholder="Pin*" required>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="logo">Profile Image</label>
                                    <input type="file" name="logo" id="logo" class="form-control"
                                        accept=".jpg, .jpeg, .png" placeholder="Upload Image">
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="about">About Employee</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"></textarea>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 mb-2">
                                    <h6 class="badge-dark m-0">Login Details</h6>
                                </div>
                                <!--<div class="col-md-6 mb-2">
                                    <input type="text" class="form-control" name="uphone" placeholder="Enter User Name"
                                        required>
                                </div>-->
                                <div class="col-md-6 mb-2">
                                    <input type="text" class="form-control" name="upass" placeholder="Enter Password"
                                        required>
                                </div>
                            </div>
                            <div class="">
                                <button type="submit" class="btn btn-success text-sm-center mt-4" name="submit">
                                    <i class="fa fa-plus"></i> Add Employee
                                </button>
                                <a href="view-employee.php" class="btn btn-warning btn-user mt-4 text-white"> <i
                                        class="fa fa-arrow-left"></i> Back </a>
                            </div>
                        </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">
                                <div class="d-flex justify-content-between">
                                    <h4 class="text-gray-800">Employee List</h4>
                                    <a class="btn btn-primary btn-sm" href="view-employee.php?add_employee"><i
                                            class="fa fa-user-plus"></i> Add
                                        Employee</a>
                                </div>
                            </div>
                            <div class="col-md-6 mt-1">
                                <div class="d-flex">
                                    <div class="w-100">
                                        <div class="form-group">
                                            <input type="text" list="First" class="form-control form-control-sm"
                                                id="FirstFilterValue" placeholder="Search By Employee Name">
                                            <datalist id="First">
                                                <?php 
                                                    $sql = "SELECT uname FROM users  WHERE utype = 'Employee' AND udisplay !='disable' AND reg_approved != '0' 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="" id="SecondFilterValue">
                                    </div>
                                    <div class="#">
                                        <button type="button" id="filter" class="btn btn-primary btn-sm"> 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 class="text-center mt-3" id="load-more-container">
                                <button id="loadMoreBtn" class="btn btn-info btn-sm text-white">Load More</button>
                                <div id="endMessage" class="text-muted mt-2" style="display: none;">End of result</div>
                            </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="adminDetailsModal" 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"></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">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="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>
    CKEDITOR.replace('content', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });
    </script>

    <script>
    $(document).ready(function() {
        // Country selection event
        $('#country-input').on('change', function() {
            var countryName = $(this).val();
            var countryOption = $('#country-list option').filter(function() {
                return this.value === countryName;
            });

            if (countryOption.length > 0) {
                var countryId = countryOption.data('id');
                $('#country-id').val(countryId);

                // Fetch states based on country ID
                $.ajax({
                    url: 'fetch-state.php',
                    type: 'POST',
                    data: {
                        country_id: countryId
                    },
                    success: function(data) {
                        $('#state-list').html(data);
                        $('#state-id').val('');
                        $('#state-input').val('');
                        $('#district-list').html('');
                        $('#district-id').val('');
                        $('#district-input').val('');
                    },
                    error: function() {
                        alert('Error loading states. Please try again.');
                    }
                });
            } else {
                $('#country-id').val('');
                $('#state-list').html('');
                $('#district-list').html('');
            }
        });

        // State selection event
        $('#state-input').on('change', function() {
            var stateName = $(this).val();
            var stateOption = $('#state-list option').filter(function() {
                return this.value === stateName;
            });

            if (stateOption.length > 0) {
                var stateId = stateOption.data('id');
                $('#state-id').val(stateId);

                // Fetch districts based on state ID
                $.ajax({
                    url: 'fetch-district.php',
                    type: 'POST',
                    data: {
                        state_id: stateId
                    },
                    success: function(data) {
                        $('#district-list').html(data);
                        $('#district-id').val('');
                        $('#district-input').val('');
                    },
                    error: function() {
                        alert('Error loading districts. Please try again.');
                    }
                });
            } else {
                $('#state-id').val('');
                $('#district-list').html('');
            }
        });

        // District selection event
        $('#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'));
            } else {
                $('#district-id').val('');
            }
        });
    });
    </script>

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

        var FirstFilterValue = '';
        var SecondFilterValue = '';

        // Initial unfiltered data load
        loadMore(load_flag);

        // Filter Button Click
        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();

            load_filter_flag = 0;
            load_flag = 0;

            $('#loadMoreBtn').show();
            $('#endMessage').hide();

            if (FirstFilterValue != '' || SecondFilterValue != '') {
                $.ajax({
                    url: 'view-employee-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue: FirstFilterValue,
                        SecondFilterValue: SecondFilterValue,
                        start: load_filter_flag
                    },
                    beforeSend: function() {
                        $("#loader").show();
                        $("#loadMoreBtn").hide();
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);

                        const newItems = $('<div>').html(result).find('li');
                        load_filter_flag += newItems.length;

                        if (newItems.length < 10) {
                            $('#loadMoreBtn').hide();
                            $('#endMessage').show();
                        } else {
                            $('#loadMoreBtn').show();
                            $('#endMessage').hide();
                        }
                    },
                    complete: function() {
                        $("#loader").hide();
                    }
                });
            } else {
                alert('Please select at least one filter option.');
                $('#full-table').show();
                $('#filter-table').hide();
            }
        });

        // Load More Button Click
        $('#loadMoreBtn').click(function() {
            if ($('#filter-table').is(':visible')) {
                loadMoreFilter(load_filter_flag);
            } else {
                loadMore(load_flag);
            }
        });

        // Load more for filtered data
        function loadMoreFilter(start) {
            $.ajax({
                url: 'view-employee-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue: FirstFilterValue,
                    SecondFilterValue: SecondFilterValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#filter-table-data').append(result);
                    const newItems = $('<div>').html(result).find('li');
                    load_filter_flag += newItems.length;

                    if (newItems.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }

        // Load more for unfiltered data
        function loadMore(start) {
            $.ajax({
                url: 'view-employee-Ajax.php',
                type: 'POST',
                data: {
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    const newItems = $('<div>').html(result).find('li');
                    load_flag += newItems.length;

                    if (newItems.length < 10) {
                        $('#loadMoreBtn').hide();
                        $('#endMessage').show();
                    } else {
                        $('#loadMoreBtn').show();
                        $('#endMessage').hide();
                    }
                },
                complete: function() {
                    $("#loader").hide();
                }
            });
        }
    });
    </script>


</body>

</html>

<?php
// Include PHPMailer files
require_once '../PHPMailer/src/Exception.php';
require_once '../PHPMailer/src/PHPMailer.php';
require_once '../PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Check if the form was submitted
if (isset($_POST['submit'])) {
    // Database connection should be initialized here
    if (!isset($con)) {
        die('Database connection not established.');
    }

    // Sanitize user inputs
    $uname = mysqli_real_escape_string($con, strip_tags($_POST['uname']));
    $ucontact = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $saddress = mysqli_real_escape_string($con, strip_tags($_POST['saddress']));
    $country = mysqli_real_escape_string($con, strip_tags($_POST['country']));
    $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']));
    $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));
    $email = mysqli_real_escape_string($con, strip_tags($_POST['email']));
    $whatsapp = mysqli_real_escape_string($con, strip_tags($_POST['whatsapp']));
    $utype = mysqli_real_escape_string($con, strip_tags($_POST['utype']));
    $about = $_POST['about'];

    $admin_ref = $_SESSION['uref'] ?? '';
    $referralCode = generateReferralCode($con);

    // Validate mobile number
    if (!preg_match('/^[0-9]{10}$/', $ucontact)) {
        echo "<script>
            alert('Enter a valid 10-digit number.');
            window.location.href = 'view-employee.php?add_employee';
        </script>";
        exit;
    }

    // Check if the phone number or email already exists
    $chk_ph_query = "SELECT ucontact, uemail FROM users WHERE ucontact = '$ucontact' OR uemail = '$email'";
    $chk_ph = mysqli_query($con, $chk_ph_query);

    if (mysqli_num_rows($chk_ph) > 0) {
        $existingRecord = mysqli_fetch_assoc($chk_ph);
        if ($existingRecord['ucontact'] === $ucontact && $existingRecord['uemail'] === $email) {
            showErrorAndRedirect('Both Mobile Number and Email already exist.');
        } elseif ($existingRecord['ucontact'] === $ucontact) {
            showErrorAndRedirect('Mobile Number already exists.');
        } elseif ($existingRecord['uemail'] === $email) {
            showErrorAndRedirect('Email already exists.');
        }
    }

    // Generate unique reference and file name
    $uref = bin2hex(random_bytes(8)) . '_' . time();
    $logopath = uploadLogo();

    // Insert user data
    $ins_sql = "INSERT INTO users (uname, uref_code, ucontact, saddress, state, dist, pin, upass, uref, utype, admin_ref, ucreated, uemail, uwhatsapp, uabout, ulogo, referal_code, uphone, ucountry) 
        VALUES ('$uname', '$uref', '$ucontact', '$saddress', '$state', '$dist', '$pin', '$upass', '$uref', '$utype', '$admin_ref', '$currentTime', '$email', '$whatsapp', '$about', '$logopath', '$referralCode', '$uphone', '$country')";

    if (mysqli_query($con, $ins_sql)) {
        sendEmail($email, $uname, $ucontact, $upass);
    } else {
        showErrorAndRedirect('Error adding user.');
    }
}

// Function to send an email using PHPMailer
function sendEmail($email, $uname, $ucontact, $upass)
{
    $mail = new PHPMailer(true);

    try {
        // SMTP Configuration
        $mail->isSMTP();
        $mail->Host = 'ayushlpo.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'contact@ayushlpo.com';
        $mail->Password = 'cKIcxib89a0R';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;

        // Email Settings
        $mail->setFrom('contact@ayushlpo.com', 'Ayush LPO');
        $mail->addAddress($email, $uname);

        // Email Content
        $mail->isHTML(true);
        $mail->Subject = 'Welcome to Ayush Lpo - Login Details';
        $mail->Body = "
            <h3>Dear $uname,</h3>
            <p>Here are your login details:</p>
            <ul>
                <li><strong>User Id:</strong> $ucontact</li>
                <li><strong>Email Id:</strong> $email</li>
                <li><strong>Password:</strong> $upass</li>
            </ul>
            <p>Please keep this information secure and do not share it with anyone.</p>
            <p>You can change your password after login from your profile.</p>
            <p>Best regards,<br>Ayush LPO</p>
        ";

        $mail->send();
        echo "<script>
            alert('Login details forwarded to the registered email ID.');
            window.location.href = 'view-employee.php';
        </script>";
    } catch (Exception $e) {
        error_log("Mailer Error: " . $mail->ErrorInfo);
        echo "<script>
            alert('Employee added successfully, but email could not be sent.');
            window.location.href = 'view-employee.php';
        </script>";
    }
}

// Function to handle logo upload
function uploadLogo()
{
    if (!empty($_FILES["logo"]["name"])) {
        $target_dir = "../upload/logo/";
        $imageFileType = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));
        $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $newFileName;

        if (getimagesize($_FILES["logo"]["tmp_name"]) === false) {
            showErrorAndRedirect('File is not an image.');
        }
        if ($_FILES["logo"]["size"] > 5000000) {
            showErrorAndRedirect('File size exceeds 5MB.');
        }
        if (!in_array($imageFileType, ['jpg', 'png', 'jpeg', 'gif'])) {
            showErrorAndRedirect('Only JPG, JPEG, PNG, and GIF files are allowed.');
        }
        if (!move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
            showErrorAndRedirect('Error uploading file.');
        }

        return $target_file;
    }
    return '';
}

// Function to show error and redirect
function showErrorAndRedirect($message)
{
    echo "<script>
        alert('$message');
        window.location.href = 'view-employee.php?add_employee';
    </script>";
    exit;
}
?>

<?php
function generateReferralCode($con) {
    // Loop until a unique referral code is generated
    do {
        $letters = substr(str_shuffle('ABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, 2);
        $numbers = substr(str_shuffle('0123456789'), 0, 4);
        
        $referralCode = str_shuffle($letters . $numbers);

        // Check if the code already exists in the database
        $query = "SELECT COUNT(*) AS count FROM users WHERE referal_code = '" . mysqli_real_escape_string($con, $referralCode) . "'";
        $result = mysqli_query($con, $query);
        $row = mysqli_fetch_assoc($result);
    } while ($row['count'] > 0);

    return $referralCode;
}
?>


<?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']));
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $saddress = mysqli_real_escape_string($con, strip_tags($_POST['saddress']));
    $country = mysqli_real_escape_string($con, strip_tags($_POST['country']));
    $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']));
    $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));
    $email = mysqli_real_escape_string($con, strip_tags($_POST['email']));
    $whatsapp = mysqli_real_escape_string($con, strip_tags($_POST['whatsapp']));
    $utype = mysqli_real_escape_string($con, strip_tags($_POST['utype']));
    $about = $_POST['about'];

    // Handle file upload
    $logopath = "";
    if (!empty($_FILES["logo"]["name"])) {
        $target_dir = "../upload/logo/";
        $imageFileType = strtolower(pathinfo($_FILES["logo"]["name"], PATHINFO_EXTENSION));
        
        // Generate a unique file name
        $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
        $target_file = $target_dir . $newFileName;
        $uploadOk = 1;
    
        // Check if image file is an actual image or fake image
        $check = getimagesize($_FILES["logo"]["tmp_name"]);
        if ($check !== false) {
            $uploadOk = 1;
        } else {
            $uploadOk = 0;
        }
    
        // Check file size (5MB maximum)
        if ($_FILES["logo"]["size"] > 5000000) {
            $uploadOk = 0;
        }
    
        // Allow certain file formats
        if ($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif") {
            $uploadOk = 0;
        }
    
        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            echo "<script>alert('Sorry, your file was not uploaded.');</script>";
        } else {
            // if everything is ok, try to upload file
            if (move_uploaded_file($_FILES["logo"]["tmp_name"], $target_file)) {
                unlink("$_POST[logoOld]");
                $logopath = $target_file;
            } else {
                echo "<script>alert('Sorry, there was an error uploading your file.');</script>";
            }
        }
    }  else{
        $logopath = $_POST["logoOld"];
    }

    $up_sql = "UPDATE users SET uname = '$uname', ucontact = '$ucontact', saddress = '$saddress', state = '$state', ucountry = '$country', dist = '$dist', pin = '$pin', upass = '$upass', uphone = '$uphone', uemail = '$email', uwhatsapp = '$whatsapp', uabout = '$about', ulogo = '$logopath', utype = '$utype' WHERE uid = '$_GET[edit_id]'";

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

<?php
if ( isset($_GET["del_id"]) ) {
// $disable_sql = "UPDATE users SET udisplay='disable' WHERE uid = '$_GET[del_id]'";
$delete_sql = "DELETE FROM users WHERE uid = '$_GET[del_id]'";

    // if ( mysqli_query($con, $disable_sql) ) {
    if ( mysqli_query($con, $delete_sql) ) {
        ?>
<script>
window.location = "view-employee.php";
</script>
<?php
    } else {
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-employee.php';
}, 1200);
</script>
<?php
    }
}
?>