<?php 

  ob_start();

  include "../../db.php";

  date_default_timezone_set('Asia/Kolkata');

  $currentCoreDate = date("Y-m-d");

  session_start();



if (isset($_POST['start'])) {

    

    $start= mysqli_real_escape_string($con,$_POST['start']);

     $AndWhere ='';



    

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



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



    }



    if ( !empty($_POST['SecondFilterValue']) ) {



         $AndWhere .= "AND st_status = '$_POST[SecondFilterValue]' ";

    }



    if (!empty($_POST['ThirdFilterValue'])) {



        $sql = "SELECT uid FROM users WHERE uname='$_POST[ThirdFilterValue]'";

        $res = mysqli_query($con,$sql);

        $row = mysqli_fetch_assoc($res);

        $AndWhere .= "AND st_by = '$row[uid]'";

    }



/*---- count ---------*/

  $st_sql = "SELECT * FROM status WHERE s_by='$_SESSION[uref]' ORDER BY s_pos ASC";

  $st_res = mysqli_query($con,$st_sql);

  $st_output = "<div class='col-md-12 text-center'>";

  while ($st_rows = mysqli_fetch_assoc($st_res)) {



      $count_sql = "SELECT * FROM student_details WHERE st_status = '$st_rows[s_id]' AND `flag_status` ='A' $AndWhere";

      $count_res = mysqli_query($con,$count_sql);

      $count_total_rows = mysqli_num_rows($count_res);



      $st_output .="

                    <b><i class='fa fa-check-square' aria-hidden='true' style='color:green;'></i> $st_rows[s_name] : $count_total_rows &nbsp; &nbsp;</b>

                ";

  }

  $st_output .= "<hr></div>";

  echo $st_output;



/*---------------*/



$sql = "SELECT * FROM student_details WHERE `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)) {



          /* show upload admin Start*/

          if(!empty($rows["st_by"])){

            $adm_sql = "SELECT uname FROM users  WHERE uid = '$rows[st_by]'";

            $adm_run = mysqli_query($con, $adm_sql);

            $adm_rows = mysqli_fetch_assoc($adm_run);

            $admin = "<b style='color:#3333ff;'><i class='fa fa-user' aria-hidden='true'></i> ".$adm_rows['uname']."</b>";

          }

          /* show upload admin End*/



          /* show status Start*/

          $st_show = '';

          if(!empty($rows["ustd_status"])){

            $st_show_sql = "SELECT * FROM status WHERE s_id = '$rows[ustd_status]' AND s_by='$_POST[uref]'";

            $st_show_run = mysqli_query($con, $st_show_sql);

            $st_show_row = mysqli_fetch_assoc($st_show_run);

            $st_show = $st_show_row['s_name'];

          }

          /* show status End*/



          /*status select option Start*/

            $st_loop ="<option selected disable>select</option>";

            $st_sql = "SELECT * FROM status WHERE s_by='$_SESSION[uref]'  ORDER BY s_pos ASC";

            $st_run = mysqli_query($con, $st_sql);

            while ( $st_rows = mysqli_fetch_assoc($st_run) ) {

              

                $st_loop .= "<option value='".$st_rows['s_id']."'>".$st_rows['s_name']."</option>";

            }



          /*status select option End*/

          $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 Admin remark 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-9 col-xs-7 second-item">

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

                (<b><?= $st_show ?></b>)

                <br>



                <i class="fa fa-phone fa-rotate-90"></i> <?= $rows['st_ph'] ?> &nbsp;

                <i class="fab fa-whatsapp"></i> <?= $rows['st_wp_no'] ?>

                <br>



                <i class="fas fa-map-marker-alt"></i> <?= $rows['st_address'] ?>

                <br>



                <b>S<i class="far fa-clock"></i>: </b> <?= $rows['uploadDT'] ?>

            </div>



            <div class="col-md-3 col-xs-5 third-item">

                <button data-bs-toggle="modal" class="m-2 btn btn-success btn-sm adminRemarkDetails"

                    id="<?= $rows['st_no'] ?>" data-bs-target="#remarkModal" data-title="Admin Remarks"

                    style="width:50px;">

                    <b style="font-size:14px;">A</b>

                    <i class="fa fa-pencil-square" aria-hidden="true" style="font-size:15px;"></i>

                </button>

            </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++;

        }



        mysqli_close($con);

    }



}

?>



<script>

$(document).ready(function() {



    $('.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);

            }

        });

    });





    $('.adminRemarkDetails').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: 'adminRemark',

                remark_for: remark_for

            },

            success: function(result) {

                $('#remarkShow').html(result);

            }

        });

    });

});

</script>