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


if (isset($_POST['start'])) {
    
    $start= mysqli_real_escape_string($con,$_POST['start']);
     $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['SecondFilterValue']) ) {

         $AndWhere .= "";

    }

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


        $AndWhere .= " AND st_name='$_POST[ThirdFilterValue]'";
    }

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

        $AndWhere .= " AND st_ph='$_POST[aFilterValue]'";
    }

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

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

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

        $AndWhere .= " AND st_category='$_POST[cFilterValue]'";
    }

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

        $AndWhere .= " AND lead_source_name = '$_POST[a2FilterValue]'";
    }

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

        $AndWhere .= " AND st_lead_source_id = '$_POST[b2FilterValue]'";
    }

/* Sub Associate Fatching */
// $subAss_sql = mysqli_query($con, "SELECT * FROM users WHERE");

/*---- count ---------*/
  $st_sql = "SELECT * FROM status  WHERE s_by='".$_POST['uadmin']."' 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_admin` ='".$_POST['uadmin']."' AND st_by='".$_POST['uid']."' AND 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 `st_admin` ='".$_POST['uadmin']."' AND st_by='".$_POST['uid']."' AND `flag_status` ='A' $AndWhere ORDER BY st_lastRemarkDate 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 status Start*/
            $st_show_sql = "SELECT * FROM status  WHERE s_id = '$rows[st_status]'";
            $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*/
          /*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 Admin remark End*/
          /*Sub Agent select option Start*/
          $st_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)) {
                  $st_loop = "<option value='{$sadm_row['uid']}' selected>{$sadm_row['uname']}</option>";
              }
          }

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

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

          /*lead_source_form_name Start*/

            $sf_sql = "SELECT * FROM `lead_source` WHERE `id` = '$rows[st_lead_source_id]'";
            $sf_run = mysqli_query($con, $sf_sql);
            $sf_row = mysqli_fetch_assoc($sf_run);
            $sf_num =mysqli_num_rows($sf_run);
            $leadSourceForm = ($sf_num > 0)?$sf_row['lead_source_form_name']:'';
          /*lead_source_form_name 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-8'>
                <a href="edit_candidate.php?id=<?= $rows['st_no']; ?>" style=" text-decoration:none;">
                    <i class='fa fa-user-circle' aria-hidden='true' style='color:orange;font-size:16px;'></i>
                    <b style='font-size:16px;'><?= $rows['st_name']; ?> ( <?= $st_show; ?> )</b>
                </a>

                <b style='color:#3333ff;'>
                    <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>
                    &nbsp;
                    <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>
                </b>
                <br><?= $course; ?>
                <br>
                <i class="fas fa-map-marker-alt"></i> <?= $rows['st_address']; ?>, <?= $rows['st_city']; ?>

                <br>
                <b><i class="fa fa-upload" aria-hidden="true"></i> </b> <?= $rows['uploadDT']; ?>
                <br>
                <b>Lead Source: </b><?= $rows['lead_source_name']; ?> <br>
                <b>Source Form: </b><?= $leadSourceForm; ?> <br>
            </div>
            <div class="col-md-4">
                <b>Sub Agent Change : </b>
                <select class='subagentChange form-control form-control-sm' id='<?= $rows['st_no'] ?>'>
                    <?= $st_loop ?>
                </select>
            </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);
            }
        });
    });


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