<?php 
  ob_start();
  include "../../db.php";
//   include "includes/function.php";
  date_default_timezone_set('Asia/Kolkata');
  $currentCoreDate = date("Y-m-d");
  session_start();

$adm_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '$_SESSION[uid]' ");
if($adm_row = mysqli_fetch_assoc($adm_sql)){
    $uadmin = $adm_row["uadmin"];
    $admin_ref = $adm_row["admin_ref"];
}

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

    if (!empty($_POST['First1FilterValue']) && !empty($_POST['First2FilterValue']) ) {

        $AndWhere .= "AND st_lastRemarkDate BETWEEN '$_POST[First1FilterValue]' AND '$_POST[First2FilterValue]'";
    }
    if (!empty($_POST['First1FilterValue']) && empty($_POST['First2FilterValue']) ) {

        $AndWhere .= "AND st_lastRemarkDate BETWEEN '$_POST[First1FilterValue]' AND '$currentCoreDate'";

    }
    if (empty($_POST['First1FilterValue']) && !empty($_POST['First2FilterValue']) ) {

        echo "<div style='text-align:center;font-size:20px;color:red;padding:15px;background:#f2f2f2;'>You Have To Enter Starting Date First.</div><br>";
        die();
    }


    if (!empty($_POST['Second1FilterValue']) && !empty($_POST['Second2FilterValue']) ) {

        $AndWhere .= "AND last_followup_date BETWEEN '$_POST[Second1FilterValue]' AND '$_POST[Second2FilterValue]'";
    }
    if (!empty($_POST['Second1FilterValue']) && empty($_POST['Second2FilterValue']) ) {

        $AndWhere .= "AND last_followup_date BETWEEN '$_POST[Second1FilterValue]' AND '$currentCoreDate'";
    }
    if (empty($_POST['Second1FilterValue']) && !empty($_POST['Second2FilterValue']) ) {

        echo "<div style='text-align:center;font-size:20px;color:red;padding:15px;background:#f2f2f2;'>You Have To Enter Starting Date First.</div><br>";
        die();
    }

    if (!empty($_POST['ThirdFilterValue'])) {
        $AndWhere .= "AND st_name='$_POST[ThirdFilterValue]'";
    }



$sql = "SELECT * FROM student_details WHERE st_status = '$st' AND st_by='$_SESSION[uid]' AND `flag_status` ='A' $AndWhere ORDER BY st_no DESC LIMIT $start,25";

