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

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

    if (!empty($_POST['FirstFilterValue'])) {
        $AndWhere .= "AND uname='" . mysqli_real_escape_string($con, $_POST['FirstFilterValue']) . "' ";
    }

    if (!empty($_POST['ThirdFilterValue'])) {
        $AndWhere .= "AND referal_code ='" . mysqli_real_escape_string($con, $_POST['ThirdFilterValue']) . "' ";
    }

    if (!empty($_POST['courseValue']) && !empty($_POST['batchValue'])) {
        // Fetch all pClient values for the selected course
        $product_sql = mysqli_query($con, "SELECT DISTINCT pClient FROM product WHERE pBatch = '{$_POST['batchValue']}' AND product = '".mysqli_real_escape_string($con, $_POST['courseValue'])."'");

        $clientIds = [];
        while ($row = mysqli_fetch_assoc($product_sql)) {
            $clientIds[] = "'" . mysqli_real_escape_string($con, $row['pClient']) . "'";
        }

        // If clients were found, build the AND condition
        if (!empty($clientIds)) {
            $clientList = implode(',', $clientIds);
            $AndWhere .= " AND uid IN ($clientList)";
        } else {
            // Optional: prevent matching any record if course has no clients
            $AndWhere .= " AND 0"; // This ensures no results
        }
    } elseif (!empty($_POST['courseValue'])) {
        // Fetch all pClient values for the selected course
        $product_sql = mysqli_query($con, "SELECT DISTINCT pClient FROM product WHERE product = '".mysqli_real_escape_string($con, $_POST['courseValue'])."'");

        $clientIds = [];
        while ($row = mysqli_fetch_assoc($product_sql)) {
            $clientIds[] = "'" . mysqli_real_escape_string($con, $row['pClient']) . "'";
        }

        // If clients were found, build the AND condition
        if (!empty($clientIds)) {
            $clientList = implode(',', $clientIds);
            $AndWhere .= " AND uid IN ($clientList)";
        } else {
            // Optional: prevent matching any record if course has no clients
            $AndWhere .= " AND 0"; // This ensures no results
        }
    }

    // Step 1: Fetch subFranchiee uref_codes
    $subFran_sql = mysqli_query($con, "SELECT uref_code FROM users WHERE utype = 'Sub Associate' AND udisplay != 'disable' AND admin_ref = '" . mysqli_real_escape_string($con, $_SESSION['uref_code']) . "'");
    $subFran_uref_codes = [];

    while ($row = mysqli_fetch_assoc($subFran_sql)) {
        $subFran_uref_codes[] = $row['uref_code']; // Add each uref_code to the array
    }

    // Add the current session uref_code to the array to check against all of them
    $subFran_uref_codes[] = $_SESSION['uref_code'];

    // Step 2: Modify the Client query to check admin_ref against the array of uref_codes
    $uref_codes_string = "'" . implode("','", array_map('mysqli_real_escape_string', array_fill(0, count($subFran_uref_codes), $con), $subFran_uref_codes)) . "'";

    $sql = "SELECT * FROM users WHERE utype = 'Student' AND udisplay != 'disable' AND admin_ref IN ($uref_codes_string) $AndWhere 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);
            if($m_rows = mysqli_fetch_assoc($m_run)){
                if($m_rows["utype"] == 'Sub Associate'){
                    $franName = $m_rows["uname"];
                    $subFranName = $m_rows["uname"];
                }else{
                    $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="client<?php echo $rows["uid"];?>">
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-7 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["ucontact"];?>'
                    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) && isset($_GET["kallol"])){?>
                <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-5 col-12'>
                <div class="d-inline-block d-lg-flex justify-content-between align-items-center">
                    <?php
                    // Fetch data_subCategory and data_category for the user
                    $checkSql =  mysqli_query($con, "SELECT * FROM data WHERE data_up_for = '{$rows["uid"]}' AND data_subCategory = 'KYC' AND data_catagory = 'Documents'"); 
                    
                    if($rows["uStatus"] == 0){?>
                    <a href='uplodDocuments.php?user=<?php echo $rows["uid"];?>&show_list'
                        class='btn btn-primary btn-sm' title='Click to Edit'>Document
                    </a>
                    <!--<button type="button" class="btn btn-outline-secondary btn-sm" disabled>KYC Uploaded</button>-->
                    <button type="button" class="btn btn-outline-primary btn-sm" disabled>Waiting For
                        Verification</button>
                    <?php } elseif(mysqli_num_rows($checkSql) > 0){
                    ?>
                    <a href='view-product.php?client_id=<?php echo $rows["uid"];?>' class='btn btn-success btn-sm'
                        title='Click to Edit'><i class="fa fa-chalkboard"></i> Courses
                    </a>
                    <a href='student-bill.php?client_id=<?php echo $rows["uid"];?>' class='btn btn-success btn-sm'
                        title='Click to Edit'><i class="fas fa-receipt"></i> Student Bill
                    </a>
                    <!--<a href='student-payout.php?client_id=<?php echo $rows["uid"];?>' class='btn btn-success btn-sm'
                        title='Click to Edit'><i class="fa fa-money-bill"></i> Pay Out
                    </a>-->
                    <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-client.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='view-client.php?del_id=<?php echo $rows["uid"];?>' class='delete btn btn-danger btn-sm'
                        title='Click to Delete'><i class='fa fa-trash' aria-hidden='true'></i>
                    </a>
                    <?php } else {?>
                    <!--<a href='kyc.php?user=<?php echo $rows["uid"];?>' class='btn btn-outline-secondary btn-sm'
                        title='Click to Delete'><i class='fa fa-upload' aria-hidden='true'></i> Upload KYC Document
                    </a>-->
                    <a href='view-product.php?client_id=<?php echo $rows["uid"];?>' class='btn btn-success btn-sm'
                        title='Click to Edit'><i class="fa fa-chalkboard"></i> Courses
                    </a>
                    <a href='student-bill.php?client_id=<?php echo $rows["uid"];?>' class='btn btn-success btn-sm'
                        title='Click to Edit'><i class="fas fa-receipt"></i> Student Bill
                    </a>
                    <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-client.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='view-client.php?del_id=<?php echo $rows["uid"];?>' class='delete btn btn-danger btn-sm'
                        title='Click to Delete'><i class='fa fa-trash' aria-hidden='true'></i>
                    </a>
                    <?php }?>
                </div>
            </div>
        </div>
    </div>
</li>

<?php
            $c++;
        }
        mysqli_close($con);
    }
}
?>


<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>