<?php 
include "../db.php";
if (isset($_POST['start'])) {
    $start= mysqli_real_escape_string($con,$_POST['start']);
    $SecondFilterValue = $_POST['SecondFilterValue'] ?? ''; // student id
    $FirstFilterValue = $_POST['FirstFilterValue'] ?? ''; // work place name
    $startDate = $_POST['startDate'] ?? '';
    $endDate   = $_POST['endDate'] ?? '';

    if (empty($SecondFilterValue)) {
        echo "<div class='alert alert-warning'>No student selected!</div>";
        exit;
    }

    
    // SUMMARY CALCULATION

    $AndWhere = "WHERE ws_student = '".mysqli_real_escape_string($con,$SecondFilterValue)."'";

    // 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 ws_vendorId = '" . mysqli_real_escape_string($con, $FirstFilterValue1) . "'";
        }
    }

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

    $summary_sql = "
        SELECT wl.wl_id, wl.wl_vendor_id, wl.wl_amount_by_hotel, wl.wl_amount_to_student
        FROM work_student ws
        INNER JOIN work_list wl ON ws.ws_workId = wl.wl_id
        $AndWhere
    ";
    $summary_res = mysqli_query($con, $summary_sql);

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

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

        // attendance for this student in this work
        $att_sql = mysqli_query($con, "SELECT wa_attendance 
                                       FROM work_attendance 
                                       WHERE wa_student = '$SecondFilterValue' 
                                         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) {
                $totalPresent++;
                $totalReceived += $work["wl_amount_by_hotel"];
                $totalDispatched += $work["wl_amount_to_student"];
            } else {
                $totalAbsent++;
            }
        } else {
            $totalAbsent++;
        }
    }
    ?>
<div class="summary-block mb-3 p-3 border rounded bg-light">
    <div class="row">
        <div class="col-md-3"><b>Total Works:</b> <?= $totalWorks; ?></div>
        <div class="col-md-3 col-6"><b>Present:</b> <?= $totalPresent; ?></div>
        <div class="col-md-3 col-6"><b>Absent:</b> <?= $totalAbsent; ?></div>
        <div class="col-md-3"><b>Total Earned:</b> <?= $totalDispatched; ?>/-</div>
    </div>
</div>
<?php

    // -------------------
    // PAGINATED LIST
    // -------------------
    $sql = "
        SELECT wl.*, wp.wp_name
        FROM work_student ws
        INNER JOIN work_list wl ON ws.ws_workId = wl.wl_id
        INNER JOIN work_place wp ON wl.wl_vendor_id = wp.wp_id
        $AndWhere
        ORDER BY wl.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 {
        while ($rows = mysqli_fetch_assoc($res)) {
            $vendor = $rows["wp_name"];
            $displayTime = date("g:i A", strtotime($rows["wl_time"]));

            // check this student's attendance
            $att_sql = mysqli_query($con, "SELECT wa_attendance FROM work_attendance 
                                           WHERE wa_student = '$SecondFilterValue' 
                                             AND wa_vendorId = '{$rows["wl_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;

            $statusText = $attendance == 1 ? "Present" : "Absent";
            $badgeClass = $attendance == 1 ? "success" : "danger";
            ?>
<li class='clearfix' id="work<?= $rows["wl_id"]?>">
    <div class="single-dis-admin mb-2">
        <div class='row align-items-center'>
            <div class='col-md-4'>
                <div class="intro-admin">
                    <a style='color:orange;font-size:17px;' class='viewDetails' data-toggle='modal'
                        data-target='#adminDetailsModal' data-name='<?= $vendor; ?>'
                        data-title='<?= $rows["wl_title"]; ?>' data-startdate='<?= $rows["wl_date"]; ?>'
                        data-time='<?= $displayTime; ?>' data-hotelamount='<?= $rows["wl_amount_by_hotel"]; ?>'
                        data-studentamount='<?= $rows["wl_amount_to_student"]; ?>'
                        data-totalreceived='<?= ($attendance==1 ? $rows["wl_amount_by_hotel"] : 0); ?>'
                        data-totaldispatched='<?= ($attendance==1 ? $rows["wl_amount_to_student"] : 0); ?>'
                        data-date='<?= $rows["wl_cDate"]; ?>' data-present='<?= ($attendance==1 ? 1 : 0); ?>'
                        data-absent='<?= ($attendance==1 ? 0 : 1); ?>'
                        data-students='<?= json_encode([["name"=>$SecondFilterValue,"attendance"=>$attendance]]); ?>'>
                        <i class="fa fa-calculator"></i>
                        <b><?= $vendor;?></b> <br class="d-none">
                        <b><?= '( ' . $rows["wl_title"] . ' )';?></b>
                    </a>
                </div>
            </div>
            <div class='col-md-4 col-6'>
                <span>Status: <span class="badge bg-<?= $badgeClass; ?>"><?= $statusText; ?></span></span>
            </div>
            <div class='col-md-4 col-6'>
                <span>Paid Amt: <?= ($attendance==1 ? $rows["wl_amount_to_student"] : 0); ?>/-</span>
            </div>
        </div>
    </div>
</li>
<?php
        }
        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>