<?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'];

// Current gym کا data fetch کریں sidebar کے لیے
$gym_stmt = $db->prepare("SELECT name, owner_name FROM gyms WHERE id = ?");
$gym_stmt->execute([$gym_id]);
$current_gym = $gym_stmt->fetch(PDO::FETCH_ASSOC);

// Mark attendance - FIXED ENUM VALUES
if ($_POST && isset($_POST['mark_attendance'])) {

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

    // FIXED: marked_by must be a valid staff_id OR NULL
    $marked_by = isset($_SESSION['staff_id']) ? $_SESSION['staff_id'] : null;

    // Validate status
    $allowed = ['present', 'absent', 'late'];
    if (!in_array($status, $allowed)) {
        $status = 'present';
    }

    try {

        // Check existing
        $stmt = $db->prepare("SELECT id FROM staff_attendance WHERE staff_id=? AND attendance_date=? AND gym_id=?");
        $stmt->execute([$staff_id, $attendance_date, $gym_id]);

        if ($stmt->rowCount() > 0) {
            // Update
            $query = "UPDATE staff_attendance 
                      SET check_in=?, check_out=?, status=?, notes=?, marked_by=?
                      WHERE staff_id=? AND attendance_date=? AND gym_id=?";
            $stmt = $db->prepare($query);
            $result = $stmt->execute([$check_in, $check_out, $status, $notes, $marked_by, $staff_id, $attendance_date, $gym_id]);

        } else {
            // Insert
            $query = "INSERT INTO staff_attendance 
                      (gym_id, staff_id, attendance_date, check_in, check_out, status, notes, marked_by) 
                      VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $db->prepare($query);
            $result = $stmt->execute([$gym_id, $staff_id, $attendance_date, $check_in, $check_out, $status, $notes, $marked_by]);
        }

        if ($result) {
            echo json_encode(['success' => true, 'message' => 'Attendance marked successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Insert failed']);
        }

        exit();

    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit();
    }
}


if ($_POST && isset($_POST['bulk_attendance'])) {
    $attendance_date = $_POST['attendance_date'];

    // FIXED: marked_by must reference staff.id or be NULL
    $marked_by = isset($_SESSION['staff_id']) ? $_SESSION['staff_id'] : null;

    $success_count = 0;
    $error_count = 0;
    $errors = [];

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

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

            $allowed = ['present', 'absent', 'late'];
            if (!in_array($status, $allowed)) {
                $status = 'present';
            }

            // Check if already exists
            $stmt = $db->prepare("SELECT id FROM staff_attendance WHERE staff_id=? AND attendance_date=? AND gym_id=?");
            $stmt->execute([$staff_id, $attendance_date, $gym_id]);

            if ($stmt->rowCount() > 0) {
                // UPDATE
                $query = "UPDATE staff_attendance 
                          SET check_in=?, check_out=?, status=?, notes=?, marked_by=? 
                          WHERE staff_id=? AND attendance_date=? AND gym_id=?";
                $stmt = $db->prepare($query);
                $result = $stmt->execute([$check_in, $check_out, $status, $notes, $marked_by, $staff_id, $attendance_date, $gym_id]);

            } else {
                // INSERT
                $query = "INSERT INTO staff_attendance 
                          (gym_id, staff_id, attendance_date, check_in, check_out, status, notes, marked_by)
                          VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt = $db->prepare($query);
                $result = $stmt->execute([$gym_id, $staff_id, $attendance_date, $check_in, $check_out, $status, $notes, $marked_by]);
            }

            if ($result) {
                $success_count++;
            } else {
                $error_count++;
                $errors[] = "Staff ID {$staff_id} failed: " . $stmt->errorInfo()[2];
            }
        }

        echo json_encode([
            'success' => $error_count === 0,
            'message' => "Attendance saved: {$success_count} success, {$error_count} failed",
            'errors' => $errors
        ]);
        exit();

    } catch (PDOException $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
        exit();
    }
}

// Get all staff members - ONLY FROM CURRENT GYM
$staff_query = "SELECT id, name, role FROM staff WHERE gym_id = ? AND status = 'active' AND role != 'receptionist' ORDER BY name";
$staff_stmt = $db->prepare($staff_query);
$staff_stmt->execute([$gym_id]);
$staff_members = $staff_stmt->fetchAll(PDO::FETCH_ASSOC);

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

// Get today's attendance for all staff - ONLY FROM CURRENT GYM
$attendance_query = "SELECT sa.*, s.name as staff_name, s.role as staff_role 
                     FROM staff_attendance sa 
                     JOIN staff s ON sa.staff_id = s.id 
                     WHERE sa.attendance_date = ? AND s.gym_id = ?
                     ORDER BY s.name";
$attendance_stmt = $db->prepare($attendance_query);
$attendance_stmt->execute([$today, $gym_id]);
$today_attendance = $attendance_stmt->fetchAll(PDO::FETCH_ASSOC);

// Get attendance history (last 30 days) - ONLY FROM CURRENT GYM
$history_query = "SELECT sa.*, s.name as staff_name, s.role as staff_role 
                  FROM staff_attendance sa 
                  JOIN staff s ON sa.staff_id = s.id 
                  WHERE sa.attendance_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND s.gym_id = ?
                  ORDER BY sa.attendance_date DESC, s.name";
$history_stmt = $db->prepare($history_query);
$history_stmt->execute([$gym_id]);
$attendance_history = $history_stmt->fetchAll(PDO::FETCH_ASSOC);

