<?php
session_start();
if (!isset($_SESSION['gym_id'])) {
    header("Location: login.php");
    exit();
}

require_once 'config/database.php';
$db = (new Database())->getConnection();
$gym_id = $_SESSION['gym_id'];

// MARKED BY MUST BE STAFF ID (NOT GYM ID)
$marked_by = isset($_SESSION['staff_id']) ? $_SESSION['staff_id'] : null;


// ============================
// 1) MARK SINGLE ATTENDANCE
// ============================
if ($_POST && isset($_POST['mark_attendance'])) {

    $member_id = $_POST['member_id'];
    $attendance_date = $_POST['attendance_date'];
    $check_in = $_POST['check_in'];
    $check_out = $_POST['check_out'] ?? null;
    $status = $_POST['status'];
    $notes = trim($_POST['notes']);

    // Check if record already exists
    $check_sql = "SELECT ma.id 
                  FROM member_attendance ma 
                  JOIN members m ON ma.member_id = m.id
                  WHERE ma.member_id = ? AND ma.attendance_date = ? AND m.gym_id = ?";
    $stmt = $db->prepare($check_sql);
    $stmt->execute([$member_id, $attendance_date, $gym_id]);

    if ($stmt->rowCount() > 0) {

        // UPDATE
        $sql = "UPDATE member_attendance ma
                JOIN members m ON ma.member_id = m.id
                SET ma.check_in = ?, ma.check_out = ?, ma.status = ?, ma.notes = ?, ma.marked_by = ?
                WHERE ma.member_id = ? AND ma.attendance_date = ? AND m.gym_id = ?";
        $stmt = $db->prepare($sql);
        $result = $stmt->execute([$check_in, $check_out, $status, $notes, $marked_by, $member_id, $attendance_date, $gym_id]);

    } else {

        // INSERT
        $sql = "INSERT INTO member_attendance (member_id, attendance_date, check_in, check_out, status, notes, marked_by)
                SELECT ?,?,?,?,?,?,?
                FROM members WHERE id = ? AND gym_id = ?";
        $stmt = $db->prepare($sql);
        $result = $stmt->execute([$member_id, $attendance_date, $check_in, $check_out, $status, $notes, $marked_by, $member_id, $gym_id]);
    }

    echo json_encode([
        'success' => $result,
        'message' => $result ? 'Member attendance marked successfully!' : 'Failed to mark attendance!'
    ]);
    exit();
}



// ============================
// 2) BULK ATTENDANCE
// ============================
if ($_POST && isset($_POST['bulk_attendance'])) {

    $attendance_date = $_POST['attendance_date'];
    $success_count = 0;
    $error_count = 0;

    foreach ($_POST['attendance'] as $member_id => $data) {

        $status = $data['status'];
        $check_in = $data['check_in'];
        $check_out = $data['check_out'] ?? null;
        $notes = trim($data['notes']);

        // Check if record exists
        $check_sql = "SELECT ma.id 
                      FROM member_attendance ma 
                      JOIN members m ON ma.member_id = m.id
                      WHERE ma.member_id = ? AND ma.attendance_date = ? AND m.gym_id = ?";
        $stmt = $db->prepare($check_sql);
        $stmt->execute([$member_id, $attendance_date, $gym_id]);

        if ($stmt->rowCount() > 0) {

            // UPDATE
            $sql = "UPDATE member_attendance ma
                    JOIN members m ON ma.member_id = m.id
                    SET ma.check_in = ?, ma.check_out = ?, ma.status = ?, ma.notes = ?, ma.marked_by = ?
                    WHERE ma.member_id = ? AND ma.attendance_date = ? AND m.gym_id = ?";
            $stmt = $db->prepare($sql);
            $result = $stmt->execute([$check_in, $check_out, $status, $notes, $marked_by, $member_id, $attendance_date, $gym_id]);

        } else {

            // INSERT
            $sql = "INSERT INTO member_attendance (member_id, attendance_date, check_in, check_out, status, notes, marked_by)
                    SELECT ?,?,?,?,?,?,?
                    FROM members WHERE id = ? AND gym_id = ?";
            $stmt = $db->prepare($sql);
            $result = $stmt->execute([$member_id, $attendance_date, $check_in, $check_out, $status, $notes, $marked_by, $member_id, $gym_id]);
        }

        if ($result) $success_count++;
        else $error_count++;
    }

    echo json_encode([
        'success' => true,
        'message' => "Attendance marked for {$success_count} members" . ($error_count > 0 ? " ({$error_count} failed)" : "")
    ]);
    exit();
}



