<?php 
include "../db.php";
session_start();
if (isset($_POST['start'])) {
    $start= mysqli_real_escape_string($con,$_POST['start']);
    $uref_code= mysqli_real_escape_string($con,$_POST['uref_code']);
    $userId= mysqli_real_escape_string($con,$_POST['userId']);
    $AndWhere ='';
    if (!empty($_POST['FirstFilterValue']) && empty($_POST['SecondFilterValue'])) {
        $AndWhere = "AND uname ='$_POST[FirstFilterValue]'";
    }elseif (empty($_POST['FirstFilterValue']) && !empty($_POST['SecondFilterValue'])) {
        $AndWhere = "AND referal_code ='$_POST[SecondFilterValue]'";
    }elseif (!empty($_POST['FirstFilterValue']) && !empty($_POST['SecondFilterValue'])) {
         $AndWhere = "AND uname ='$_POST[FirstFilterValue]'";
    }

    $sql = "SELECT * FROM users WHERE utype = 'Sub Associate' AND admin_ref = '$uref_code' AND udisplay != 'disabled' $AndWhere 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  {
        $s_output='';
        $c = $start+1;

        while ($rows=mysqli_fetch_assoc($res)) {
            //referance count end//
            ?>
<li class='clearfix' style='float: none;'>
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-9 col-xs-9'>
                <div class="d-flex justify-content-between align-items-center">
                    <div class="intro-admin">
                        <a style='color:orange;font-size:17px;text-decoration:none;' class='viewDetails'
                            data-toggle='modal' data-target='#adminDetailsModal'>
                            <i class='fa fa-user' aria-hidden='true'></i> <b><?php echo $rows["uname"];?></b> [
                            <?php echo $rows["referal_code"];?> ]
                        </a>
                    </div>
                </div>
            </div>
            <div class='col-md-3 d-flex justify-content-between align-items-center'>
                <a href='uplodDocuments.php?user=<?php echo $rows["uid"];?>&show_list' class='btn btn-primary btn-sm'
                    title='Click to Edit'>Document
                </a>
                <!-- Agreement Button --
                <a href='agreementDownload.php?user=<?php echo $rows["uid"];?>' class='btn btn-primary btn-sm'
                    title='Click to Agreement Page'>Agreement
                </a>-->
                <a href='subFranchiee-list.php?franchisee=<?php echo $userId;?>&view_id=<?php echo $rows["uid"];?>'
                    class='btn btn-info text-white btn-sm' title='Click to View'><i class='fa fa-eye'
                        aria-hidden='true'></i>
                </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>
    </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>