<?php
    // session_start();
    include "../db.php";
    require '../auth.php';
    restrictAccess(['master_admin']);
    date_default_timezone_set('Asia/Kolkata');
    $currentTime = date('M j, Y g:i a');

    if ( !isset($_SESSION['uid']) && !isset($_SESSION['uref']) && !isset($_SESSION['utype']) ) {
        header("Location: logout.php");
        exit();
    }

    if ( $_SESSION['utype'] != 'master_admin' && $_SESSION['uref'] != 'fssdf4543frts' ) {
        header("Location: logout.php");
        exit();
    }

    $vendor = "";
    if(isset($_GET["vendor_id"])){
        $vendor_id = $_GET["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"];
        }
    }
?>

<!DOCTYPE html>
<html lang="en">

<head>
    <?php include "include/meta.php"; ?>
    <?php include "include/css.php"; ?>
    <?php include "include/php-functions.php"; ?>
    <script src="https://cdn.ckeditor.com/4.6.2/standard-all/ckeditor.js"></script>
</head>

<body>
    <!--  Header -->
    <?php include "include/header.php"; ?>
    <!-- #header -->

    <section id="inner-body">
        <div class="body-content">
            <div class="container-fluid">
                <?php
                // 1) Collect all distinct dates first
                $dates = [];
                $date_rs = mysqli_query($con, "
                    SELECT DISTINCT wa_date, wa_time
                    FROM work_attendance
                    WHERE wa_workId = '{$_GET['work_id']}'
                    AND wa_vendorId = '$vendor_id'
                    ORDER BY wa_date ASC
                ");

                while ($r = mysqli_fetch_assoc($date_rs)) {
                    $dates[] = [
                        'date' => $r['wa_date'],
                        'time' => $r['wa_time']
                    ];
                }

                if (!empty($dates)) {
                    $today    = date('Y-m-d');
                    $hasToday = in_array($today, array_column($dates, 'date'), true);
                    ?>
                <div class="accordion my-3" id="attendanceAccordion">
                    <?php foreach ($dates as $idx => $dt): 
                            $wa_date = $dt['date'];
                            $wa_time = $dt['time'];
                            $formatted_time = !empty($wa_time) ? date("h:i A", strtotime($wa_time)) : "";       
                                            
                            $isToday   = ($wa_date === $today);
                            // 2) If today exists, open today's panel; otherwise open the first
                            $isOpen    = $hasToday ? $isToday : ($idx === 0);
                            $showClass = $isOpen ? 'show' : '';
                            $collapsed = $isOpen ? '' : 'collapsed';
                            $ariaExp   = $isOpen ? 'true' : 'false';
                            $accId     = 'acc'.($idx+1);
                        ?>
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="heading-<?php echo $accId; ?>">
                            <button class="accordion-button <?php echo $collapsed; ?>" type="button"
                                data-bs-toggle="collapse" data-bs-target="#collapse-<?php echo $accId; ?>"
                                aria-expanded="<?php echo $ariaExp; ?>" aria-controls="collapse-<?php echo $accId; ?>">
                                Attendance on <?php echo htmlspecialchars($wa_date); ?>
                                <?php if ($formatted_time): ?>
                                <span class="ms-2 text-muted">(<?php echo $formatted_time; ?>)</span>
                                <?php endif; ?>
                                <?php if ($isToday): ?>
                                <span class="badge bg-info ms-2">Today</span>
                                <?php endif; ?>
                            </button>
                        </h2>
                        <div id="collapse-<?php echo $accId; ?>"
                            class="accordion-collapse collapse <?php echo $showClass; ?>"
                            aria-labelledby="heading-<?php echo $accId; ?>" data-bs-parent="#attendanceAccordion">
                            <div class="accordion-body">
                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead>
                                            <tr>
                                                <th>Student</th>
                                                <th>Email</th>
                                                <th>Mobile</th>
                                                <th>Status</th>
                                                <th>Attendance</th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            <?php
                                            // 3) List students for this date
                                            $att_q = mysqli_query($con, "
                                                SELECT wa.wa_id, wa.wa_attendance, ws.ws_student
                                                FROM work_attendance wa
                                                JOIN work_student ws ON ws.ws_id = wa.wa_wsId
                                                JOIN users u ON u.uid = ws.ws_student
                                                WHERE wa.wa_date   = '$wa_date'
                                                AND wa.wa_workId = '{$_GET['work_id']}'
                                                AND wa.wa_vendorId = '$vendor_id'
                                                ORDER BY u.uname ASC
                                            ");

                                            while ($att = mysqli_fetch_assoc($att_q)) {
                                                $wa_id      = $att['wa_id'];
                                                $status     = (int)$att['wa_attendance'];
                                                $student_id = $att['ws_student'];

                                                $stu_q = mysqli_query($con, "SELECT uname, uemail, ucontact FROM users WHERE uid='$student_id'");
                                                $stu   = mysqli_fetch_assoc($stu_q);

                                                $statusText = $status === 1 ? 'Present' : 'Absent';
                                                $badgeClass = $status === 1 ? 'badge bg-success' : 'badge bg-danger';
                                                ?>
                                            <tr>
                                                <td><?php echo htmlspecialchars($stu['uname']); ?></td>
                                                <td><?php echo htmlspecialchars($stu['uemail']); ?></td>
                                                <td><?php echo htmlspecialchars($stu['ucontact']); ?></td>
                                                <td><span
                                                        class="<?php echo $badgeClass; ?>"><?php echo $statusText; ?></span>
                                                </td>
                                                <td>
                                                    <button class="btn btn-sm btn-warning toggleAttendance text-white"
                                                        data-waid="<?php echo $wa_id; ?>"
                                                        data-current="<?php echo $status; ?>">
                                                        <?php echo $status == 1 ? "Mark Absent" : "Mark Present"; ?>
                                                    </button>
                                                </td>
                                            </tr>
                                            <?php } ?>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
                <?php } else{?>
                <div class="card mt-3 mb-3">
                    <p>Add Student to give attendance.</p>
                </div>
                <?php }?>
            </div>
        </div>

        <?php include "include/footer.php"; ?>
    </section>

    <!-- JavaScript Libraries -->

    <?php include "include/js.php"; ?>

    <script>
    $(document).on("click", ".toggleAttendance", function() {
        var btn = $(this);
        var wa_id = btn.data("waid");
        var current = btn.data("current");

        $.ajax({
            url: "work-student-attendance-ajax.php",
            type: "POST",
            data: {
                wa_id: wa_id,
                current: current
            },
            success: function(res) {
                try {
                    var data = JSON.parse(res);
                    if (data.success) {
                        var row = btn.closest("tr");
                        var badge = row.find("td:eq(3) span"); // ✅ 4th column = Status

                        if (data.newStatus == 1) {
                            badge.removeClass("bg-danger").addClass("bg-success").text("Present");
                            btn.text("Mark Absent"); // ✅ Update button text
                        } else {
                            badge.removeClass("bg-success").addClass("bg-danger").text("Absent");
                            btn.text("Mark Present"); // ✅ Update button text
                        }

                        // update button current value
                        btn.data("current", data.newStatus);
                    } else {
                        alert("Failed to update attendance.");
                    }
                } catch (e) {
                    console.error(e, res);
                    alert("Invalid response!");
                }
            }
        });
    });
    </script>


</body>

</html>