<?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 Student Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-12 mb-2">
                                    <h6 class="m-0">Student Details:</h6>
                                </div>
                                <div class="col-md-12 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-4 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-4 mb-2">
                                    <label for="phoneNo">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-4 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-12 mb-2">
                                    <h6 class="m-0">Address Details:</h6>
                                </div>

                                <div class="col-md-3 mb-2">
                                    <label for="state">State</label>
                                    <input type="hidden" name="state" id="state-id"
                                        value="<?php echo $edit_row["state"];?>">
                                    <input type="text" list="state-list" class="form-control" id="state-input"
                                        value="<?php echo $state_name;?>">
                                    <datalist id="state-list">
                                        <?php
                                        $sql = "SELECT id, name FROM state ORDER BY name ASC";
                                        $res = mysqli_query($con, $sql);
                                        while ($row = mysqli_fetch_assoc($res)) {
                                            echo "<option value='{$row['name']}' data-id='{$row['id']}'></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-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-12 mb-2">
                                    <h6 class="m-0">Academic Details:</h6>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="lastQualification">Last Qualification:</label>
                                    <input type="text" class="form-control" name="lastQualification"
                                        value="<?php echo $edit_row["uqualification"];?>"
                                        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-4 mb-2">
                                    <label for="anyEntrance">Any Entrance:</label>
                                    <input type="text" class="form-control" name="anyEntrance"
                                        value="<?php echo $edit_row["uEntrance"];?>"
                                        pattern="^[A-Za-z]+(?:\s[A-Za-z]+)*$"
                                        title="Only alphabets and space between two word are allowed, and extra space not allowed.">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="entranceRank">Entrance Rank:</label>
                                    <input type="text" class="form-control" name="entranceRank"
                                        value="<?php echo $edit_row["uEntranceRank"];?>">
                                </div>
                                <div class="col-md-12 mb-2">
                                    <h6 class="m-0">Guardian Details:</h6>
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="studentName">Edit Guardian Name</label>
                                    <input type="text" class="form-control" name="uso"
                                        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['uso']; ?>">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="gContact">Guardian Number:</label>
                                    <input type="number" class="form-control" name="gContact"
                                        value="<?php echo $edit_row["usoContact"];?>" required minlength="10"
                                        maxlength="10" oninput="this.value=this.value.slice(0,10)">
                                </div>
                                <div class="col-md-4 mb-2">
                                    <label for="gOccupation">Guardian Occupation:</label>
                                    <input type="text" class="form-control" name="gOccupation"
                                        value="<?php echo $edit_row["usoOccupation"];?>">
                                </div>

                                <div class="col-md-12 mb-2">
                                    <label for="about" class="h6 m-0">About Student</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"><?php echo $edit_row["uabout"];?></textarea>
                                </div>
                            </div>
                            <h6 class="badge-dark">Login Details</h6>
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="passWOrd">Password</label>
                                    <input type="text" class="form-control" name="upass" placeholder="Enter Password"
                                        value="<?php echo $edit_row['upass']?>">
                                </div>
                            </div>
                            <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-client.php#client<?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["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">Student Details</h5>
                    <div class="card-body">
                        <h6 class="m-0 underline">Personal Details:-</h6>
                        <p class="m-0"><strong>Student Name :
                            </strong><?php echo $view_row['uname'] . ' [' . $view_row['referal_code'] . ']'; ?>
                        </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="mb-2"><strong>Email Id : </strong><?php echo $view_row['uemail']; ?></p>
                        <h6 class="m-0 underline">Academic Details:-</h6>
                        <p class="m-0"><strong>Last Qualification : </strong><?php echo $view_row['uqualification']; ?>
                        </p>
                        <p class="m-0"><strong>Entrance Exam: </strong><?php echo $view_row['uEntrance']; ?>
                        </p>
                        <p class="mb-2"><strong>Entrance Rank: </strong><?php echo $view_row['uEntranceRank']; ?>
                        </p>
                        <h6 class="m-0 underline">Guardian Details:-</h6>
                        <p class="m-0"><strong>Guardian Name : </strong><?php echo $view_row['uso']; ?></p>
                        <p class="m-0"><strong>Guardian Number : </strong><?php echo $view_row['usoContact']; ?></p>
                        <p class="mb-2"><strong>Guardian Occupation : </strong><?php echo $view_row['usoOccupation']; ?>
                        </p>
                        <h6 class="m-0 underline">Address Details:-</h6>
                        <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>District : </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 Client : </strong></p>
                        <div id="ck-img-preview">
                            <?php echo $view_row["uabout"];?>
                        </div>
                        <div>
                            <a href="view-client.php#client<?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 Client Details</h5>
                    <div class="card-body">
                        <form class="user" method="post" enctype="multipart/form-data">
                            <div class="row">
                                <div class="col-md-2 mb-2">
                                    <label for="forPrefix">Select Prefix</label>
                                    <select name="prefix" class="form-control" id="prefix">
                                        <option value=""></option>
                                        <option value="Mr">Mr</option>
                                        <option value="Mrs">Mrs</option>
                                        <option value="MS">MS</option>
                                        <option value="M/S">M/S</option>
                                    </select>
                                </div>
                                <div class="col-md-5 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-2 mb-2">
                                    <label for="forMS">Select M/S Type</label>
                                    <select name="MStype" class="form-control" id="MStype" disabled>
                                        <option value=""></option>
                                        <option value="Company">Company</option>
                                        <option value="Firm">Firm</option>
                                        <option value="LLP">LLP</option>
                                        <option value="Trust">Trust</option>
                                        <option value="Others">Others</option>
                                    </select>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="studentName">S/O</label>
                                    <input type="text" class="form-control" name="uso" placeholder="Enter C/O"
                                        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="state">State</label>
                                    <input type="hidden" name="state" id="state-id" value="">
                                    <input type="text" list="state" class="form-control" id="state-input"
                                        placeholder="Select from the list">
                                    <datalist id="state">
                                        <?php 
                                            $sql = "SELECT id, name FROM state ORDER BY id ASC";
                                            $res = mysqli_query($con, $sql);
                                            while ($row = mysqli_fetch_assoc($res)) {
                                        ?>
                                        <option data-id="<?php echo $row['id']; ?>" value="<?php echo $row['name']; ?>">
                                            <?php echo $row['name']; ?></option>
                                        <?php } ?>
                                    </datalist>
                                </div>
                                <div class="col-md-3 mb-2">
                                    <label for="dist">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" required>
                                    <datalist id="district-list"></datalist>
                                </div>
                                <div class="col-md-3">
                                    <label for="pinCode">Edit Pin Code</label>
                                    <input type="number" class="form-control" name="pin" placeholder="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*">
                                </div>
                                <div class="col-md-12 mb-2">
                                    <label for="about">About Client</label>
                                    <textarea class="form-control ckeditor" name="about" id="content"
                                        rows="3"></textarea>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 mb-2">
                                    <h6 class="badge-dark m-0">Login Details</h6>
                                </div>
                                <!--<div class="col-md-6 mb-2">
                                    <input type="text" class="form-control" name="uphone" placeholder="Enter User Name"
                                        required>
                                </div>-->
                                <div class="col-md-6 mb-2">
                                    <input type="password" class="form-control" name="upass"
                                        placeholder="Enter Password" required>
                                </div>
                            </div>
                            <div>
                                <button type="submit" class="btn btn-success btn-user m-2" name="submit"><i
                                        class="fa fa-plus"></i> Add Client
                                </button>
                                <a href="view-client.php" class="btn btn-warning btn-user m-2"> <i
                                        class="fa fa-ban"></i> Cancel </a>
                            </div>
                        </form>
                    </div>
                </div>
                <?php
                } else{?>
                <div class="card mt-3 mb-3">
                    <div class="card-header">
                        <div class="row">
                            <div class="col-md-3">
                                <div class="row mb-2">
                                    <div class="col-md-8 col-8">
                                        <h5 class="text-gray-800 m-0">All Student List</h5>
                                    </div>
                                    <!--<div class="col-md-4 col-4 text-end">
                                        <a href="view-client.php?add_id" class="btn btn-primary btn-sm m-0"><i
                                                class="fa fa-plus"></i>&nbsp; Client</a>
                                    </div>-->
                                </div>
                            </div>
                            <div class="col-md-9">
                                <ul class="search-details">
                                    <li>
                                        <input type="text" list="First" class="form-control form-control-sm"
                                            id="FirstFilterValue" placeholder="Search By Student Name">
                                        <datalist id="First">
                                            <?php 
                                                $sql = "SELECT DISTINCT uname FROM users WHERE utype = 'Student' AND udisplay != 'disable' ORDER BY uid 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="Student Number">
                                        <datalist id="FirstNo">
                                            <?php 
                                                $sql = "SELECT DISTINCT ucontact FROM users WHERE utype = 'Student' 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>
                                        <input type="text" list="FirstEmail" class="form-control form-control-sm"
                                            id="emailValue" placeholder="Student Email">
                                        <datalist id="FirstEmail">
                                            <?php 
                                                $sql = "SELECT DISTINCT uemail FROM users WHERE utype = 'Student' 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>
                                    </li>
                                    <li>
                                        <input type="text" list="second" class="form-control form-control-sm"
                                            id="SecondFilterValue" placeholder="Search By Associate Name">
                                        <datalist id="second">
                                            <?php 
                                                $sql = "SELECT DISTINCT uname FROM users WHERE utype = 'Associate' AND udisplay != 'disable' ORDER BY uid 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>
                                        <div class="form-group">
                                            <input type="text" list="ras" class="form-control form-control-sm"
                                                id="thirdValue" placeholder="Search By Sub Associate Name">
                                            <datalist id="ras">
                                                <?php 
                                                    $sql = "SELECT DISTINCT uname FROM users  WHERE utype = 'Sub Associate'  AND udisplay !='disable' ORDER BY uname ASC";
                                                    $res = mysqli_query($con,$sql);
                                                    while ($row = mysqli_fetch_assoc($res)) {
                                                ?>
                                                <option value="<?php echo $row['uname']; ?>">
                                                    <?php echo $row['uname']; ?></option>
                                                <?php } ?>
                                            </datalist>
                                        </div>
                                        <input type="hidden" class="form-control" value="" id="thirdValue">
                                    </li>
                                    <li>
                                        <input type="text" list="Third" class="form-control form-control-sm"
                                            id="ThirdFilterValue" placeholder="Search By Unique Id">
                                        <datalist id="Third">
                                            <?php 
                                                $sql = "SELECT DISTINCT referal_code FROM users WHERE utype = 'Student' 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>
                                    </li>
                                    <li>
                                        <!-- Course Name Search -->
                                        <input type="text" list="third" id="course_search" name="course_search"
                                            class="form-control form-control-sm" placeholder="Search by Course Name">

                                        <!-- Hidden field to hold selected course ID -->
                                        <input type="hidden" name="selected_courseId" id="selected_courseId">

                                        <datalist id="third">
                                            <!-- Populated dynamically from PHP -->
                                            <?php
                                            $coursePidMap = []; // renamed to courseIdMap for clarity

                                            $res = mysqli_query($con, "
                                                SELECT DISTINCT sl_no, course_name 
                                                FROM clg_course 
                                                WHERE course_name IS NOT NULL AND course_name != ''
                                                ORDER BY course_name ASC
                                            ");

                                            while ($row = mysqli_fetch_assoc($res)) {
                                                $course_name = htmlspecialchars($row['course_name']);
                                                $sl_no = htmlspecialchars($row['sl_no']);
                                                $coursePidMap[$course_name] = $sl_no; // Map course name to sl_no
                                                echo '<option value="' . $course_name . '">' . $course_name . '</option>';
                                            }
                                            ?>

                                        </datalist>
                                    </li>
                                    <li>
                                        <select name="batch" id="batch" class="form-control form-control-sm">
                                            <?php if (!empty($batch_name)) { ?>
                                            <option value="<?= $batch ?>"><?= $batch_name; ?></option>
                                            <?php } else { ?>
                                            <option value="">Select Course First</option>
                                            <?php } ?>
                                        </select>
                                    </li>
                                    <li>
                                        <button type="button" id="filter" class="btn btn-primary mb-2 btn-sm"><i
                                                class="fa fa-search"></i>
                                        </button>
                                    </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"
    });
    </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>
    const courseIdMap = <?= json_encode($coursePidMap) ?>;

    document.getElementById('course_search').addEventListener('input', function() {
        const selectedCourse = this.value;
        const courseId = courseIdMap[selectedCourse] || '';
        document.getElementById('selected_courseId').value = courseId;

        if (courseId) {
            fetchBatches(courseId);
        } else {
            document.getElementById('batch').innerHTML = '<option value="">Select Course First</option>';
        }
    });

    function fetchBatches(course_id) {
        $.ajax({
            url: 'fetch_batch.php',
            type: 'POST',
            data: {
                course_id: course_id
            },
            success: function(response) {
                document.getElementById('batch').innerHTML = response;
            },
            error: function() {
                document.getElementById('batch').innerHTML =
                    '<option value="">Failed to load batches</option>';
            }
        });
    }
    </script>

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

        let FirstFilterValue = '';
        let SecondFilterValue = '';
        let ThirdFilterValue = '';
        let thirdValue = '';
        let noValue = '';
        let emailValue = '';
        let courseValue = '';
        let batchValue = '';

        // Filter button click
        $("#filter").click(function() {
            FirstFilterValue = $('#FirstFilterValue').val();
            SecondFilterValue = $('#SecondFilterValue').val();
            ThirdFilterValue = $('#ThirdFilterValue').val();
            thirdValue = $('#thirdValue').val();
            noValue = $('#noValue').val();
            emailValue = $('#emailValue').val();
            courseValue = $('#selected_courseId').val();
            batchValue = $('#batch').val();

            load_filter_flag = 0;
            load_flag = 0;

            if (
                FirstFilterValue || SecondFilterValue || ThirdFilterValue || thirdValue ||
                noValue || emailValue || courseValue || batchValue
            ) {
                $.ajax({
                    url: 'view-client-Ajax.php',
                    type: 'POST',
                    data: {
                        FirstFilterValue,
                        SecondFilterValue,
                        ThirdFilterValue,
                        thirdValue,
                        noValue,
                        emailValue,
                        courseValue,
                        batchValue,
                        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 tempDiv = $('<div>').html(result);
                        const items = tempDiv.find('li');
                        load_filter_flag += items.length;

                        if (items.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();
                $('#loadMoreBtn').show();
                $('#endMessage').hide();
            }
        });

        // Initial load for unfiltered data
        loadMore(load_flag);

        function loadMore(start) {
            $.ajax({
                url: 'view-client-Ajax.php',
                type: 'POST',
                data: {
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#full-table-data').append(result);
                    initializeStatusSwitches();

                    const tempDiv = $('<div>').html(result);
                    const items = tempDiv.find('li');
                    load_flag += items.length;

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

        function loadMoreFilter(start) {
            $.ajax({
                url: 'view-client-Ajax.php',
                type: 'POST',
                data: {
                    FirstFilterValue,
                    SecondFilterValue,
                    ThirdFilterValue,
                    thirdValue,
                    noValue,
                    emailValue,
                    courseValue,
                    batchValue,
                    start: start
                },
                beforeSend: function() {
                    $("#loader").show();
                    $("#loadMoreBtn").hide();
                },
                success: function(result) {
                    $('#filter-table-data').append(result);
                    initializeStatusSwitches();

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

                    if (items.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
// 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']));
        $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'])); 
        $lastQualification = mysqli_real_escape_string($con, strip_tags($_POST['lastQualification']));
        $anyEntrance = mysqli_real_escape_string($con, strip_tags($_POST['anyEntrance']));
        $entranceRank = mysqli_real_escape_string($con, strip_tags($_POST['entranceRank']));
        $uso = mysqli_real_escape_string($con, strip_tags($_POST['uso']));
        $gContact = mysqli_real_escape_string($con, strip_tags($_POST['gContact']));
        $gOccupation = mysqli_real_escape_string($con, strip_tags($_POST['gOccupation']));
        $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', ucreated = '$currentTime', uso = '$uso', usoOccupation = '$gOccupation', usoContact = '$gContact', uqualification = '$lastQualification', uEntranceRank = '$entranceRank', uEntrance = '$anyEntrance' ";

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

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

<script>
window.location = 'view-client.php';
</script>
<?php
        }
        else{
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-client.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]'";
    if ( mysqli_query($con, $disable_sql) ) {
        ?>
<script>
window.location = "view-client.php";
</script>
<?php
    } else {
        ?>
<script>
alert('OOPS !!!!');
setTimeout(() => {
    window.location = 'view-client.php';
}, 1200);
</script>
<?php
    }
}
?>