<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['Employee']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['uref_code']) && !isset($_SESSION['uname']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }
    // echo $_SESSION["otp"];
    // echo $_SESSION["uref_code"];
?>

<!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 Associate Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-9 mb-2">
                                    <label for="studentName">Edit 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-3 mb-2">
                                    <label for="phoneNo">Edit Mobile No</label>
                                    <input type="number" class="form-control" name="ucontact"
                                        placeholder="Enter Mobile Number*" value="<?php echo $edit_row['ucontact']; ?>"
                                        minlength="10" maxlength="10" oninput="this.value=this.value.slice(0,10)">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="phoneNo">Edit Whatsapp No</label>
                                    <input type="number" class="form-control" name="uwhatsapp"
                                        placeholder="Enter Whatsapp Number*"
                                        value="<?php echo $edit_row['uwhatsapp']; ?>" minlength="10" maxlength="10"
                                        oninput="this.value=this.value.slice(0,10)">
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="email">Edit Email Id</label>
                                    <input type="email" class="form-control" name="email"
                                        value="<?php echo $edit_row["uemail"];?>" required>
                                </div>
                                <div class="col-md-3 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-3 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-3 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-3 mb-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-6 mb-2">
                                    <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-12 mb-2">
                                    <label for="about">Edit About Associate</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">Edit Password</label>
                                    <input type="text" class="form-control" name="upass" placeholder="Enter Password"
                                        value="<?php echo $edit_row['upass']?>">
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user my-2" name="edit_users"><i
                                        class="fa fa-edit"></i> UPDATE DETAILS
                                </button>
                                <a href="view-franchiee.php#franchisee<?php echo $edit_row["uid"]?>"
                                    class="btn btn-warning btn-user m-2 text-white"> <i class="fa fa-arrow-left"></i>
                                    Back </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php }
                } elseif(isset($_GET["add_id"])){?>
                <div class="card mt-3">
                    <h5 class="card-header text-dark  text-center font-weight-bold">Add Associate Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-9 mb-2">
                                    <label for="studentName">Name</label>
                                    <input type="text" class="form-control" name="uname" placeholder="Enter Name"
                                        pattern="^[A-Za-z]+(?:\s[A-Za-z]+)*$"
                                        title="Only alphabets and space between two word are allowed, and extra space not allowed."
                                        required>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="phoneNo">Mobile Number</label>
                                    <input type="number" class="form-control" name="ucontact" id="ucontact"
                                        placeholder="Enter Your Mobile 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-3 mb-2">
                                    <label for="uwhatsapp">Whatsapp Number</label>
                                    <input type="number" class="form-control" name="uwhatsapp"
                                        placeholder="Enter Whatsapp Number*" required minlength="10" maxlength="10"
                                        oninput="this.value=this.value.slice(0,10)">
                                </div>
                                <div class="col-md-3 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-3 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-3 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-3 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-3">
                                    <label for="pinCode">Pin Code</label>
                                    <input type="number" class="form-control" name="pin" placeholder="Pin*">
                                </div>
                                <div class="col-md-6">
                                    <label for="address">Address</label>
                                    <input type="text" class="form-control" name="saddress"
                                        placeholder="Enter Your Street Address*">
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="about">About Associate</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"></textarea>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 mb-2">
                                    <h6 class="badge-dark mb-2">Login Details</h6>
                                    <input type="text" class="form-control" name="upass" placeholder="Enter Password"
                                        required>
                                </div>
                                <div class="col-md-8 mb-2">
                                    <div class="row">
                                        <div class="col-md-12 mb-2">
                                            <h6 class="badge-dark m-0">KYC Details</h6>
                                        </div>
                                        <div class="col-md-6 mb-2">
                                            <select name="docType" class="form-control" id="">
                                                <option value="">Select Document</option>
                                                <option value="Pan Card">Pan Card</option>
                                                <option value="Votar Card">Votar Card</option>
                                                <option value="Aadhar Card">Aadhar Card</option>
                                            </select>
                                        </div>
                                        <div class="col-md-6 mb-2">
                                            <input type="file" class="form-control" name="docFile"
                                                accept=".jpg,.jpeg,.png,.gif,.bmp,.tiff,.webp,.pdf" capture required>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user my-2" name="submit"><i
                                        class="fa fa-plus"></i> Add Associate
                                </button>
                                <a href="view-franchiee.php" class="btn btn-warning btn-user m-2 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 col-12">
                                <div class="d-flex justify-content-between align-items-center">
                                    <h4 class="text-gray-800 m-0">All Associate List</h4>
                                    <a href="view-franchiee.php?add_id" class="btn btn-primary btn-sm m-0"><i
                                            class="fa fa-plus"></i>&nbsp; Associate</a>
                                </div>
                            </div>
                            <div class="col-md-6 col-12 mt-2 mt-lg-0 d-flex justify-content-center">
                                <div class="form-group w-100">
                                    <input type="hidden" name="state" id="state-id2" value="">
                                    <input type="text" list="state2" class="form-control form-control-sm"
                                        id="state-input2" placeholder="Select State From The List">
                                    <datalist id="state2">
                                        <?php 
                                            $sql = "SELECT id, name FROM state WHERE country_id = '101' 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="form-group w-100">
                                    <input type="hidden" name="dist" id="district-id2" value="">
                                    <input type="text" list="district-list2" class="form-control form-control-sm"
                                        id="district-input2" placeholder="Select State First" required>
                                    <datalist id="district-list2"></datalist>
                                </div>
                                <div class="form-group w-100">
                                    <input type="text" list="First" class="form-control form-control-sm"
                                        id="FirstFilterValue" placeholder="Search By Associate Name">
                                    <datalist id="First">
                                        <?php 
                                            $sql = "SELECT DISTINCT uname FROM users  WHERE utype = 'Associate'  AND udisplay !='disable' AND admin_ref = '$_SESSION[uref]' 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>
                                <div class="form-group w-100">
                                    <input type="text" list="Second" class="form-control form-control-sm"
                                        id="SecondFilterValue" placeholder="Search By Unique Code">
                                    <datalist id="Second">
                                        <?php 
                                            $sql = "SELECT DISTINCT referal_code FROM users WHERE utype = 'Associate' AND admin_ref = '$_SESSION[uref]' AND udisplay !='disable' ORDER BY uname ASC";
                                            $res = mysqli_query($con,$sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                        ?>
                                        <option value="<?php echo $row['referal_code']; ?>">
                                            <?php echo $row['referal_code']; ?></option>
                                        <?php } ?>
                                    </datalist>
                                </div>
                                <div class="">
                                    <button type="button" id="filter" class="btn btn-primary btn-sm"><i
                                            class="fa fa-search"></i></button>
                                </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-left: 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-left: 0;">
                                    </>
                                </ul>
                            </div>

                            <div class="text-center my-3">
                                <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;">
                                    <i class="fa fa-check-circle"></i> No more data to load.
                                </div>
                                <div id="loader" style="display:none;">
                                    <i class="fa fa-spinner fa-spin"></i> Loading...
                                </div>
                            </div>

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

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

    <!-- JavaScript Libraries -->

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

    <script>
    CKEDITOR.replace('content', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });
    </script>

    <!-- Modal Structure -->
    <div class="modal fade" id="studentDetailsModal" 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">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>
    $(document).ready(function() {
        // Handle state selection
        $('#state-input2').on('change', function() {
            const stateName = $(this).val();
            const stateOption = $('#state2 option').filter(function() {
                return this.value === stateName;
            });

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

                // Fetch districts using AJAX
                $.ajax({
                    url: 'fetch-district.php',
                    type: 'POST',
                    data: {
                        state_id: stateId
                    },
                    success: function(data) {
                        $('#district-list2').html(data);
                        $('#district-id2').val('');
                        $('#district-input2').val('');
                    },
                    error: function() {
                        alert('Error loading districts. Please try again.');
                    }
                });
            } else {
                $('#state-id2').val('');
                $('#district-list2').html('');
            }
        });

        // Handle district selection
        $('#district-input2').on('change', function() {
            const districtName = $(this).val();
            const districtOption = $('#district-list2 option').filter(function() {
                return this.value === districtName;
            });

            if (districtOption.length > 0) {
                $('#district-id2').val(districtOption.data('id'));
            } else {
                $('#district-id2').val('');
            }
        });
    });
    </script>


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

        var FirstFilterValue = '';
        var SecondFilterValue = '';
        var ThirdFilterValue = '';
        var StateValue = '';
        var DistValue = '';

        // Load initial unfiltered data
        loadMore(load_flag);

        // Filter button click
        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            ThirdFilterValue = $('#ThirdFilterValue').val();
            StateValue = $('#state-id2').val();
            DistValue = $('#district-id2').val();

            load_filter_flag = 0;
            load_flag = 0;

            if (FirstFilterValue || SecondFilterValue || ThirdFilterValue || StateValue || DistValue) {
                $.ajax({
                    url: 'view-franchiee-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue,
                        SecondFilterValue,
                        ThirdFilterValue,
                        StateValue,
                        DistValue,
                        start: load_filter_flag
                    },
                    beforeSend: function() {
                        $("#loader").show();
                    },
                    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 filtered data
        function loadMoreFilter(start) {
            $.ajax({
                url: 'view-franchiee-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue,
                    SecondFilterValue,
                    ThirdFilterValue,
                    StateValue,
                    DistValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                },
                success: function(result) {
                    const newItems = $('<div>').html(result).find('li');
                    $('#filter-table-data').append(newItems);
                    load_filter_flag += newItems.length;

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

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

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

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

if (isset($_POST['submit'])) {
    $uname = mysqli_real_escape_string($con, strip_tags($_POST['uname']));
    $ucontact = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $uwhatsapp = mysqli_real_escape_string($con, strip_tags($_POST['uwhatsapp']));
    $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']));
    $email = mysqli_real_escape_string($con, strip_tags($_POST['email']));
    $admin_ref = $_SESSION['uref'];
    $about = $_POST['about'];
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $upass = mysqli_real_escape_string($con, strip_tags($_POST['upass']));

    $type = "Associate";
    $ref_code = rand() . strtoupper(substr(uniqid(), 0, 4)) . time();
    $uref_code = rand() . strtoupper(substr(uniqid(), 0, 4)) . time();
    $uref = rand() . '_' . time();
    $uState = 1;

    // Unique ID for RA
    $reff_code = generateUniqueIdRA($state, $dist, $con);

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

    // Check if ucontact or email already exists
    $check_query = "SELECT * FROM users WHERE ucontact = '$ucontact' OR uemail = '$email'";
    $check_result = mysqli_query($con, $check_query);

    if (mysqli_num_rows($check_result) > 0) {
        $existing_data = mysqli_fetch_assoc($check_result);
        if ($existing_data['ucontact'] == $ucontact) {
            echo '<script>alert("The contact number is already registered. Please use a different number.");';
        } elseif ($existing_data['uemail'] == $email) {
            echo '<script>alert("The email address is already registered. Please use a different email.");';
        }
        echo 'window.location.href = "view-franchiee.php";</script>';
        exit;
    }

    // Insert new record
    $sql = "INSERT INTO users (uname, uphone, ucountry, uref_code, ucontact, saddress, state, dist, pin, upass, uref, utype, admin_ref, ucreated, uStatus, uabout, referal_code, uemail, uwhatsapp, uadmin) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    $stmt = $con->prepare($sql);

    $stmt->bind_param('ssssssssssssssssssss', $uname, $uphone, $country, $uref_code, $ucontact, $saddress, $state, $dist, $pin, $upass, $uref, $type, $admin_ref, $currentTime, $uState, $about, $reff_code, $email, $uwhatsapp, 'fssdf4543frts');


    if ($stmt->execute()) {
        $uid = $con->insert_id;
        $title = mysqli_real_escape_string($con, strip_tags($_POST['docType']));
        $prefix = "uplodDocuments"; // Your prefix
        $random_number = str_pad(rand(0, 99999), 5, '0', STR_PAD_LEFT);
        $timestamp = date("YmdHis");
        $ref_id = $prefix . $random_number . $timestamp;

        $up_by = $_SESSION['uid'];
        $catagory = 'Documents';
        $logopath = '';
        $ustate = 1;
        $kyc = 'KYC';

        if (!empty($_FILES["docFile"]["name"])) {
            $target_dir = "../upload/uplodDocuments/";
            $imageFileType = strtolower(pathinfo($_FILES["docFile"]["name"], PATHINFO_EXTENSION));
            $newFileName = uniqid() . '_' . time() . '.' . $imageFileType;
            $target_file = $target_dir . $newFileName;

            // Get file MIME type
            $fileType = mime_content_type($_FILES["docFile"]["tmp_name"]);
            $allowedTypes = [
                'image/jpeg', 
                'image/png', 
                'image/gif', 
                'application/pdf', 
                'application/msword', 
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
            ];

            if (in_array($fileType, $allowedTypes)) {
                // Move uploaded file
                if (move_uploaded_file($_FILES["docFile"]["tmp_name"], $target_file)) {
                    if (in_array($fileType, ['image/jpeg', 'image/png'])) {
                        // Compress image
                        compressImage($target_file, $target_file, 75);
                    }
                    $logopath = $target_file;
                } else {
                    echo "<script>alert('Error uploading your file.');</script>";
                }
            } else {
                echo "<script>alert('Invalid file type. Allowed: JPEG, PNG, GIF, PDF, DOC/DOCX.');</script>";
            }
        }

        // Prepare the SQL query using prepared statements
        $stmt = $con->prepare("INSERT INTO data (data_ref_id, data_catagory, data_title, data_img, data_up_by, data_up_date, data_recycle, data_up_for, data_subCategory) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("ssssissis", $ref_id, $catagory, $title, $logopath, $up_by, $currentTime, $ustate, $uid, $kyc);

        if ($stmt->execute()) { 

            // Send SMS OTP
            $api_key = '45899D6EF8D236';
            $entity = '1501681760000015777';
            $template_id = '1407173554566676394';
            $contacts = $ucontact;
            $message = "Your account is created successfully. Once verified we will notify you.";
            $from = 'DXTECH';
            $sms_text = urlencode(''.$uname.' Password to Recover your Account is '.$message.' Do not share with anyone. DIGI X');

            //Submit to server
            $ch = curl_init();
            curl_setopt($ch,CURLOPT_URL, "http://manage.sambsms.com/app/smsapi/index.php");
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, "key=".$api_key."&entity=".$entity."&tempid=".$template_id."&campaign=0&routeid=7&type=text&contacts=".$contacts."&senderid=".$from."&msg=".$sms_text);

            $smsResponse = curl_exec($ch);
            curl_close($ch);

            // Initialize PHPMailer
            $mail = new PHPMailer(true);

            try {
                // SMTP Configuration
                $mail->isSMTP();
                $mail->SMTPDebug = 2; // Set to 2 for debugging
                $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 Franchisee $uname,</h3>
                    <p>Here is 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>
                ";

                // Send Email
                $mail->send();

                echo "<script>alert('Login details have been forwarded to the registered email ID.');";
                echo "window.location = 'view-franchiee.php';</script>";
            } catch (Exception $e) {
                error_log("Mailer Error: " . $mail->ErrorInfo);
                echo "<script>alert('Employee added successfully. Email could not be sent. Error: " . addslashes($mail->ErrorInfo) . "');";
                echo "window.location = 'view-franchiee.php';</script>";
            }
        } else {
            $stmt = $con->prepare("UPDATE users SET uStatus = ? WHERE uid = ?");

            // Bind the parameters
            $uStatus = 0; // Set uStatus to '0'
            $stmt->bind_param("ii", $uStatus, $uid); // 'ii' indicates two integers
            if ($stmt->execute()) {
            echo '<script>alert("Error during KYC submit. Please try again later.");</script>';
            }
        } 
    } else {
        echo '<script>alert("Error during registration. Please try again later.");</script>';
    } 
}
?>

<?php
// Function to generate unique code
function generateUniqueIdRA($state, $dist, $con) {
    // Pad the state and district values
    $state1 = str_pad($state, 2, '0', STR_PAD_LEFT);
    $dist1 = str_pad($dist, 3, '0', STR_PAD_LEFT);

    // Generate random alphabets and numbers
    $random_alphabets = chr(rand(65, 90)) . chr(rand(65, 90));
    $random_number = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);

    // Concatenate components to form the referral code
    $reff_code = $state1 . $dist1 . $random_alphabets . $random_number;

    // Check if the generated referral code already exists in the database
    $query = "SELECT COUNT(*) AS count FROM users WHERE referal_code = ?";
    $stmt = mysqli_prepare($con, $query);
    mysqli_stmt_bind_param($stmt, 's', $reff_code);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $row = mysqli_fetch_assoc($result);

    // If the referral code exists, regenerate it until it is unique
    while ($row['count'] > 0) {
        $random_alphabets = chr(rand(65, 90)) . chr(rand(65, 90));
        $random_number = str_pad(rand(0, 9999), 4, '0', STR_PAD_LEFT);
        $reff_code = $state1 . $dist1 . $random_alphabets . $random_number;

        // Check again if the new code exists
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $row = mysqli_fetch_assoc($result);
    }

    // Return the unique referral code
    return $reff_code;
}
// Function to compress images
function compressImage($source, $destination, $quality) {
    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') {
        $image = imagecreatefromjpeg($source);
        imagejpeg($image, $destination, $quality);
    } elseif ($info['mime'] == 'image/png') {
        $image = imagecreatefrompng($source);
        imagepng($image, $destination, floor($quality / 10));
    }
}
?>

<?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']));
        $uwhatsapp = mysqli_real_escape_string($con, strip_tags($_POST['uwhatsapp']));
        $email = mysqli_real_escape_string($con, strip_tags($_POST['email']));
        $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'])); 
        $about = $_POST['about'];

        $up_sql = "UPDATE users SET uname = '$uname', ucontact = '$ucontact', saddress = '$saddress', uwhatsapp = '$uwhatsapp', uemail = '$email', state = '$state', dist = '$dist', pin = '$pin', uabout = '$about', upass = '$upass', ucountry = '$country', uphone = '$ucontact' ";

        $up_sql .= " WHERE uid = '$_GET[edit_id]' ";

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

<script>
window.location = 'view-franchiee.php';
</script>
<?php
        }
        else{
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-franchiee.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-franchiee.php";
</script>
<?php
    } else {
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-franchiee.php';
}, 1200);
</script>
<?php
    }
}
?>