$res = mysqli_query($con,$sql);
if ($total_rows=mysqli_num_rows($res)>0) {
    $s_output="";
    $c = $start+25;
    while ($rows=mysqli_fetch_assoc($res)) {

        /*status select option Start*/
        $st_loop = '';

        // Check if st_status is not empty
        if (!empty($rows["st_status"])) {
            $st_show_sql = "SELECT * FROM status WHERE s_id = '" . $rows['st_status'] . "'";
            $st_show_run = mysqli_query($con, $st_show_sql);
            
            if ($st_show_row = mysqli_fetch_assoc($st_show_run)) {
                $st_show = $st_show_row['s_name'];
                // Show the current status and disable it
                $st_loop .= "<option value='" . $rows['st_status'] . "' disabled selected>" . $st_show . "</option>";
            }
        } else {
            // Show default select option if no status exists
            $st_loop .= "<option selected disabled>Select Status</option>";
        }

        // Fetch all status options
        $st_sql = "SELECT * FROM status WHERE s_by='$uadmin' ORDER BY s_pos ASC";
        $st_run = mysqli_query($con, $st_sql);

        while ($st_rows = mysqli_fetch_assoc($st_run)) {
            // Skip adding the already selected status again
            if ($st_rows['s_id'] != $rows['st_status']) {
                $st_loop .= "<option value='" . $st_rows['s_id'] . "'>" . $st_rows['s_name'] . "</option>";
            }
        }

        /*status select option End*/

         /*Sub Agent select option Start*/
         $sub_loop = "<option selected disabled>Select Sub Agent</option>";

         if (!empty($rows["st_sub_by"])) {
             $sadm_sql = mysqli_query($con, "SELECT * FROM users WHERE uid = '{$rows['st_sub_by']}'");
             if ($sadm_row = mysqli_fetch_assoc($sadm_sql)) {
                 $sub_loop = "<option value='{$sadm_row['uid']}' selected>{$sadm_row['uname']}</option>";
             }
         }

         $sub_sql = "SELECT `uid`,`uname` FROM users WHERE utype='Sub Associate' AND `admin_ref` = '{$_SESSION['uref_code']}' ORDER BY `uname` ASC";
         $sub_run = mysqli_query($con, $sub_sql);

         while ($sub_rows = mysqli_fetch_assoc($sub_run)) {
             $disabled = ($rows['st_sub_by'] == $sub_rows['uid']) ? "disabled" : "";
             $sub_loop .= "<option value='{$sub_rows['uid']}' $disabled>{$sub_rows['uname']}</option>";
         }
       /*Sub Agent select option End*/

        /*latest remark Start*/
        $all_remarks = "";
        $latest_remark = "";
        
        // Array to store remarks
        $all_remarks_array = [];
        
        // Fetch and store user remarks with username
        $r_run = mysqli_query($con, "SELECT r.*, u.uname FROM remark r 
            LEFT JOIN users u ON u.uid = r.r_by 
            WHERE r.r_sid = '$rows[st_no]' 
            ORDER BY STR_TO_DATE(r.uploadDate, '%Y-%m-%d %H:%i:%s') DESC");
        
        while ($r_row = mysqli_fetch_assoc($r_run)) {
            $username = !empty($r_row['uname']) ? $r_row['uname'] : 'Unknown User';
            $followupDate = !empty($r_row['followup_date']) ? " <br> FollowUp Date : {$r_row['followup_date']}" : '';
            $followupTime = !empty($r_row['followup_time']) ? " / FollowUp Time : " . date("g:i A", strtotime($r_row['followup_time'])) : '';
        
            $all_remarks_array[] = [
                'remark' => "<b style='color:#3333ff;'><i class='fas fa-comments'></i> {$username}: " . $r_row['remark'] . " </b> (" . $r_row['uploadDate'] . ")" . $followupDate . $followupTime,
                'uploadDate' => $r_row['uploadDate']
            ];
        }
        
        // Fetch and store admin remarks
        $r_run_admin = mysqli_query($con, "SELECT * FROM admin_remark 
            WHERE r_sid = '$rows[st_no]' 
            ORDER BY STR_TO_DATE(uploadDate, '%Y-%m-%d %H:%i:%s') DESC");
        
        while ($r_row_admin = mysqli_fetch_assoc($r_run_admin)) {
            $all_remarks_array[] = [
                'remark' => "<b style='color:red;'>Admin <i class='fas fa-comments'></i> " . $r_row_admin['remark'] . " </b> (" . $r_row_admin['uploadDate'] . ")",
                'uploadDate' => $r_row_admin['uploadDate']
            ];
        }
        
        // Merge and sort remarks by date (latest first)
        usort($all_remarks_array, function ($a, $b) {
            return strtotime($b['uploadDate']) - strtotime($a['uploadDate']);
        });
        
        // Store all remarks and set the latest remark
        if (!empty($all_remarks_array)) {
            $latest_remark = $all_remarks_array[0]['remark']; // First (latest) remark
            foreach ($all_remarks_array as $remark) {
                $all_remarks .= $remark['remark'] . "<br>";
            }
        }
        /*latest remark End*/
		  
		  
		/* show upload course Start*/
        $adm_sql = "SELECT cat_name FROM clg_course_cat WHERE sl_no = '$rows[st_category]'";
        $adm_run = mysqli_query($con, $adm_sql);
        $adm_rows = mysqli_fetch_assoc($adm_run);
        $course = "<b style='color:#3333ff;'><i class='fas fa-tags'></i> ".$adm_rows['cat_name']."</b>";
        /* show upload course End*/
		  

        /*followup datetime Start*/
        if (!empty($rows['last_followup_date']) && !empty($rows['last_followup_time'])) {
            $followup_datetime = "<b> <i class='far fa-calendar-alt'></i> </b>".$rows['last_followup_date']." ".($rows['last_followup_time']);
        }else{
            $followup_datetime = '';
        }
        /*followup datetime End*/
          
           ?>
<li class='clearfix' style='float: none;'>
    <div class="single-dis-admin mb-2">
        <span id="status-msg-<?= $rows['st_no']; ?>" class="text-center"></span>
        <div class="row">
            <div class="col-md-7">
                <i class="fa fa-user-circle" aria-hidden="true" style="color:orange; font-size:18px;"></i>
                <b style="color:black; font-size:17px;"><?= $rows['st_name']; ?></b>
                <br>

                <i class="fas fa-map-marker-alt"></i> <?= $rows['st_address']; ?>, <?= $rows['st_city']; ?>
                <br>
                <?= $course; ?> <br>
                <i class="fas fa-bullseye"></i> <?= $rows['st_about']; ?>
                <br>
                <b><i class="fa fa-upload" aria-hidden="true"></i></b> <?= $rows['uploadDT']; ?>
            </div>
            <div class="col-md-3">
                <div class="small">Update Status</div>
                <select class="status_change form-control mt-2" id="<?= $rows['st_no']; ?>">
                    <?= $st_loop; ?>
                </select> <br>
                <b>Sub Agent Change : </b>
                <select class='subagentChange form-control form-control-sm' id='<?= $rows['st_no'] ?>'>
                    <?= $sub_loop ?>
                </select>
            </div>
            <div class="col-md-1 d-flex justify-content-between">
                <div>
                    <a href="tel:+91<?= $rows['st_ph']; ?>" class="m-2 btn btn-success btn-sm" style="width:35px;">
                        <i class="fa fa-phone" aria-hidden="true" style="font-size:17px;"></i>
                    </a>
                </div>

                <div>
                    <a href="https://api.whatsapp.com/send?phone=91<?= $rows['st_wp_no']; ?>"
                        class="m-2 btn btn-success btn-sm" style="width:35px;">
                        <b style="font-size:15px;"><i class="fab fa-whatsapp"></i></b>
                    </a>
                </div>

                <div>
                    <!-- Button to Open Modal -->
                    <button data-bs-toggle="modal" class="m-2 btn btn-success btn-sm remarkDetails"
                        id="<?= $rows['st_no']; ?>" data-bs-target="#remarkModal" data-title="Remarks"
                        style="width:35px;">
                        <i class="fa fa-comment" aria-hidden="true" style="font-size:17px;"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-12 mt-3">
                <div class="about-display mb-2">
                    <label for="">Avout :</label>
                    <?= implode(', ', array_filter([$rows['st_about'], $rows['st_about2'], $rows['st_about3'], $rows['st_about4'], $rows['st_about5'], $rows['st_about6'], $rows['st_about7'], $rows['st_about8']])) ?>
                </div>
                <!-- Remark Accordion Start -->
                <div class="accordion" id="remarkAccordion<?= $rows['st_no'] ?>">
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="heading<?= $rows['st_no'] ?>">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse"
                                data-bs-target="#collapse<?= $rows['st_no'] ?>" aria-expanded="false"
                                aria-controls="collapse<?= $rows['st_no'] ?>">
                                <b><?= !empty($latest_remark) ? $latest_remark : 'No Recent Remarks' ?></b>
                            </button>
                        </h2>
                        <div id="collapse<?= $rows['st_no'] ?>" class="accordion-collapse collapse"
                            aria-labelledby="heading<?= $rows['st_no'] ?>"
                            data-bs-parent="#remarkAccordion<?= $rows['st_no'] ?>">
                            <div class="accordion-body">
                                <?= !empty($all_remarks) ? $all_remarks : '<p>No remarks available</p>'; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Remark Accordion End -->
            </div>
        </div>
    </div>

</li>
<?php
        $c++;
        }
        echo $s_output;
    }

}
?>

<script>
$(document).ready(function() {

    $('.subagentChange').on('change', function() {
        var agentId = this.value;
        var sid = $(this).attr('id');

        $.ajax({
            url: "action-Ajax.php",
            method: "POST",
            data: {
                action: 'subagentChange',
                agentId: agentId,
                sid: sid
            },
            cache: false,
            success: function(result) {
                $("#status-msg-" + sid).html(result);
            }
        });

    });


    $('.status_change').on('change', function() {
        var status_id = this.value;
        var sid = $(this).attr('id');

        $.ajax({
            url: "action-Ajax.php",
            method: "POST",
            data: {
                action: 'statusChange',
                status_id: status_id,
                sid: sid
            },
            cache: false,
            success: function(result) {
                $("#status-msg-" + sid).html(result);
            }
        });
    });


    $('.remarkDetails').on('click', function() {
        var remark_for = $(this).attr('id');
        var title = $(this).data('title');
        //console.log(remark_for);
        $('#modalName').text(title);

        $('.modal-css').css({
            'color': 'black'
        });
        $('.modal-name').css({
            'text-align': 'center',
            'color': 'black',
            'font-size': '20px'
        });
        $.ajax({
            url: 'action-Ajax.php',
            type: 'post',
            data: {
                action: 'remark',
                remark_for: remark_for
            },
            success: function(result) {
                $('#remarkShow').html(result);
            }
        });
    });
});
</script>