<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    @hotelSettings
    <title>Attendance Record - {{ $hotelName ?? hotelName() }}</title>
    <style>
        :root {
            --primary-green: var(--primary-green, #2e7d32);
            --primary-green-light: var(--secondary-green, #4caf50);
            --primary-green-dark: var(--dark-green, #1b5e20);
            --secondary-green: var(--secondary-green, #81c784);
            --secondary-green-light: var(--light-green, #a5d6a7);
            --accent-green: var(--accent, #43a047);
            --light-green-bg: var(--gray-100, #f1f8e9);
            --medium-green-bg: var(--gray-200, #e8f5e9);
            --dark-text: var(--gray-800, #1b3c1f);
            --light-text: #f9fdfa;
            --border-green: var(--gray-300, #c8e6c9);
            --success-green: #66bb6a;
            --warning-amber: #ffb300;
            --danger-red: #e53935;
            --info-blue: #2196f3;
            --gray-light: var(--gray-100, #f5f5f5);
            --gray-medium: var(--gray-600, #bdbdbd);
            --shadow-light: 0 2px 8px rgba(46, 125, 50, 0.1);
            --shadow-medium: 0 4px 12px rgba(46, 125, 50, 0.15);
            --radius-sm: var(--border-radius, 6px);
            --radius-md: var(--border-radius, 10px);
            --radius-lg: var(--border-radius, 14px);
            --font-family: var(--font-family, 'Segoe UI', sans-serif);
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            color: #000000 !important;
        }

        body {
            background-color: var(--light-green-bg);
            color: var(--dark-text);
            line-height: 1.6;
        }

        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 24px;
        }

        /* Header Styles */
        .page-header {
            background: linear-gradient(135deg, var(--primary-green), var(--primary-green-dark));
            color: var(--light-text);
            padding: 28px 32px;
            border-radius: var(--radius-lg);
            margin-bottom: 32px;
            box-shadow: var(--shadow-medium);
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            align-items: center;
        }

        .header-content h1 {
            font-size: 2.4rem;
            font-weight: 700;
            margin-bottom: 8px;
            letter-spacing: 0.5px;
        }

        .header-content p {
            font-size: 1.1rem;
            opacity: 0.9;
            font-weight: 300;
        }

        .header-actions {
            display: flex;
            gap: 16px;
            margin-top: 16px;
            flex-wrap: wrap;
        }

        /* Button Styles */
        .btn {
            padding: 12px 24px;
            border-radius: var(--radius-sm);
            font-weight: 600;
            font-size: 0.95rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: none;
            text-decoration: none;
        }

        .btn-primary {
            background-color: var(--primary-green);
            color: white;
            box-shadow: 0 3px 5px rgba(46, 125, 50, 0.3);
        }

        .btn-primary:hover {
            background-color: var(--primary-green-dark);
            transform: translateY(-2px);
            box-shadow: 0 5px 8px rgba(46, 125, 50, 0.4);
        }

        .btn-outline-primary {
            background-color: transparent;
            color: var(--light-text);
            border: 2px solid rgba(255, 255, 255, 0.7);
        }

        .btn-outline-primary:hover {
            background-color: rgba(255, 255, 255, 0.1);
            border-color: white;
        }

        .btn-outline-secondary {
            background-color: transparent;
            color: var(--light-text);
            border: 2px solid rgba(255, 255, 255, 0.4);
        }

        .btn-outline-secondary:hover {
            background-color: rgba(255, 255, 255, 0.05);
            border-color: rgba(255, 255, 255, 0.7);
        }

        .btn-success {
            background-color: var(--success-green);
            color: white;
        }

        .btn-success:hover {
            background-color: var(--accent-green);
            transform: translateY(-2px);
        }

        .btn-danger {
            background-color: var(--danger-red);
            color: white;
        }

        .btn-danger:hover {
            background-color: #c62828;
            transform: translateY(-2px);
        }

        .btn-warning {
            background-color: var(--warning-amber);
            color: white;
        }

        .btn-warning:hover {
            background-color: #f57c00;
            transform: translateY(-2px);
        }

        .btn i {
            margin-right: 8px;
        }

        /* Alert Styles */
        .alert {
            padding: 18px 24px;
            border-radius: var(--radius-md);
            margin-bottom: 28px;
            display: flex;
            align-items: center;
            box-shadow: var(--shadow-light);
            animation: slideDown 0.3s ease;
        }

        @keyframes slideDown {
            from { opacity: 0; transform: translateY(-10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .alert-success {
            background-color: #e8f5e9;
            color: var(--primary-green-dark);
            border-left: 5px solid var(--success-green);
        }

        .alert-error {
            background-color: #ffebee;
            color: #c62828;
            border-left: 5px solid var(--danger-red);
        }

        .alert i {
            margin-right: 12px;
            font-size: 1.3rem;
        }

        .btn-close {
            background: none;
            border: none;
            font-size: 1.2rem;
            margin-left: auto;
            cursor: pointer;
            color: #888;
            padding: 0;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .btn-close:hover {
            color: #333;
        }

        /* Card Styles */
        .card {
            background-color: white;
            border-radius: var(--radius-lg);
            box-shadow: var(--shadow-light);
            margin-bottom: 32px;
            overflow: hidden;
            border: 1px solid var(--border-green);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .card:hover {
            box-shadow: var(--shadow-medium);
        }

        .card-header {
            background-color: var(--medium-green-bg);
            padding: 22px 28px;
            border-bottom: 1px solid var(--border-green);
        }

        .card-header h5 {
            color: var(--primary-green-dark);
            font-size: 1.4rem;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .card-header h5 i {
            margin-right: 12px;
            color: var(--primary-green);
        }

        .card-body {
            padding: 28px;
        }

        /* Form Styles */
        .form-label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: var(--dark-text);
        }

        .form-control, .form-select, .form-select-sm {
            width: 100%;
            padding: 12px 16px;
            border-radius: var(--radius-sm);
            border: 1px solid var(--border-green);
            background-color: white;
            color: var(--dark-text);
            font-size: 1rem;
            transition: all 0.2s ease;
        }

        .form-control:focus, .form-select:focus {
            outline: none;
            border-color: var(--primary-green-light);
            box-shadow: 0 0 0 3px rgba(76, 175, 80, 0.2);
        }

        .form-control-sm {
            padding: 8px 12px;
            font-size: 0.9rem;
        }

        .row {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 24px;
        }

        .col-md-2, .col-md-3, .col-md-4, .col-md-6 {
            padding: 0 12px;
        }

        .col-md-2 { width: 16.666%; }
        .col-md-3 { width: 25%; }
        .col-md-4 { width: 33.333%; }
        .col-md-6 { width: 50%; }

        /* Table Styles */
        .table-responsive {
            overflow-x: auto;
            border-radius: var(--radius-md);
            border: 1px solid var(--border-green);
            margin-top: 20px;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            min-width: 1000px;
        }

        .table thead {
            background-color: var(--medium-green-bg);
        }

        .table th {
            padding: 18px 16px;
            text-align: left;
            font-weight: 600;
            color: var(--primary-green-dark);
            border-bottom: 2px solid var(--border-green);
            white-space: nowrap;
        }

        .table tbody tr {
            border-bottom: 1px solid var(--border-green);
            transition: background-color 0.2s ease;
        }

        .table tbody tr:hover {
            background-color: var(--light-green-bg);
        }

        .table td {
            padding: 16px;
            vertical-align: middle;
        }

        /* Avatar Styles */
        .avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            background-color: var(--secondary-green);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            overflow: hidden;
            flex-shrink: 0;
        }

        .avatar-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .d-flex {
            display: flex;
            align-items: center;
        }

        .me-2 {
            margin-right: 8px;
        }

        /* Badge Styles */
        .department-badge {
            display: inline-block;
            padding: 6px 12px;
            background-color: var(--secondary-green-light);
            color: var(--primary-green-dark);
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.85rem;
            font-weight: 500;
        }

        .bg-light {
            background-color: var(--medium-green-bg);
            color: var(--primary-green-dark);
        }

        .bg-secondary {
            background-color: var(--gray-medium);
            color: white;
        }

        /* Status Specific Styles */
        .status-present {
            color: var(--primary-green);
            font-weight: 600;
        }

        .status-absent {
            color: var(--danger-red);
            font-weight: 600;
        }

        .status-late {
            color: var(--warning-amber);
            font-weight: 600;
        }

        .status-half_day {
            color: var(--info-blue);
            font-weight: 600;
        }

        .status-on_leave {
            color: #5d4037;
            font-weight: 600;
        }

        /* Loading Overlay */
        .loading-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 9999;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 5px solid var(--light-green-bg);
            border-top: 5px solid var(--primary-green);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Today's Date Highlight */
        .today-highlight {
            display: inline-block;
            background-color: var(--primary-green);
            color: white;
            padding: 4px 12px;
            border-radius: 20px;
            font-weight: 600;
            margin-left: 10px;
            font-size: 0.9rem;
        }

        /* Animation for saved records */
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .table tbody tr {
            animation: fadeIn 0.5s ease forwards;
        }

        .table tbody tr:nth-child(even) {
            animation-delay: 0.05s;
        }
        .table tbody tr:nth-child(odd) {
            animation-delay: 0.1s;
        }

        /* Custom scrollbar */
        .table-responsive::-webkit-scrollbar {
            height: 8px;
        }

        .table-responsive::-webkit-scrollbar-track {
            background: var(--light-green-bg);
            border-radius: 4px;
        }

        .table-responsive::-webkit-scrollbar-thumb {
            background: var(--secondary-green);
            border-radius: 4px;
        }

        .table-responsive::-webkit-scrollbar-thumb:hover {
            background: var(--primary-green-light);
        }

        /* Responsive Design */
        @media (max-width: 1200px) {
            .col-md-2, .col-md-3, .col-md-4, .col-md-6 {
                width: 100%;
                margin-bottom: 16px;
            }
            
            .page-header {
                flex-direction: column;
                align-items: flex-start;
            }
            
            .header-actions {
                width: 100%;
                justify-content: flex-start;
            }
        }

        @media (max-width: 768px) {
            .main-content {
                padding: 16px;
            }
            
            .page-header {
                padding: 22px 20px;
            }
            
            .header-content h1 {
                font-size: 1.8rem;
            }
            
            .card-body, .card-header {
                padding: 20px;
            }
            
            .btn {
                width: 100%;
                margin-bottom: 8px;
            }
            
            .header-actions {
                flex-direction: column;
            }
        }

        /* Validation styles */
        .is-invalid {
            border-color: var(--danger-red) !important;
        }

        .invalid-feedback {
            color: var(--danger-red);
            font-size: 0.875rem;
            margin-top: 4px;
            display: none;
        }

        .is-invalid + .invalid-feedback {
            display: block;
        }

        /* Action buttons in table */
        .action-buttons {
            display: flex;
            gap: 8px;
        }

        .action-btn {
            padding: 6px 12px;
            border-radius: var(--radius-sm);
            font-size: 0.85rem;
            cursor: pointer;
            border: none;
            transition: all 0.2s ease;
        }

        .action-btn-save {
            background-color: var(--primary-green);
            color: white;
        }

        .action-btn-save:hover {
            background-color: var(--primary-green-dark);
        }

        .action-btn-clear {
            background-color: var(--gray-light);
            color: var(--dark-text);
        }

        .action-btn-clear:hover {
            background-color: var(--gray-medium);
        }
    </style>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
</head>
<body>
    <!-- Loading Overlay -->
    <div class="loading-overlay" id="loadingOverlay">
        <div class="spinner"></div>
    </div>

    <div class="main-content">
        <div class="page-header">
            <div class="header-content">
                <h1 class="page-title">Record Attendance <span class="today-highlight">Today</span></h1>
                <p class="page-subtitle">Record staff clock-in and clock-out times for efficient tracking</p>
            </div>
            <div class="header-actions">
                <a href="{{ route('dashboard') }}" class="btn btn-outline-primary">
                    <i class="fas fa-tachometer-alt me-2"></i>Back to Dashboard
                </a>
                <a href="{{ route('attendance.report') }}" class="btn btn-outline-primary">
                    <i class="fas fa-chart-bar me-2"></i>View Reports
                </a>
                <a href="{{ route('staff.index') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-2"></i>Back to Staff
                </a>
            </div>
        </div>
        
        @if(session('success'))
            <div class="alert alert-success alert-dismissible fade show mb-4" id="successAlert">
                <i class="fas fa-check-circle me-2"></i>
                {{ session('success') }}
                <button type="button" class="btn-close" onclick="dismissAlert('successAlert')">×</button>
            </div>
        @endif

        @if(session('error'))
            <div class="alert alert-error alert-dismissible fade show mb-4" id="errorAlert">
                <i class="fas fa-exclamation-circle me-2"></i>
                {{ session('error') }}
                <button type="button" class="btn-close" onclick="dismissAlert('errorAlert')">×</button>
            </div>
        @endif
        
        <!-- Quick Daily Recording -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-calendar-day me-2"></i>Record for Today ({{ \Carbon\Carbon::parse($today)->format('F j, Y') }})</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="{{ route('attendance.store') }}" id="individualForm">
                    @csrf
                    <div class="row mb-3">
                        <div class="col-md-4">
                            <label class="form-label">Select Staff Member *</label>
                            <select name="staff_id" class="form-select" id="staffSelect" required>
                                <option value="">-- Select Staff --</option>
                                @foreach($staff as $member)
                                    <option value="{{ $member->id }}">
                                        {{ $member->first_name }} {{ $member->last_name }} ({{ $member->employee_id ?? 'No ID' }})
                                    </option>
                                @endforeach
                            </select>
                            <div class="invalid-feedback">Please select a staff member</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Date *</label>
                            <input type="date" name="date" value="{{ $today }}" class="form-control" id="dateInput" required>
                            <div class="invalid-feedback">Please select a date</div>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">Status *</label>
                            <select name="status" class="form-select" id="statusSelect" required>
                                <option value="present">Present</option>
                                <option value="absent">Absent</option>
                                <option value="late">Late</option>
                                <option value="half_day">Half Day</option>
                                <option value="on_leave">On Leave</option>
                            </select>
                            <div class="invalid-feedback">Please select a status</div>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-warning w-100" onclick="fillCurrentDateTime()">
                                <i class="fas fa-clock me-2"></i>Use Current Date & Time
                            </button>
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <label class="form-label">Clock In Time</label>
                            <input type="time" name="clock_in" class="form-control" id="clockInInput">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">Clock Out Time</label>
                            <input type="time" name="clock_out" class="form-control" id="clockOutInput">
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">&nbsp;</label>
                            <div class="action-buttons">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i>Save Record
                                </button>
                                <button type="button" class="btn btn-outline-secondary" onclick="fillCurrentTime()">
                                    <i class="fas fa-clock me-2"></i>Use Current Time Only
                                </button>
                                <button type="reset" class="btn btn-outline-secondary">
                                    <i class="fas fa-redo me-2"></i>Reset Form
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Bulk Attendance Recording -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0"><i class="fas fa-users me-2"></i>Bulk Attendance Recording</h5>
            </div>
            <div class="card-body">
                <form method="POST" action="{{ route('attendance.bulk-store') }}" id="bulkAttendanceForm">
                    @csrf
                    <div class="row mb-3">
                        <div class="col-md-3">
                            <label class="form-label">Date *</label>
                            <input type="date" name="date" value="{{ $today }}" class="form-control" id="bulkDate" required>
                            <div class="invalid-feedback">Please select a date</div>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-success w-100" onclick="markAllAs('present')">
                                <i class="fas fa-check me-2"></i>Mark All Present
                            </button>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-danger w-100" onclick="markAllAs('absent')">
                                <i class="fas fa-times me-2"></i>Mark All Absent
                            </button>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label">&nbsp;</label>
                            <button type="button" class="btn btn-warning w-100" onclick="markAllAs('late')">
                                <i class="fas fa-clock me-2"></i>Mark All Late
                            </button>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label">&nbsp;</label>
                            <button type="submit" class="btn btn-primary w-100" onclick="return validateBulkForm()">
                                <i class="fas fa-save me-2"></i>Save All Records
                            </button>
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th width="50">#</th>
                                    <th>Staff Member</th>
                                    <th>Employee ID</th>
                                    <th>Department</th>
                                    <th width="120">Status *</th>
                                    <th width="120">Clock In</th>
                                    <th width="120">Clock Out</th>
                                    <th>Today's Record</th>
                                    <th width="100">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($staff as $member)
                                    @php
                                        $todayRecord = $todayAttendance[$member->id] ?? null;
                                        $hasRecord = $todayRecord && $todayRecord->status;
                                    @endphp
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <div class="avatar me-2">
                                                    @if($member->profile_picture)
                                                        <img src="{{ asset('storage/' . $member->profile_picture) }}" class="avatar-img">
                                                    @else
                                                        {{ substr($member->first_name, 0, 1) }}{{ substr($member->last_name, 0, 1) }}
                                                    @endif
                                                </div>
                                                {{ $member->first_name }} {{ $member->last_name }}
                                            </div>
                                        </td>
                                        <td>{{ $member->employee_id ?? 'N/A' }}</td>
                                        <td>
                                            <span class="department-badge">{{ $member->department->name ?? 'N/A' }}</span>
                                        </td>
                                        <td>
                                            <select name="attendance[{{ $member->id }}][status]" 
                                                    class="form-select form-select-sm attendance-status" 
                                                    data-staff-id="{{ $member->id }}"
                                                    required>
                                                <option value="">-- Select --</option>
                                                <option value="present" {{ $hasRecord && $todayRecord->status == 'present' ? 'selected' : '' }}>Present</option>
                                                <option value="absent" {{ $hasRecord && $todayRecord->status == 'absent' ? 'selected' : '' }}>Absent</option>
                                                <option value="late" {{ $hasRecord && $todayRecord->status == 'late' ? 'selected' : '' }}>Late</option>
                                                <option value="half_day" {{ $hasRecord && $todayRecord->status == 'half_day' ? 'selected' : '' }}>Half Day</option>
                                                <option value="on_leave" {{ $hasRecord && $todayRecord->status == 'on_leave' ? 'selected' : '' }}>On Leave</option>
                                            </select>
                                        </td>
                                        <td>
                                            <input type="time" 
                                                   name="attendance[{{ $member->id }}][clock_in]" 
                                                   class="form-control form-control-sm clock-in"
                                                   data-staff-id="{{ $member->id }}"
                                                   value="{{ $hasRecord && $todayRecord->clock_in_time ? \Carbon\Carbon::parse($todayRecord->clock_in_time)->format('H:i') : '09:00' }}">
                                        </td>
                                        <td>
                                            <input type="time" 
                                                   name="attendance[{{ $member->id }}][clock_out]" 
                                                   class="form-control form-control-sm clock-out"
                                                   data-staff-id="{{ $member->id }}"
                                                   value="{{ $hasRecord && $todayRecord->clock_out_time ? \Carbon\Carbon::parse($todayRecord->clock_out_time)->format('H:i') : '17:00' }}">
                                        </td>
                                        <td>
                                            @if($hasRecord)
                                                @php
                                                    $statusClass = 'status-' . $todayRecord->status;
                                                @endphp
                                                <span class="{{ $statusClass }}">
                                                    {{ ucfirst($todayRecord->status) }}
                                                    @if($todayRecord->clock_in_time)
                                                        ({{ \Carbon\Carbon::parse($todayRecord->clock_in_time)->format('h:i A') }}
                                                        @if($todayRecord->clock_out_time)
                                                            - {{ \Carbon\Carbon::parse($todayRecord->clock_out_time)->format('h:i A') }}
                                                        @endif
                                                        )
                                                    @endif
                                                </span>
                                            @else
                                                <span class="badge bg-secondary">Not Recorded</span>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="action-buttons">
                                                <button type="button" class="action-btn action-btn-save" onclick="saveIndividualRow({{ $member->id }})">
                                                    <i class="fas fa-save"></i>
                                                </button>
                                                <button type="button" class="action-btn action-btn-clear" onclick="clearRow({{ $member->id }})">
                                                    <i class="fas fa-times"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Loading overlay control
        function showLoading() {
            document.getElementById('loadingOverlay').style.display = 'flex';
        }

        function hideLoading() {
            document.getElementById('loadingOverlay').style.display = 'none';
        }

        // Alert dismissal
        function dismissAlert(alertId) {
            document.getElementById(alertId).style.display = 'none';
        }

        // Auto-dismiss alerts after 5 seconds
        setTimeout(() => {
            const alerts = document.querySelectorAll('.alert');
            alerts.forEach(alert => {
                alert.style.display = 'none';
            });
        }, 5000);

        // Date and time functions
        function fillCurrentDateTime() {
            const now = new Date();
            const dateString = now.toISOString().split('T')[0];
            const timeString = now.toTimeString().substring(0, 5);
            
            // Fill date
            document.getElementById('dateInput').value = dateString;
            
            // Fill times
            document.getElementById('clockInInput').value = timeString;
            document.getElementById('clockOutInput').value = timeString;
            
            // Auto-select "present" status
            document.getElementById('statusSelect').value = 'present';
            
            // Visual feedback
            highlightFields(['dateInput', 'clockInInput', 'clockOutInput', 'statusSelect']);
        }

        function fillCurrentTime() {
            const now = new Date();
            const timeString = now.toTimeString().substring(0, 5);
            
            // Fill only the time inputs
            document.getElementById('clockInInput').value = timeString;
            document.getElementById('clockOutInput').value = timeString;
            
            // Visual feedback
            highlightFields(['clockInInput', 'clockOutInput']);
        }

        function highlightFields(fieldIds) {
            fieldIds.forEach(id => {
                const field = document.getElementById(id);
                if (field) {
                    field.style.backgroundColor = '#e8f5e9';
                    field.style.borderColor = '#4caf50';
                    
                    setTimeout(() => {
                        field.style.backgroundColor = '';
                        field.style.borderColor = '';
                    }, 1500);
                }
            });
        }

        // Bulk operations
        function markAllAs(status) {
            const selects = document.querySelectorAll('.attendance-status');
            let count = 0;
            
            selects.forEach(select => {
                select.value = status;
                count++;
                
                // Trigger change event to update times
                const event = new Event('change');
                select.dispatchEvent(event);
            });
            
            // Show confirmation
            const action = status === 'present' ? 'Present' : 
                          status === 'absent' ? 'Absent' : 
                          status === 'late' ? 'Late' : 'Marked';
            showNotification(`${count} staff members marked as ${action}`, 'success');
        }

        // Auto-update clock times based on status
        document.querySelectorAll('.attendance-status').forEach(select => {
            select.addEventListener('change', function() {
                const staffId = this.dataset.staffId;
                const row = this.closest('tr');
                const clockIn = row.querySelector(`.clock-in[data-staff-id="${staffId}"]`);
                const clockOut = row.querySelector(`.clock-out[data-staff-id="${staffId}"]`);
                
                if (this.value === 'absent' || this.value === 'on_leave') {
                    if (clockIn) clockIn.value = '';
                    if (clockOut) clockOut.value = '';
                } else if (this.value === 'present') {
                    if (clockIn && !clockIn.value) clockIn.value = '09:00';
                    if (clockOut && !clockOut.value) clockOut.value = '17:00';
                } else if (this.value === 'half_day') {
                    if (clockIn && !clockIn.value) clockIn.value = '09:00';
                    if (clockOut && !clockOut.value) clockOut.value = '13:00';
                } else if (this.value === 'late') {
                    if (clockIn && !clockIn.value) clockIn.value = '10:00';
                    if (clockOut && !clockOut.value) clockOut.value = '18:00';
                }
                
                // Apply status color
                applyStatusColor(this);
            });
            
            // Initialize colors
            if (select.value) {
                applyStatusColor(select);
            }
        });

        function applyStatusColor(select) {
            const colors = {
                'present': '#4caf50',
                'absent': '#e53935',
                'late': '#ffb300',
                'half_day': '#2196f3',
                'on_leave': '#5d4037'
            };
            
            select.style.color = colors[select.value] || '#1b3c1f';
            select.style.fontWeight = '600';
            select.style.backgroundColor = colors[select.value] ? `${colors[select.value]}15` : '';
        }

        // Update bulk date for all forms
        document.getElementById('bulkDate').addEventListener('change', function() {
            document.getElementById('dateInput').value = this.value;
            highlightFields(['bulkDate', 'dateInput']);
        });

        // Today's date highlighting
        document.addEventListener('DOMContentLoaded', function() {
            const today = new Date().toISOString().split('T')[0];
            const dateInputs = document.querySelectorAll('input[type="date"]');
            
            dateInputs.forEach(input => {
                if (input.value === today) {
                    input.style.backgroundColor = '#f1f8e9';
                    input.style.borderColor = '#2e7d32';
                    input.style.fontWeight = '600';
                }
            });
        });

        // Form validation
        function validateIndividualForm() {
            const staffSelect = document.getElementById('staffSelect');
            const dateInput = document.getElementById('dateInput');
            const statusSelect = document.getElementById('statusSelect');
            let isValid = true;
            
            // Reset validation
            [staffSelect, dateInput, statusSelect].forEach(field => {
                field.classList.remove('is-invalid');
            });
            
            // Validate fields
            if (!staffSelect.value) {
                staffSelect.classList.add('is-invalid');
                isValid = false;
            }
            
            if (!dateInput.value) {
                dateInput.classList.add('is-invalid');
                isValid = false;
            }
            
            if (!statusSelect.value) {
                statusSelect.classList.add('is-invalid');
                isValid = false;
            }
            
            return isValid;
        }

        function validateBulkForm() {
            const bulkDate = document.getElementById('bulkDate');
            const statusSelects = document.querySelectorAll('.attendance-status');
            let hasData = false;
            
            // Reset validation
            bulkDate.classList.remove('is-invalid');
            
            // Validate date
            if (!bulkDate.value) {
                bulkDate.classList.add('is-invalid');
                showNotification('Please select a date for bulk attendance', 'error');
                return false;
            }
            
            // Check if at least one status is selected
            statusSelects.forEach(select => {
                if (select.value) {
                    hasData = true;
                }
            });
            
            if (!hasData) {
                showNotification('Please mark attendance for at least one staff member', 'error');
                return false;
            }
            
            // Show loading
            showLoading();
            return true;
        }

        // Individual row save function
        function saveIndividualRow(staffId) {
            const row = document.querySelector(`tr td select[data-staff-id="${staffId}"]`).closest('tr');
            const statusSelect = row.querySelector(`select[data-staff-id="${staffId}"]`);
            const clockIn = row.querySelector(`.clock-in[data-staff-id="${staffId}"]`);
            const clockOut = row.querySelector(`.clock-out[data-staff-id="${staffId}"]`);
            const bulkDate = document.getElementById('bulkDate');
            
            if (!statusSelect.value) {
                showNotification('Please select a status for this staff member', 'error');
                return;
            }
            
            if (!bulkDate.value) {
                showNotification('Please select a date first', 'error');
                return;
            }
            
            // Create form data
            const formData = new FormData();
            formData.append('_token', document.querySelector('input[name="_token"]').value);
            formData.append('staff_id', staffId);
            formData.append('date', bulkDate.value);
            formData.append('status', statusSelect.value);
            if (clockIn.value) formData.append('clock_in', clockIn.value);
            if (clockOut.value) formData.append('clock_out', clockOut.value);
            
            // Send request
            showLoading();
            fetch("{{ route('attendance.store') }}", {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.success) {
                    showNotification('Attendance saved successfully!', 'success');
                    // Update the "Today's Record" cell
                    const recordCell = row.querySelector('td:nth-child(8)');
                    const status = statusSelect.value;
                    const statusText = status.charAt(0).toUpperCase() + status.slice(1);
                    const timeText = clockIn.value ? 
                        ` (${formatTimeForDisplay(clockIn.value)}${clockOut.value ? ' - ' + formatTimeForDisplay(clockOut.value) : ''})` : '';
                    
                    recordCell.innerHTML = `<span class="status-${status}">${statusText}${timeText}</span>`;
                } else {
                    showNotification(data.message || 'Error saving attendance', 'error');
                }
            })
            .catch(error => {
                hideLoading();
                showNotification('Network error. Please try again.', 'error');
                console.error('Error:', error);
            });
        }

        function clearRow(staffId) {
            const row = document.querySelector(`tr td select[data-staff-id="${staffId}"]`).closest('tr');
            const statusSelect = row.querySelector(`select[data-staff-id="${staffId}"]`);
            const clockIn = row.querySelector(`.clock-in[data-staff-id="${staffId}"]`);
            const clockOut = row.querySelector(`.clock-out[data-staff-id="${staffId}"]`);
            
            statusSelect.value = '';
            if (clockIn) clockIn.value = '';
            if (clockOut) clockOut.value = '';
            applyStatusColor(statusSelect);
            
            showNotification('Row cleared', 'info');
        }

        function formatTimeForDisplay(timeString) {
            if (!timeString) return '';
            
            const [hours, minutes] = timeString.split(':');
            const hour = parseInt(hours);
            const ampm = hour >= 12 ? 'PM' : 'AM';
            const displayHour = hour % 12 || 12;
            
            return `${displayHour}:${minutes} ${ampm}`;
        }

        // Notification system
        function showNotification(message, type = 'info') {
            // Create notification element
            const notification = document.createElement('div');
            notification.className = `alert alert-${type === 'error' ? 'error' : 'success'}`;
            notification.style.position = 'fixed';
            notification.style.top = '20px';
            notification.style.right = '20px';
            notification.style.zIndex = '9999';
            notification.style.minWidth = '300px';
            notification.style.maxWidth = '400px';
            
            const icon = type === 'error' ? 
                '<i class="fas fa-exclamation-circle me-2"></i>' : 
                '<i class="fas fa-check-circle me-2"></i>';
            
            notification.innerHTML = `
                ${icon}${message}
                <button type="button" class="btn-close" onclick="this.parentElement.remove()">×</button>
            `;
            
            document.body.appendChild(notification);
            
            // Auto-remove after 5 seconds
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 5000);
        }

        // Add form submit handlers
        document.getElementById('individualForm').addEventListener('submit', function(e) {
            if (!validateIndividualForm()) {
                e.preventDefault();
                showNotification('Please fill all required fields', 'error');
            } else {
                showLoading();
            }
        });

        document.getElementById('bulkAttendanceForm').addEventListener('submit', function(e) {
            if (!validateBulkForm()) {
                e.preventDefault();
            }
        });

        // Add today's date to bulk form if not set
        document.addEventListener('DOMContentLoaded', function() {
            const bulkDate = document.getElementById('bulkDate');
            const today = new Date().toISOString().split('T')[0];
            
            if (bulkDate && !bulkDate.value) {
                bulkDate.value = today;
            }
        });
    </script>
</body>
</html>