// Create a quick lookup array for today's attendance
$attendance_lookup = [];
foreach ($today_attendance as $record) {
    $attendance_lookup[$record['staff_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">Staff 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">Staff 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($staff_members); ?></h4>
                                <p class="card-category">Total Staff</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 Staff Attendance - <?php echo date('M d, Y'); ?></h4>
                        <p class="text-muted">Mark attendance for all staff 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>Staff Name</th>
                                            <th>Role</th>
                                            <th>Check In</th>
                                            <th>Check Out</th>
                                            <th>Status</th>
                                            <th>Notes</th>
                                            <th>Action</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($staff_members as $staff): 
                                            $attendance = $attendance_lookup[$staff['id']] ?? null;
                                        ?>
                                        <tr>
                                            <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($staff['name']); ?></div>
                                                    </div>
                                                </div>
                                            </td>
                                            <td>
                                                <span class="badge badge-info"><?php echo ucfirst(str_replace('_', ' ', $staff['role'])); ?></span>
                                            </td>
                                            <td>
                                                <input type="time" class="form-control form-control-sm" 
                                                       name="attendance[<?php echo $staff['id']; ?>][check_in]" 
                                                       value="<?php echo $attendance['check_in'] ?? '09:00'; ?>">
                                            </td>
                                            <td>
                                                <input type="time" class="form-control form-control-sm" 
                                                       name="attendance[<?php echo $staff['id']; ?>][check_out]" 
                                                       value="<?php echo $attendance['check_out'] ?? '17:00'; ?>">
                                            </td>
                                            <td>
                                                <select class="form-control form-control-sm" 
                                                        name="attendance[<?php echo $staff['id']; ?>][status]">
                                                    <option value="present" <?php echo ($attendance['status'] ?? 'present') == 'present' ? 'selected' : ''; ?>>Present</option>
                                                    <option value="late" <?php echo ($attendance['status'] ?? '') == 'late' ? 'selected' : ''; ?>>Late</option>
                                                    <option value="half_day" <?php echo ($attendance['status'] ?? '') == 'half_day' ? 'selected' : ''; ?>>Half Day</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 $staff['id']; ?>][notes]" 
                                                       placeholder="Notes..." 
                                                       value="<?php echo $attendance['notes'] ?? ''; ?>">
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-primary btn-sm mark-single-btn" 
                                                        data-staff-id="<?php echo $staff['id']; ?>"
                                                        data-staff-name="<?php echo htmlspecialchars($staff['name']); ?>">
                                                    <i class="mdi mdi-check"></i> Mark
                                                </button>
                                                <button type="button" class="btn btn-info btn-sm view-history-btn mt-1"
                                                        data-staff-id="<?php echo $staff['id']; ?>"
                                                        data-staff-name="<?php echo htmlspecialchars($staff['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>Staff Name</th>
                                        <th>Role</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 htmlspecialchars($record['staff_name']); ?></td>
                                        <td>
                                            <span class="badge badge-info"><?php echo ucfirst(str_replace('_', ' ', $record['staff_role'])); ?></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' : 
                                                    ($record['status'] == 'late' ? 'warning' : 
                                                    ($record['status'] == 'half_day' ? 'info' : '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="7" 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>Staff Name</th>
                                        <th>Role</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 htmlspecialchars($record['staff_name']); ?></td>
                                        <td>
                                            <span class="badge badge-info"><?php echo ucfirst(str_replace('_', ' ', $record['staff_role'])); ?></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' : 
                                                    ($record['status'] == 'late' ? 'warning' : 
                                                    ($record['status'] == 'half_day' ? 'info' : '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 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_staff_id" name="staff_id">
                    <input type="hidden" name="attendance_date" value="<?php echo $today; ?>">
                    
                    <div class="form-group">
                        <label class="form-label">Staff Member</label>
                        <input type="text" class="form-control" id="single_staff_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="late">Late</option>
                            <option value="half_day">Half Day</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>

<!-- Staff History Modal -->
<div class="modal fade" id="staffHistoryModal" 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_staff_name"></span></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="staffHistoryContent">
                    <!-- 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 staff 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('reception_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 staffId = this.getAttribute('data-staff-id');
            const staffName = this.getAttribute('data-staff-name');
            
            document.getElementById('single_staff_id').value = staffId;
            document.getElementById('single_staff_name').value = staffName;
            
            // 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 Staff History
    document.querySelectorAll('.view-history-btn').forEach(button => {
        button.addEventListener('click', function() {
            const staffId = this.getAttribute('data-staff-id');
            const staffName = this.getAttribute('data-staff-name');
            
            document.getElementById('history_staff_name').textContent = staffName;
            
            // Load staff history via AJAX
            fetch(`get_staff_history.php?staff_id=${staffId}`)
                .then(response => response.text())
                .then(html => {
                    document.getElementById('staffHistoryContent').innerHTML = html;
                    const modal = new bootstrap.Modal(document.getElementById('staffHistoryModal'));
                    modal.show();
                })
                .catch(error => {
                    console.error('Error:', error);
                    Swal.fire('Error!', 'Failed to load staff history', 'error');
                });
        });
    });

    // Submit Single Attendance
    function submitSingleAttendance() {
        const formData = new FormData(document.getElementById('singleAttendanceForm'));
        formData.append('mark_attendance', 'true');
        
        fetch('reception_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) input.value = '09:00';
        });
        
        document.querySelectorAll('input[name*="[check_out]"]').forEach(input => {
            if (!input.value) input.value = '17:00';
        });
        
        Toast.fire({
            icon: 'info',
            title: 'All staff members marked as Present with default timings!'
        });
    }

    // View Full History
    function viewFullHistory() {
        document.getElementById('attendance-history-section').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>
