<?php 
include "../db.php";
if (isset($_POST['start'])) {
    $start= mysqli_real_escape_string($con,$_POST['start']);
    $AndWhere = "WHERE wl_recycle !='0'";

    // Vendor / Hotel filters
    $FirstFilterValue = $_POST['FirstFilterValue'] ?? '';
    $SecondFilterValue = $_POST['SecondFilterValue'] ?? '';
    $startDate = $_POST['startDate'] ?? '';
    $endDate   = $_POST['endDate'] ?? '';

    // If FirstFilterValue (work_place wp_name) is set
    if (!empty($FirstFilterValue)) {
        $wp_sql = mysqli_query($con, "SELECT wp_id FROM work_place WHERE wp_name = '" . mysqli_real_escape_string($con, $FirstFilterValue) . "' LIMIT 1");
        if (mysqli_num_rows($wp_sql) > 0) {
            $wp_row = mysqli_fetch_assoc($wp_sql);
            $FirstFilterValue1 = $wp_row['wp_id']; // replace with actual wp_id
            $AndWhere .= " AND wl_vendor_id = '" . mysqli_real_escape_string($con, $FirstFilterValue1) . "'";
        }
    }

    // If SecondFilterValue is set (direct vendor id)
    if (!empty($SecondFilterValue)) {
        $AndWhere .= " AND wl_vendor_id = '" . mysqli_real_escape_string($con, $SecondFilterValue) . "'";
    }


    // Date filters
    if (!empty($startDate) && !empty($endDate)) {
        $AndWhere .= " AND wl_date BETWEEN '".mysqli_real_escape_string($con,$startDate)."' 
                                     AND '".mysqli_real_escape_string($con,$endDate)."'";
    } elseif (!empty($startDate)) {
        $AndWhere .= " AND wl_date = '".mysqli_real_escape_string($con,$startDate)."'";
    } elseif (!empty($endDate)) {
        $AndWhere .= " AND wl_date = '".mysqli_real_escape_string($con,$endDate)."'";
    }

    // SUMMARY CALCULATION 
    $summary_sql = "SELECT wl_id, wl_vendor_id, wl_amount_by_hotel, wl_amount_to_student FROM work_list $AndWhere";
    $summary_res = mysqli_query($con, $summary_sql);

    $totalWorks = mysqli_num_rows($summary_res);
    $totalStudents = 0;
    $totalPresent = 0;
    $totalAbsent = 0;
    $totalReceived = 0;
    $totalDispatched = 0;

    while ($work = mysqli_fetch_assoc($summary_res)) {
        $vendor_id = $work["wl_vendor_id"];
        $work_id   = $work["wl_id"];

        $stu_sql = mysqli_query($con, "SELECT ws_student FROM work_student WHERE ws_vendorId='$vendor_id' AND ws_workId='$work_id'");
        $studentCount = mysqli_num_rows($stu_sql);
        $totalStudents += $studentCount;

        $present = 0;
        $absent = 0;

        if ($studentCount > 0) {
            while ($stu = mysqli_fetch_assoc($stu_sql)) {
                $student_id = $stu['ws_student'];

                $att_sql = mysqli_query($con, "SELECT wa_attendance 
                                               FROM work_attendance 
                                               WHERE wa_student = '$student_id' 
                                                 AND wa_vendorId = '$vendor_id' 
                                                 AND wa_workId = '$work_id' 
                                               LIMIT 1");

                if (mysqli_num_rows($att_sql) > 0) {
                    $att_row = mysqli_fetch_assoc($att_sql);
                    if ($att_row['wa_attendance'] == 1) {
                        $present++;
                    } else {
                        $absent++;
                    }
                } else {
                    $absent++;
                }
            }
        }

        $totalPresent += $present;
        $totalAbsent += $absent;
        $totalReceived += $present * $work["wl_amount_by_hotel"];
        $totalDispatched += $present * $work["wl_amount_to_student"];
    }

    /** -------------------
     *  SHOW SUMMARY BLOCK
     * ------------------- */
    ?>
<div class="summary-block mb-3 p-3 border rounded bg-light">
    <!--<h5>Summary (Applied Filters)</h5>-->
    <div class="row">
        <div class="col-md-2"><b>Total Works:</b> <?= $totalWorks; ?></div>
        <!--<div class="col-md-3"><b>Total Students:</b> <?= $totalStudents; ?></div>
        <div class="col-md-3"><b>Present:</b> <?= $totalPresent; ?></div>
        <div class="col-md-3"><b>Absent:</b> <?= $totalAbsent; ?></div>-->
        <div class="col-md-5"><b>Total Received:</b> <?= $totalReceived; ?>/-</div>
        <div class="col-md-5"><b>Total Dispatched:</b> <?= $totalDispatched; ?>/-</div>
    </div>
    <div class="text-muted">
        <small>
            Filtered by:
            Vendor/Hotel = <?= !empty($FirstFilterValue) ? $FirstFilterValue : "All"; ?> |
            Date = <?= (!empty($startDate) || !empty($endDate)) ? "$startDate to $endDate" : "All"; ?>
        </small>
    </div>
</div>
<?php

    /** -------------------
     *  PAGINATED LIST
     * ------------------- */
    $sql = "SELECT * FROM work_list $AndWhere ORDER BY wl_id 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)) {
            $vendor_id = $rows["wl_vendor_id"];
            $vendor_sql = mysqli_query($con, "SELECT * FROM work_place WHERE wp_id = '$vendor_id' ");
            if($vendor_row = mysqli_fetch_assoc($vendor_sql)){
                $vendor = $vendor_row["wp_name"];
            }

            $total_student = 0;
            $totalStudent_sql = mysqli_query($con, "SELECT ws_student FROM work_student WHERE ws_vendorId = '$vendor_id' AND ws_workId = '{$rows["wl_id"]}'");

            $total_student = mysqli_num_rows($totalStudent_sql);

            $present_students = 0;
            $absent_students = 0;

            if ($total_student > 0) {
                while ($stu = mysqli_fetch_assoc($totalStudent_sql)) {
                    $student_id = $stu['ws_student'];
                    $att_sql = mysqli_query($con, "SELECT wa_attendance FROM work_attendance WHERE wa_student = '$student_id' AND wa_vendorId = '$vendor_id' AND wa_workId = '{$rows["wl_id"]}' LIMIT 1 ");
                    if (mysqli_num_rows($att_sql) > 0) {
                        $att_row = mysqli_fetch_assoc($att_sql);
                        if ($att_row['wa_attendance'] == 1) {
                            $present_students++;
                        } else {
                            $absent_students++;
                        }
                    } else {
                        $absent_students++;
                    }
                }
            }

            //Get the student details for each work each student
            $students_data = [];
            $stu_sql = mysqli_query($con, "SELECT ws_student FROM work_student WHERE ws_vendorId='$vendor_id' AND ws_workId='{$rows["wl_id"]}'");
            while ($stu = mysqli_fetch_assoc($stu_sql)) {
                $student_id = $stu['ws_student'];

                // get user info
                $user_sql = mysqli_query($con, "SELECT uname, ucontact FROM users WHERE uid='$student_id' LIMIT 1");
                $user = mysqli_fetch_assoc($user_sql);

                // check attendance
                $att_sql = mysqli_query($con, "SELECT wa_attendance FROM work_attendance 
                                            WHERE wa_student='$student_id' 
                                                AND wa_vendorId='$vendor_id' 
                                                AND wa_workId='{$rows["wl_id"]}' LIMIT 1");
                $attendance = (mysqli_num_rows($att_sql) > 0) ? mysqli_fetch_assoc($att_sql)['wa_attendance'] : 0;

                $students_data[] = [
                    "name" => $user['uname'] ?? "Unknown",
                    "contact" => $user['ucontact'] ?? "-",
                    "attendance" => $attendance
                ];
            }

            $displayTime = date("g:i A", strtotime($rows["wl_time"]));
?>
<li class='clearfix' style='float: none;' id="employee<?php echo $rows["wl_id"]?>">
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-4 col-xs-5'>
                <div class="intro-admin">
                    <a style='color:orange;font-size:17px;' class='viewDetails' data-toggle='modal'
                        data-target='#adminDetailsModal' data-name='<?php echo !empty($vendor) ? $vendor : "-"; ?>'
                        data-title='<?php echo !empty($rows["wl_title"]) ? $rows["wl_title"] : "-"; ?>'
                        data-startdate='<?php echo !empty($rows["wl_date"]) ? $rows["wl_date"] : "-"; ?>'
                        data-time='<?php echo !empty($displayTime) ? $displayTime : "-"; ?>'
                        data-hotelamount='<?php echo !empty($rows["wl_amount_by_hotel"]) ? $rows["wl_amount_by_hotel"] : "-"; ?>'
                        data-studentamount='<?php echo !empty($rows["wl_amount_to_student"]) ? $rows["wl_amount_to_student"] : "-"; ?>'
                        data-totalreceived='<?php echo $present_students * $rows["wl_amount_by_hotel"]; ?>'
                        data-totaldispatched='<?php echo $present_students * $rows["wl_amount_to_student"]; ?>'
                        data-date='<?php echo !empty($rows["wl_cDate"]) ? $rows["wl_cDate"] : "-"; ?>'
                        data-total='<?php echo !empty($total_student) ? $total_student : "-"; ?>'
                        data-absent='<?php echo !empty($absent_students) ? $absent_students : "-"; ?>'
                        data-present='<?php echo !empty($present_students) ? $present_students : "-"; ?>'
                        data-students='<?php echo json_encode($students_data, JSON_HEX_APOS | JSON_HEX_QUOT); ?>'>
                        <i class="fa fa-calculator" aria-hidden="true"></i>
                        <b><?= $vendor;?></b> <br>
                        <b><?= ' ( ' . $rows["wl_title"] . ' )';?></b>
                    </a>
                </div>
            </div>

            <div class='col-md-3'>
                Total Students: <?= $total_student; ?> <br>
                <div class="d-flex justify-content-between">
                    <span>Present: <?= $present_students;?></span>
                    <span>Absent: <?= $absent_students;?></span>
                </div>
            </div>

            <div class='col-md-5'>
                <div class="d-flex justify-content-between">
                    <span>Received Per student: <?= $rows["wl_amount_by_hotel"];?>/-</span>
                    <span>Dispatched Per student: <?= $rows["wl_amount_to_student"];?>/-</span>
                </div>
                <div class="d-flex justify-content-between">
                    <span>Total Received: <?= $present_students * $rows["wl_amount_by_hotel"];?>/-</span>
                    <span>Total Dispatched: <?= $present_students * $rows["wl_amount_to_student"];?>/-</span>
                </div>
            </div>
        </div>
    </div>
</li>
<?php
          $c++;
        }
        mysqli_close($con);
    }
}
?>


