<?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['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 College Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-6 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']; ?>">
                                </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 City:</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">
                                    <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">
                                    <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="address">Edit Logo: <a
                                            href="../upload/logo/<?php echo $edit_row["ulogo"];?>"><img
                                                src="../upload/logo/<?php echo $edit_row["ulogo"];?>" class="img-fluid"
                                                style="height:15px;" alt="<?php echo $edit_row["uname"];?> Logo"> <i
                                                class="fa fa-eye"></i></a></label>
                                    <input type="file" class="form-control" name="logo" accept=".jpg, .jpeg, .png">
                                    <input type="hidden" name="oldlogo" value="<?php echo $edit_row["ulogo"];?>">
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="about">About College:</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"><?php echo $edit_row["uabout"];?></textarea>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="oabout">Others About College:</label>
                                    <textarea class="form-control ckeditor" name="oabout" id="content1"
                                        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="uphone">Login Id:</label>
                                    <input type="text" class="form-control" name="uphone"
                                        value="<?php echo $edit_row['uphone']?>">
                                </div>
                                <div class="col-md-6">
                                    <label for="upass">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-college.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 }
                } elseif(isset($_GET["view_id"])){
                    $view_id = $_GET["view_id"];
                    $view_run = mysqli_query($con, "SELECT * FROM users WHERE uid = '$_GET[view_id]'");
                    if($view_row = mysqli_fetch_assoc($view_run)){
                       
                        $country_sql = mysqli_query($con, "SELECT * FROM countries WHERE id = '$view_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 = '$view_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 = '$view_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">College Details</h5>
                    <div class="card-body">
                        <p class="m-0"><strong>College Name: </strong><?php echo $view_row['uname'];?></p>
                        <p class="m-0"><strong>Phone Number: </strong><?php echo $view_row['ucontact']; ?></p>
                        <p class="m-0"><strong>Whatsapp Number: </strong><?php echo $view_row['uwhatsapp']; ?></p>
                        <p class="m-0"><strong>Email Id: </strong><?php echo $view_row['uemail']; ?></p>
                        <p class="m-0"><strong>Address: </strong><?php echo $view_row['saddress']; ?></p>
                        <p class="m-0"><strong>Country: </strong><?php echo $country_name; ?></p>
                        <p class="m-0"><strong>State: </strong><?php echo $state_name; ?></p>
                        <p class="m-0"><strong>City: </strong><?php echo $dist_name; ?></p>
                        <p class="m-0"><strong>Pin Code: </strong><?php echo $view_row["pin"]; ?></p>
                        <p class="m-0"><strong>About College: </strong></p>
                        <div id="ck-img-preview">
                            <?php echo $view_row["uabout"];?>
                        </div>
                        <p class="m-0"><strong>Other About College: </strong></p>
                        <div id="ck-img-preview">
                            <?php echo $view_row["uOabout"];?>
                        </div>
                        <div>
                            <a href="view-college.php#college<?php echo $view_row["uid"];?>"
                                class="btn btn-warning btn-user my-2 text-white"> <i class="fa fa-arrow-left"></i>
                                Back </a>
                        </div>
                    </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 College Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-6 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">City:</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">Enter Pin Code</label>
                                    <input type="number" class="form-control" name="pin" placeholder="Pin*">
                                </div>
                                <div class="col-md-6">
                                    <label for="address">Enter Address</label>
                                    <input type="text" class="form-control" name="saddress"
                                        placeholder="Enter Your Street Address*">
                                </div>
                                <div class="col-md-3">
                                    <label for="address">Logo</label>
                                    <input type="file" class="form-control" name="logo" accept=".jpg, .jpeg, .png"
                                        required>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="about">About College</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"></textarea>
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="oabout">Other About College</label>
                                    <textarea class="form-control ckeditor" name="oabout" id="content1"
                                        rows="3"></textarea>
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user my-2" name="submit"><i
                                        class="fa fa-plus"></i> Add Client
                                </button>
                                <a href="view-college.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-end">
                            <div class="col-md-4">
                                <div class="row mb-2">
                                    <div class="col-md-7 col-8">
                                        <h5 class="text-gray-800 m-0">All College List</h5>
                                    </div>
                                    <div class="col-md-5 col-4 text-end">
                                        <a href="view-college.php?add_id" class="btn btn-primary btn-sm m-0"><i
                                                class="fa fa-plus"></i>&nbsp; College</a>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-8">
                                <ul class="search-details">
                                    <li>
                                        <input type="hidden" name="country" id="country-id" value="">
                                        <input type="text" list="country-list" class="form-control form-control-sm"
                                            id="country-input" placeholder="Select Country 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>
                                    </li>
                                    <li>
                                        <input type="hidden" name="state" id="state-id" value="">
                                        <input type="text" list="state-list" class="form-control form-control-sm"
                                            id="state-input" placeholder="Select State from the list">
                                        <datalist id="state-list"></datalist>
                                    </li>
                                    <li>
                                        <input type="hidden" name="dist" id="district-id" value="">
                                        <input type="text" list="district-list" class="form-control form-control-sm"
                                            id="district-input" placeholder="Select City from the list">
                                        <datalist id="district-list"></datalist>
                                    </li>
                                    <li>
                                        <select name="dept" class="form-control form-control-sm" id="dept">
                                            <option value="">Select Department From List</option>
                                            <?php 
                                            $dept_sql = mysqli_query($con, "SELECT * FROM clg_course_cat WHERE recycle = '1' ORDER BY sl_no DESC");
                                            
                                            while ($dept_row = mysqli_fetch_assoc($dept_sql)) {
                                            ?>
                                            <option value="<?php echo $dept_row["sl_no"]; ?>"
                                                data-cat-id="<?php echo $dept_row["cat_id"]; ?>">
                                                <?php echo $dept_row["cat_name"]; ?>
                                            </option>
                                            <?php } ?>
                                        </select>
                                    </li>
                                    <li>
                                        <select name="course" class="form-control form-control-sm" id="course">
                                            <option value="">Select Course From List</option>
                                        </select>
                                    </li>
                                    <li>
                                        <input type="text" list="First" class="form-control form-control-sm"
                                            id="FirstFilterValue" placeholder="Search By College Name">
                                        <datalist id="First">
                                            <?php 
                                                $sql = "SELECT DISTINCT uname FROM users WHERE utype = 'College' AND udisplay != 'disable' ORDER BY uname ASC";
                                                $res = mysqli_query($con,$sql);
                                                while ($row = mysqli_fetch_assoc($res)) {
                                            ?>
                                            <option value="<?php echo $row['uname']; ?>">
                                                <?php echo $row['uname']; ?></option>
                                            <?php } ?>
                                        </datalist>
                                    </li>
                                    <li>
                                        <input type="text" list="FirstNo" class="form-control form-control-sm"
                                            id="noValue" placeholder="College Number">
                                        <datalist id="FirstNo">
                                            <?php 
                                                $sql = "SELECT DISTINCT ucontact FROM users WHERE utype = 'College' AND udisplay != 'disable' ORDER BY uid ASC";
                                                $res = mysqli_query($con,$sql);
                                                while ($row = mysqli_fetch_assoc($res)) {
                                            ?>
                                            <option value="<?php echo $row['ucontact']; ?>">
                                                <?php echo $row['ucontact']; ?></option>
                                            <?php } ?>
                                        </datalist>
                                    </li>
                                    <li>
                                        <div class="d-flex">
                                            <input type="text" list="FirstEmail" class="form-control form-control-sm"
                                                id="emailValue" placeholder="College Email">
                                            <datalist id="FirstEmail">
                                                <?php 
                                                    $sql = "SELECT DISTINCT uemail FROM users WHERE utype = 'College' AND udisplay != 'disable' ORDER BY uid ASC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['uemail']; ?>">
                                                    <?php echo $row['uemail']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                            <button type="button" id="filter" class="btn btn-primary btn-sm"><i
                                                    class="fa fa-search"></i>
                                            </button>
                                        </div>
                                    </li>
                                </ul>
                            </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 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"; ?>

    <script>
    CKEDITOR.replace('content', {
        height: 300,
        filebrowserUploadUrl: "upload.php"
    });
    CKEDITOR.replace('content1', {
        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() {
        // 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 City. 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('');
            }
        });

        $("#dept").change(function() {
            var sl_no = $(this).val();
            var cat_id = $("#dept option:selected").data("cat-id");

            if (sl_no !== "") {
                $.ajax({
                    url: "get_courses.php",
                    type: "POST",
                    data: {
                        sl_no: sl_no,
                        cat_id: cat_id
                    },
                    success: function(response) {
                        $("#course").html(response);
                    }
                });
            } else {
                $("#course").html('<option value="">Select From List</option>');
            }
        });
    });
    </script>

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

        // Filter values
        let FirstFilterValue = '';
        let noValue = '';
        let emailValue = '';
        let countryId = '';
        let stateId = '';
        let districtId = '';
        let dept = '';
        let course = '';

        // Load initial unfiltered data
        loadMore(load_flag);

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

        // Filter button click
        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            noValue = $('#noValue').val();
            emailValue = $('#emailValue').val();
            countryId = $('#country-id').val();
            stateId = $('#state-id').val();
            districtId = $('#district-id').val();
            dept = $('#dept').val();
            course = $('#course').val();

            load_filter_flag = 0;
            load_flag = 0;

            if (countryId || stateId || districtId || FirstFilterValue || dept || course || noValue ||
                emailValue) {
                $.ajax({
                    url: 'view-college-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue,
                        noValue,
                        emailValue,
                        countryId,
                        stateId,
                        districtId,
                        dept,
                        course,
                        start: load_filter_flag
                    },
                    beforeSend: function() {
                        $("#loader").show();
                        $("#loadMoreBtn").hide();
                    },
                    success: function(result) {
                        $('#full-table').hide();
                        $('#filter-table').show();
                        $('#filter-table-data').html(result);
                        initializeStatusSwitches();

                        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 unfiltered data
        function loadMore(start) {
            $.ajax({
                url: 'view-college-Ajax.php',
                type: 'POST',
                data: {
                    start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    initializeStatusSwitches();

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

        // Load filtered data
        function loadMoreFilter(start) {
            $.ajax({
                url: 'view-college-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue,
                    noValue,
                    emailValue,
                    countryId,
                    stateId,
                    districtId,
                    dept,
                    course,
                    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();
                }
            });
        }
    });
    </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_code'];
    $about = $_POST['about'];
    $oabout = $_POST['oabout'];
    $uphone = mysqli_real_escape_string($con, strip_tags($_POST['ucontact']));
    $upass = "1111";

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

    if (isset($_FILES['logo']) && $_FILES['logo']['error'] == 0) {
        $file_name = time() . "_" . basename($_FILES['logo']['name']);
        $target_path = "../upload/logo/" . $file_name;
        move_uploaded_file($_FILES['logo']['tmp_name'], $target_path);
    } else {
        $file_name = ''; // Default if no file uploaded
    }    

    if (!preg_match('/^[0-9]{10}$/', $ucontact) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo '<script>alert("Invalid contact number or email.");';
        echo 'window.location.href = "view-college.php";</script>';
        exit();
    } else {
        // Check if contact or email exists
        $uni_sql = mysqli_query($con, "SELECT * FROM users WHERE utype != 'College' AND ucontact = '$ucontact' OR uemail = '$email'");
        if (mysqli_num_rows($uni_sql) > 0) {
            $row = mysqli_fetch_assoc($uni_sql);
            if ($row['ucontact'] === $ucontact && $row['uemail'] === $email) {
                echo '<script>alert("Contact number and email already exist.");';
                echo 'window.location.href = "view-college.php";</script>';
            } elseif ($row['ucontact'] === $ucontact) {
                echo '<script>alert("Contact number already exists.");';
                echo 'window.location.href = "view-college.php";</script>';
            } elseif ($row['uemail'] === $email) {
                echo '<script>alert("Email already exists.");';
                echo 'window.location.href = "view-college.php";</script>';
            }
        } else {
            $sql = "INSERT INTO users (uname, uref_code, ucontact, saddress, state, dist, pin, upass, uref, utype, admin_ref, ucreated, uStatus, uabout, referal_code, uemail, uwhatsapp, ulogo, ucountry, uOabout, uphone) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $con->prepare($sql);

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

            if ($stmt->execute()) {
                // Initialize PHPMailer
                $mail = new PHPMailer(true);

                try {
                    // SMTP Configuration
                    $mail->isSMTP();
                    $mail->SMTPDebug = 2; // Set 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; // Common SMTP port for STARTTLS

                    // 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 = "
                        <div style='font-family: Arial, sans-serif; color: #333;'>
                            <h2 style='color: #4CAF50;'>Welcome to Ayush LPO</h2>
                            <p>Dear <strong>$uname</strong>,</p>
                            <p>We are thrilled to have you on board. Below are your login credentials:</p>
                            <table style='border-collapse: collapse; width: 100%;'>
                                <tr style='background-color: #f2f2f2;'>
                                    <th style='text-align: left; padding: 8px;'>Detail</th>
                                    <th style='text-align: left; padding: 8px;'>Value</th>
                                </tr>
                                <tr>
                                    <td style='padding: 8px;'>Register Number</td>
                                    <td style='padding: 8px;'>$ucontact</td>
                                </tr>
                                <tr>
                                    <td style='padding: 8px;'>Register Email</td>
                                    <td style='padding: 8px;'>$email</td>
                                </tr>
                                <tr>
                                    <td style='padding: 8px;'>Password</td>
                                    <td style='padding: 8px;'>$upass</td>
                                </tr>
                            </table>
                            <p>Please keep this information secure. You can change your password after logging in.</p>
                            <p>Best regards,<br><strong>Ayush LPO Team</strong></p>
                        </div>
                    ";

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

                    // Redirect with success message
                    echo "<script>
                        alert('Login details forwarded to registered email ID.');
                    </script>";
                    echo "<script>window.location = 'view-college.php';</script>";
                } catch (Exception $e) {
                    error_log("Mailer Error: " . $mail->ErrorInfo);
                    echo "<script>
                        alert('Employee added successfully. Email could not be sent. Mailer Error: " . addslashes($mail->ErrorInfo) . "');
                        window.location = 'view-college.php?add_employee';
                    </script>";
                }
            } else {
                echo '<script>alert("Error during registration. Please try again later.");</script>';
            }
        }
    }
}
?>


<?php
// Function to generate unique code
function generateUniqueIdClient($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'];
    $oabout = $_POST['oabout'];
    $uphone = mysqli_real_escape_string($con, $_POST['uphone']);
    
    $old_logo = $_POST['oldlogo'];
    $new_logo = $_FILES['logo']['name'];
    
    if(!empty($new_logo)){
        $logo_ext = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $logo_name = time() . '.' . $logo_ext;
        $upload_path = "../upload/logo/" . $logo_name;

        // Move the uploaded file
        if (move_uploaded_file($_FILES['logo']['tmp_name'], $upload_path)) {
            // Check if old logo exists before deleting
            if (!empty($old_logo) && file_exists($old_logo)) {
                unlink($old_logo);
            }
        } else {
            // If upload fails, retain the old logo
            $logo_name = $old_logo;
        }
    } else {
        $logo_name = $old_logo;
    }

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

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


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