<?php
session_start();
include "../db.php";

if (isset($_POST['start'])) {
    $start = mysqli_real_escape_string($con, $_POST['start']);
    $AndWhere = '';
    $AndWherec = '';

    if (!empty($_POST['FirstFilterValue'])) {
        $AndWhere .= "AND uname='" . mysqli_real_escape_string($con, $_POST['FirstFilterValue']) . "' ";
    }
    if (!empty($_POST['noValue'])) {
        $AndWhere .= "AND ucontact ='" . mysqli_real_escape_string($con, $_POST['noValue']) . "' ";
    }
    if (!empty($_POST['emailValue'])) {
        $AndWhere .= "AND uemail ='" . mysqli_real_escape_string($con, $_POST['emailValue']) . "' ";
    }
    if (!empty($_POST['countryId'])) {
        $AndWhere .= "AND ucountry ='" . mysqli_real_escape_string($con, $_POST['countryId']) . "' ";
    }
    if (!empty($_POST['stateId'])) {
        $AndWhere .= "AND state ='" . mysqli_real_escape_string($con, $_POST['stateId']) . "' ";
    }
    if (!empty($_POST['districtId'])) {
        $AndWhere .= "AND dist ='" . mysqli_real_escape_string($con, $_POST['districtId']) . "' ";
    }
    
    $valid_filter = false; // Flag to track valid conditions

    if (!empty($_POST['course'])) {
        $course_up_for = [];
        $course_sql = mysqli_query($con, "SELECT data_up_for FROM data WHERE data_catagory = 'Course' AND data_title = '".mysqli_real_escape_string($con, $_POST['course'])."'");
        
        while ($course_row = mysqli_fetch_assoc($course_sql)) {
            if (!empty($course_row['data_up_for'])) {
                $course_up_for[] = $course_row['data_up_for'];
            }
        }

        if (!empty($course_up_for)) {
            $valid_filter = true; // At least one valid course found
            $course_up_for_str = implode(',', $course_up_for);
            $AndWherec = " AND FIND_IN_SET(uid, '$course_up_for_str')";
        } else{
            $AndWherec .= " AND 1=0";
        }
    } else if (!empty($_POST['dept'])) {
        $dept_up_for = [];
        $dept_sql = mysqli_query($con, "SELECT data_up_for FROM data WHERE data_catagory = 'Department' AND data_short_des = '".mysqli_real_escape_string($con, $_POST['dept'])."'");
        
        while ($dept_row = mysqli_fetch_assoc($dept_sql)) {
            if (!empty($dept_row['data_up_for'])) {
                $dept_up_for[] = $dept_row['data_up_for'];
            }
        }

        if (!empty($dept_up_for)) {
            $valid_filter = true; // At least one valid department found
            $dept_up_for_str = implode(',', $dept_up_for);
            $AndWherec .= " AND FIND_IN_SET(uid, '$dept_up_for_str')";
        } else{
            $AndWherec .= " AND 1=0";
        }
    }

    $sql = "SELECT * FROM users WHERE utype = 'College' AND udisplay != 'disable' $AndWhere $AndWherec GROUP BY uname ORDER BY uid DESC LIMIT $start, 10";
    $res = mysqli_query($con, $sql);

        if (mysqli_num_rows($res) === 0) {
            header('Content-Type: text/plain');
            echo '__NO_MORE_DATA__';
            exit;
        } else {
        $c = $start + 1;

        while ($rows = mysqli_fetch_assoc($res)) {
            $franName = "";
            $m_sql = "SELECT * FROM users WHERE uref_code = '" . mysqli_real_escape_string($con, $rows['admin_ref']) . "'";
            $m_run = mysqli_query($con, $m_sql);
            $m_rows = mysqli_fetch_assoc($m_run);
            if($m_rows["utype"] == 'subFranchiee'){
                $f_sql = mysqli_query($con, "SELECT * FROM users WHERE uref_code = '$m_rows[admin_ref]' ");
                if($f_row = mysqli_fetch_assoc($f_sql)){
                    $franName = $f_row["uname"];
                    $subFranName = $m_rows["uname"];
                }
            }elseif($m_rows["utype"] == 'Franchiee'){
                $franName = $m_rows["uname"];
                $subFranName = '';
            }

            $state_sql = mysqli_query($con, "SELECT * FROM state WHERE id = '" . mysqli_real_escape_string($con, $rows['state']) . "'");
            $state_name = mysqli_fetch_assoc($state_sql)["name"] ?? '';

            $dist_sql = mysqli_query($con, "SELECT * FROM dist WHERE id = '" . mysqli_real_escape_string($con, $rows['dist']) . "'");
            $dist_name = mysqli_fetch_assoc($dist_sql)["distName"] ?? '';

?>
<li class='clearfix' style='float: none;' id="college<?php echo $rows["uid"]?>">
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-6 col-12'>
                <a style='color:orange;font-size:17px;cursor:pointer; text-decoration:none;' class='viewDetails'
                    data-toggle='modal' data-target='#studentDetailsModal' data-name='<?php echo $rows["uname"];?>'
                    data-state='<?php echo $state_name;?>' data-dist='<?php echo $dist_name;?>'
                    data-pin='<?php echo $rows["pin"];?>' data-userid='<?php echo $rows["uphone"];?>'
                    data-pass='<?php echo $rows["upass"];?>' data-address='<?php echo $rows["saddress"];?>'
                    data-classs='<?php echo $class_name;?>' data-date='<?php echo $rows["ucreated"];?>'>
                    <i class='fa fa-user' aria-hidden='true'></i> <b><?php echo $rows["uname"];?></b> [
                    <?php echo $rows["referal_code"];?> ]
                </a>
                <br>
                <a href='tel:<?php echo $rows["ucontact"];?>' class='small text-dark text-decoration-none'
                    title='Click here to Call'> <i class='fa fa-phone fa-rotate-90'></i> <?php echo $rows["ucontact"];?>
                </a>
                &nbsp;
                <?php if(!empty($franName)){?>
                <b><i class='fa fa-industry'></i> </b><?php echo $franName;?>
                <?php } if(!empty($subFranName)){
                    ?>
                ( <b><i class='fa fa-industry'></i> </b><?php echo $subFranName;?> )
                <?php }?>
            </div>

            <div class='col-md-6 col-12'>
                <div class="d-flex justify-content-between align-items-center mb-1">
                    <a href='uplodDocuments.php?user=<?php echo $rows["uid"];?>&show_list'
                        class='btn btn-primary btn-sm' title='Click to Edit'>Document
                    </a>
                    <a href='view-college.php?view_id=<?php echo $rows["uid"];?>' class='btn btn-success btn-sm'
                        title='Click to Edit'><i class='fa fa-eye' aria-hidden='true'></i>
                    </a>
                    <a href='view-college.php?edit_id=<?php echo $rows["uid"];?>' class='btn btn-success btn-sm'
                        title='Click to Edit'><i class='fa fa-edit' aria-hidden='true'></i>
                    </a>
                    <a href="facility.php?college=<?php echo $rows["uid"];?>"
                        class="btn btn-sm btn-primary">Facility</a>
                    <a href="faq.php?college=<?php echo $rows["uid"];?>" class="btn btn-sm btn-primary">FAQ</a>
                    <a href="ctag.php?college=<?php echo $rows["uid"];?>" class="btn btn-sm btn-primary">TAG</a>
                    <a href="department.php?college=<?php echo $rows["uid"];?>"
                        class="btn btn-sm btn-primary">Department</a>
                    <!-- Status Switch Container -->
                    <div class="form-check form-switch status-switch" data-user-id="<?php echo $rows['uid']; ?>">
                        <input class="form-check-input" type="checkbox" role="switch"
                            id="switch_<?php echo $rows['uid']; ?>">
                        <label class="form-check-label" for="switch_<?php echo $rows['uid']; ?>">Loading...</label>
                    </div>
                </div>
                <div class="d-flex justify-content-between align-items-center">
                    <a href="course.php?college=<?php echo $rows["uid"];?>" class="btn btn-sm btn-primary">Course</a>
                    <a href="admission.php?college=<?php echo $rows["uid"];?>"
                        class="btn btn-sm btn-primary">Admission</a>
                    <a href="c-entrance.php?college=<?php echo $rows["uid"];?>"
                        class="btn btn-sm btn-primary">Entrance</a>
                    <a href="seo.php?college=<?php echo $rows["uid"];?>" class="btn btn-sm btn-primary">SEO</a>
                    <a href="placement.php?college=<?php echo $rows["uid"];?>"
                        class="btn btn-sm btn-primary">Placement</a>
                    <a href="wallpaper.php?college=<?php echo $rows["uid"];?>"
                        class="btn btn-sm btn-primary">Wallpaper</a>
                    <a href="gallery.php?college=<?php echo $rows["uid"];?>" class="btn btn-sm btn-primary">Gallery</a>
                </div>
            </div>
        </div>
    </div>
</li>

<?php
            $c++;
        }
        mysqli_close($con);
    }
}
?>
<script>
function initializeStatusSwitches() {
    $('.status-switch').each(function() {
        const container = $(this);
        const userId = container.data('user-id');
        const inputSwitch = container.find('input');
        const label = container.find('label');

        // Fetch current status
        $.post('fetch_status.php', {
            userId
        }, function(response) {
            try {
                const data = JSON.parse(response);
                const status = parseInt(data.uStatus, 10) || 0;

                inputSwitch.prop('checked', status === 1);
                label.text(status === 1 ? 'Active' : 'Inactive');
                inputSwitch.attr('title', 'Click to ' + (status === 1 ? 'Inactive' : 'Active'));
            } catch (e) {
                console.error('Status fetch error:', e);
                label.text('Error');
            }
        });

        // Handle switch change
        inputSwitch.on('change', function() {
            const newStatus = $(this).is(':checked') ? 1 : 0;

            $.post('update_status.php', {
                userId,
                uStatus: newStatus
            }, function(response) {
                try {
                    const res = JSON.parse(response);
                    if (res.status === 'success') {
                        label.text(newStatus === 1 ? 'Active' : 'Inactive');
                        inputSwitch.attr('title', 'Click to ' + (newStatus === 1 ? 'Inactive' :
                            'Active'));
                    } else {
                        alert(res.message || 'Update failed');
                        inputSwitch.prop('checked', !newStatus);
                    }
                } catch (e) {
                    console.error('Update parse error:', e);
                    alert('Error updating status');
                    inputSwitch.prop('checked', !newStatus);
                }
            }).fail(function() {
                alert('Update request failed');
                inputSwitch.prop('checked', !newStatus);
            });
        });
    });
}
</script>


<script>
$(document).ready(function() {
    $('.viewDetails').on('click', function(e) {
        e.preventDefault(); // Prevent default anchor tag action

        var name = $(this).data('name');
        $('#modalName').text(name);

        var state = $(this).data('state');
        $('#modalState').text(state);

        var dist = $(this).data('dist');
        $('#modalDist').text(dist);

        var pin = $(this).data('pin');
        $('#modalPin').text(pin);

        var userid = $(this).data('userid');
        $('#modalId').text(userid);

        var pass = $(this).data('pass');
        $('#modalPass').text(pass);

        var classs = $(this).data('classs');
        $('#modalClasss').text(classs);

        var qualification = $(this).data('qualification');
        $('#modalqualification').text(qualification);

        var address = $(this).data('address');
        $('#modalAddress').text(address);

        var date = $(this).data('date');
        $('#modalDate').text(date);

        $('#studentDetailsModal').modal('show'); // Open the modal
    });

});
</script>