// ============================
// 3) FETCH DATA
// ============================

// Active Members (only current gym)
$members_stmt = $db->prepare("SELECT id, member_id, name, membership_type, status 
                              FROM members 
                              WHERE status='active' AND gym_id=? 
                              ORDER BY name");
$members_stmt->execute([$gym_id]);
$members = $members_stmt->fetchAll(PDO::FETCH_ASSOC);

// Today
$today = date('Y-m-d');

// Today attendance
$attendance_stmt = $db->prepare("SELECT ma.*, m.name AS member_name, m.member_id AS member_code, m.membership_type
                                 FROM member_attendance ma
                                 JOIN members m ON ma.member_id = m.id
                                 WHERE ma.attendance_date = ? AND m.gym_id = ?
                                 ORDER BY m.name");
$attendance_stmt->execute([$today, $gym_id]);
$today_attendance = $attendance_stmt->fetchAll(PDO::FETCH_ASSOC);

// Last 30 days
$history_stmt = $db->prepare("SELECT ma.*, m.name AS member_name, m.member_id AS member_code, m.membership_type
                              FROM member_attendance ma
                              JOIN members m ON ma.member_id = m.id
                              WHERE ma.attendance_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY)
                              AND m.gym_id = ?
                              ORDER BY ma.attendance_date DESC, m.name");
$history_stmt->execute([$gym_id]);
$attendance_history = $history_stmt->fetchAll(PDO::FETCH_ASSOC);

// Lookup
$attendance_lookup = [];
foreach ($today_attendance as $record) {
    $attendance_lookup[$record['member_id']] = $record;
}
?>


<?php include 'includes/header.php'; ?>
<?php include 'includes/sidebar.php'; ?>
<?php include 'includes/navbar.php'; ?>

<!-- Include SweetAlert -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.all.min.js"></script>

<div class="main-panel">
    <div class="content-wrapper">
        <div class="page-header">
            <h3 class="page-title">Member Attendance Management</h3>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                    <li class="breadcrumb-item active" aria-current="page">Member Attendance</li>
                </ol>
            </nav>
        </div>

        <!-- Quick Stats -->
        <div class="row">
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="card-title"><?php echo count($members); ?></h4>
                                <p class="card-category">Active Members</p>
                            </div>
                            <div class="icon-big text-center">
                                <i class="mdi mdi-account-multiple text-primary"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="card-title"><?php echo count($today_attendance); ?></h4>
                                <p class="card-category">Marked Today</p>
                            </div>
                            <div class="icon-big text-center">
                                <i class="mdi mdi-calendar-check text-success"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="card-title"><?php echo date('M d, Y'); ?></h4>
                                <p class="card-category">Today's Date</p>
                            </div>
                            <div class="icon-big text-center">
                                <i class="mdi mdi-calendar text-info"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="card card-stats">
                    <div class="card-body">
                        <div class="d-flex justify-content-between">
                            <div>
                                <h4 class="card-title">Reception</h4>
                                <p class="card-category">Marked By</p>
                            </div>
                            <div class="icon-big text-center">
                                <i class="mdi mdi-account-tie text-warning"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Bulk Attendance Form -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">Mark Member Attendance - <?php echo date('M d, Y'); ?></h4>
                        <p class="text-muted">Mark attendance for all active members at once</p>
                        
                        <form id="bulkAttendanceForm">
                            <input type="hidden" name="attendance_date" value="<?php echo $today; ?>">
                            
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Member ID</th>
                                            <th>Name</th>
                                            <th>Membership</th>
                                            <th>Check In</th>
                                            <th>Check Out</th>
                                            <th>Status</th>
                                            <th>Notes</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($members as $member): 
                                            $attendance = $attendance_lookup[$member['id']] ?? null;
                                        ?>
                                        <tr>
                                            <td>
                                                <span class="fw-bold text-primary"><?php echo $member['member_id']; ?></span>
                                            </td>
                                            <td>
                                                <div class="d-flex align-items-center">
                                                    <i class="mdi mdi-account" style="font-size:24px; color:#7a7a7a;"></i>
                                                    <div class="ms-3">
                                                        <div class="fw-semibold"><?php echo htmlspecialchars($member['name']); ?></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge badge-<?php 
                                                    echo $member['membership_type'] == 'vip' ? 'danger' : 
                                                        ($member['membership_type'] == 'premium' ? 'warning' : 
                                                        ($member['membership_type'] == 'basic' ? 'info' : 'success')); 
                                                ?>">
                                                    <?php echo ucfirst($member['membership_type']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <input type="time" class="form-control form-control-sm" 
                                                       name="attendance[<?php echo $member['id']; ?>][check_in]" 
                                                       value="<?php echo $attendance['check_in'] ?? date('H:i'); ?>">
                                            </td>
                                            <td>
                                                <input type="time" class="form-control form-control-sm" 
                                                       name="attendance[<?php echo $member['id']; ?>][check_out]" 
                                                       value="<?php echo $attendance['check_out'] ?? ''; ?>">
                                            </td>
                                            <td>
                                                <select class="form-control form-control-sm" 
                                                        name="attendance[<?php echo $member['id']; ?>][status]">
                                                    <option value="present" <?php echo ($attendance['status'] ?? 'present') == 'present' ? 'selected' : ''; ?>>Present</option>
                                                    <option value="absent" <?php echo ($attendance['status'] ?? '') == 'absent' ? 'selected' : ''; ?>>Absent</option>
                                                </select>
                                            </td>
                                            <td>
                                                <input type="text" class="form-control form-control-sm" 
                                                       name="attendance[<?php echo $member['id']; ?>][notes]" 
                                                       placeholder="Notes..." 
                                                       value="<?php echo $attendance['notes'] ?? ''; ?>">
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-primary btn-sm mark-single-btn" 
                                                        data-member-id="<?php echo $member['id']; ?>"
                                                        data-member-name="<?php echo htmlspecialchars($member['name']); ?>"
                                                        data-member-code="<?php echo $member['member_id']; ?>">
                                                    <i class="mdi mdi-check"></i> Mark
                                                </button>
                                                <button type="button" class="btn btn-info btn-sm view-history-btn mt-1"
                                                        data-member-id="<?php echo $member['id']; ?>"
                                                        data-member-name="<?php echo htmlspecialchars($member['name']); ?>">
                                                    <i class="mdi mdi-history"></i> History
                                                </button>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                            
                            <div class="mt-3">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="mdi mdi-content-save-all"></i> Save All Attendance
                                </button>
                                <button type="button" class="btn btn-info btn-lg" onclick="markAllPresent()">
                                    <i class="mdi mdi-account-check"></i> Mark All Present
                                </button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <!-- Today's Attendance Summary -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center">
                            <h4 class="card-title">Today's Attendance Summary</h4>
                            <button class="btn btn-outline-primary" onclick="viewFullHistory()">
                                <i class="mdi mdi-history"></i> View Full History
                            </button>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Member ID</th>
                                        <th>Name</th>
                                        <th>Membership</th>
                                        <th>Check In</th>
                                        <th>Check Out</th>
                                        <th>Status</th>
                                        <th>Notes</th>
                                        <th>Marked At</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($today_attendance as $record): ?>
                                    <tr>
                                        <td><?php echo $record['member_code']; ?></td>
                                        <td><?php echo htmlspecialchars($record['member_name']); ?></td>
                                        <td>
                                            <span class="badge badge-<?php 
                                                echo $record['membership_type'] == 'vip' ? 'danger' : 
                                                    ($record['membership_type'] == 'premium' ? 'warning' : 
                                                    ($record['membership_type'] == 'basic' ? 'info' : 'success')); 
                                            ?>">
                                                <?php echo ucfirst($record['membership_type']); ?>
                                            </span>
                                        </td>
                                        <td><?php echo $record['check_in'] ?: '--'; ?></td>
                                        <td><?php echo $record['check_out'] ?: '--'; ?></td>
                                        <td>
                                            <label class="badge badge-<?php echo $record['status'] == 'present' ? 'success' : 'danger'; ?>">
                                                <?php echo ucfirst($record['status']); ?>
                                            </label>
                                        </td>
                                        <td><?php echo $record['notes'] ?: '--'; ?></td>
                                        <td><?php echo date('h:i A', strtotime($record['created_at'])); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($today_attendance)): ?>
                                    <tr>
                                        <td colspan="8" class="text-center text-muted py-4">
                                            <i class="mdi mdi-calendar-blank display-4 d-block mb-2"></i>
                                            No attendance marked for today.
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Attendance History -->
        <div class="row mt-4">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">Attendance History (Last 30 Days)</h4>
                        
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Date</th>
                                        <th>Member ID</th>
                                        <th>Name</th>
                                        <th>Check In</th>
                                        <th>Check Out</th>
                                        <th>Status</th>
                                        <th>Notes</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($attendance_history as $record): ?>
                                    <tr>
                                        <td>
                                            <?php echo date('M d, Y', strtotime($record['attendance_date'])); ?>
                                            <br>
                                            <small class="text-muted"><?php echo date('D', strtotime($record['attendance_date'])); ?></small>
                                        </td>
                                        <td><?php echo $record['member_code']; ?></td>
                                        <td><?php echo htmlspecialchars($record['member_name']); ?></td>
                                        <td><?php echo $record['check_in'] ?: '--'; ?></td>
                                        <td><?php echo $record['check_out'] ?: '--'; ?></td>
                                        <td>
                                            <label class="badge badge-<?php echo $record['status'] == 'present' ? 'success' : 'danger'; ?>">
                                                <?php echo ucfirst($record['status']); ?>
                                            </label>
                                        </td>
                                        <td><?php echo $record['notes'] ?: '--'; ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                    
                                    <?php if (empty($attendance_history)): ?>
                                    <tr>
                                        <td colspan="7" class="text-center text-muted py-4">
                                            <i class="mdi mdi-history display-4 d-block mb-2"></i>
                                            No attendance history found.
                                        </td>
                                    </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php include 'includes/footer.php'; ?>
</div>

<!-- Single Attendance Modal -->
<div class="modal fade" id="singleAttendanceModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Mark Member Attendance</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="singleAttendanceForm">
                    <input type="hidden" id="single_member_id" name="member_id">
                    <input type="hidden" name="attendance_date" value="<?php echo $today; ?>">
                    
                    <div class="form-group">
                        <label class="form-label">Member ID</label>
                        <input type="text" class="form-control" id="single_member_code" readonly>
                    </div>
                    
                    <div class="form-group">
                        <label class="form-label">Member Name</label>
                        <input type="text" class="form-control" id="single_member_name" readonly>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="single_check_in" class="form-label">Check In Time</label>
                                <input type="time" class="form-control" id="single_check_in" name="check_in" value="<?php echo date('H:i'); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label for="single_check_out" class="form-label">Check Out Time</label>
                                <input type="time" class="form-control" id="single_check_out" name="check_out">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label for="single_status" class="form-label">Status</label>
                        <select class="form-control" id="single_status" name="status">
                            <option value="present">Present</option>
                            <option value="absent">Absent</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label for="single_notes" class="form-label">Notes</label>
                        <textarea class="form-control" id="single_notes" name="notes" rows="2" placeholder="Any notes..."></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="submitSingleAttendance()">Mark Attendance</button>
            </div>
        </div>
    </div>
</div>

<!-- Member History Modal -->
<div class="modal fade" id="memberHistoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Attendance History - <span id="history_member_name"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="memberHistoryContent">
                    <!-- History will be loaded here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script>
    // SweetAlert configuration
    const Toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer)
            toast.addEventListener('mouseleave', Swal.resumeTimer)
        }
    });

    // Bulk Attendance Form Submission
    document.getElementById('bulkAttendanceForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        Swal.fire({
            title: 'Save All Attendance?',
            text: 'This will save attendance for all members',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, save all!',
            cancelButtonText: 'Cancel'
        }).then((result) => {
            if (result.isConfirmed) {
                const formData = new FormData(this);
                formData.append('bulk_attendance', 'true');
                
                fetch('member_attendance.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        Toast.fire({
                            icon: 'success',
                            title: data.message
                        });
                        setTimeout(() => location.reload(), 1000);
                    } else {
                        Swal.fire('Error!', data.message, 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Error!', 'An error occurred while saving attendance', 'error');
                });
            }
        });
    });

    // Single Attendance Marking
    document.querySelectorAll('.mark-single-btn').forEach(button => {
        button.addEventListener('click', function() {
            const memberId = this.getAttribute('data-member-id');
            const memberName = this.getAttribute('data-member-name');
            const memberCode = this.getAttribute('data-member-code');
            
            document.getElementById('single_member_id').value = memberId;
            document.getElementById('single_member_name').value = memberName;
            document.getElementById('single_member_code').value = memberCode;
            
            // Set current time
            const now = new Date();
            const timeString = now.toTimeString().split(' ')[0].substring(0, 5);
            document.getElementById('single_check_in').value = timeString;
            
            const modal = new bootstrap.Modal(document.getElementById('singleAttendanceModal'));
            modal.show();
        });
    });

    // View Member History
    document.querySelectorAll('.view-history-btn').forEach(button => {
        button.addEventListener('click', function() {
            const memberId = this.getAttribute('data-member-id');
            const memberName = this.getAttribute('data-member-name');
            
            document.getElementById('history_member_name').textContent = memberName;
            
            // Load member history via AJAX
            fetch(`get_member_history.php?member_id=${memberId}`)
                .then(response => response.text())
                .then(html => {
                    document.getElementById('memberHistoryContent').innerHTML = html;
                    const modal = new bootstrap.Modal(document.getElementById('memberHistoryModal'));
                    modal.show();
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Error!', 'Failed to load member history', 'error');
                });
        });
    });

    // Submit Single Attendance
    function submitSingleAttendance() {
        const formData = new FormData(document.getElementById('singleAttendanceForm'));
        formData.append('mark_attendance', 'true');
        
        fetch('member_attendance.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Toast.fire({
                    icon: 'success',
                    title: data.message
                });
                bootstrap.Modal.getInstance(document.getElementById('singleAttendanceModal')).hide();
                setTimeout(() => location.reload(), 1000);
            } else {
                Swal.fire('Error!', data.message, 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire('Error!', 'An error occurred while marking attendance', 'error');
        });
    }

    // Mark All Present
    function markAllPresent() {
        document.querySelectorAll('select[name*="[status]"]').forEach(select => {
            select.value = 'present';
        });
        
        document.querySelectorAll('input[name*="[check_in]"]').forEach(input => {
            if (!input.value) {
                const now = new Date();
                input.value = now.toTimeString().split(' ')[0].substring(0, 5);
            }
        });
        
        Toast.fire({
            icon: 'info',
            title: 'All members marked as Present with current time!'
        });
    }


    // View Full History
    function viewFullHistory() {
        document.querySelector('.row.mt-4:last-child').scrollIntoView({
            behavior: 'smooth'
        });
    }

    // Auto-set current time
    document.querySelectorAll('input[type="time"]').forEach(input => {
        input.addEventListener('focus', function() {
            if (!this.value) {
                const now = new Date();
                this.value = now.toTimeString().split(' ')[0].substring(0, 5);
            }
        });
    });

    // Auto-clear today's data at midnight
    function checkMidnightReset() {
        const now = new Date();
        const hours = now.getHours();
        const minutes = now.getMinutes();
        
        // If it's between 12:00 AM and 12:05 AM, suggest refresh
        if (hours === 0 && minutes <= 5) {
            Toast.fire({
                icon: 'info',
                title: 'New day started! Page will refresh to clear old data.'
            });
            setTimeout(() => location.reload(), 2000);
        }
    }

    // Check every minute
    setInterval(checkMidnightReset, 60000);
</script>