<script>
$(document).ready(function() {
    $('.viewDetails').on('click', function(e) {
        e.preventDefault();

        $('#modalName').text($(this).data('name'));
        $('#modalTitle').text($(this).data('title'));
        $('#modalStartDate').text($(this).data('startdate'));
        $('#modaltime').text($(this).data('time'));
        $('#modalHotelAmount').text($(this).data('hotelamount'));
        $('#modalStudentAmount').text($(this).data('studentamount'));
        $('#modalDate').text($(this).data('date'));
        $('#modalTotalReceived').text($(this).data('totalreceived'));
        $('#modalTotalDispatched').text($(this).data('totaldispatched'));
        $('#total').text($(this).data('total'));
        $('#present').text($(this).data('present'));
        $('#absent').text($(this).data('absent'));

        // Students grid display of Presrnt and absent
        var students = $(this).data('students');
        var $list = $("#modalStudents");
        $list.empty();

        if (students && students.length > 0) {
            students.forEach(function(stu) {
                var badgeClass = stu.attendance == 1 ? "success" : "danger";
                var statusText = stu.attendance == 1 ? "Present" : "Absent";

                $list.append(
                    '<div class="col-md-3 mb-3">' +
                    '<div class="border rounded p-2 text-center">' +
                    '<strong>' + stu.name + '</strong><br>' +
                    '<small>' +
                    '<i class="fa fa-phone" aria-hidden="true"></i> ' +
                    '<a href="tel:' + stu.contact + '">' + stu.contact + '</a>' +
                    '</small><br>' +
                    '<span class="badge bg-' + badgeClass + '">' + statusText + '</span>' +
                    '</div>' +
                    '</div>'
                );
            });
        } else {
            $list.append('<div class="col-12"><p>No students found.</p></div>');
        }

        $('#adminDetailsModal').modal('show');
    });
});
</script>