@extends('layouts.dashboard.superadminapp')

@section('title', 'Employee Daily Attendance')

@section('styles')
<style>
    div.dt-buttons {
        float: left;
        display: flex !important;
    }
    .dataTable {
        overflow-x: auto !important;
        display: table !important;
    }
    .dt-buttons .btn {
        margin-right: 0.5rem !important;
        padding: 0.25rem 0.75rem !important;
        font-size: 0.95rem !important;
    }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<x-layout.page-header title="UEPL | Employee Daily Attendance" icon="user-tie" iconColor="primary" />

<!-- Alerts -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle mr-2"></i>{{ session('success') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif
@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
@endif

<!-- Filters & Actions -->
<div class="row mb-4">
    <div class="col-md-8">
        <form action="{{ route('superadmin.employee.index') }}" method="GET" class="form-inline">
            <label class="mr-2 font-weight-bold">Filter By Date:</label>
            <input type="date" name="date" class="form-control mr-2" value="{{ request('date') ?? date('Y-m-d') }}">
            
            <button type="submit" class="btn btn-primary btn-sm">
                <i class="fas fa-filter mr-1"></i> Filter
            </button>
            <a href="{{ route('superadmin.employee.index') }}" class="btn btn-secondary btn-sm ml-2">
                <i class="fas fa-sync-alt mr-1"></i> Reset
            </a>
        </form>
    </div>
    <div class="col-md-4 text-right">
        <button type="button" class="btn btn-success btn-sm mr-2" data-toggle="modal" data-target="#addAttendanceModal">
            <i class="fas fa-plus mr-1"></i> Add Manual Entry
        </button>
        <button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#uploadModal">
            <i class="fas fa-upload mr-1"></i> Upload Excel
        </button>
    </div>
</div>

<!-- Attendance Card -->
<div class="card shadow mb-4">
    <div class="card-header py-3 d-flex justify-content-between align-items-center" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-clipboard-list mr-2"></i> Attendance Records ({{ $attendances->count() }})
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table id="attendanceTable" class="table table-bordered table-striped table-sm" width="100%" cellspacing="0">
                <thead class="thead-light">
                    <tr class="text-center">
                        <th>Date</th>
                        <th>Emp ID</th>
                        <th>Name</th>
                        <th>Check In</th>
                        <th>Break Out</th>
                        <th>Break In</th>
                        <th>Check Out</th>
                        <th>Work Hrs</th>
                        <th>OT</th>
                        <th>Shortage</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @php
                        function decimalToHoursMinutes($decimal) {
                            $h = floor($decimal);
                            $m = round(($decimal - $h) * 60);
                            return sprintf('%02d:%02d', $h, $m);
                        }
                    @endphp
                    @foreach($attendances as $row)
                        @php
                            // Check if fields are time strings or Carbon objects
                            // Assuming model casts to H:i:s string or null
                            $checkIn = $row->check_in ? \Carbon\Carbon::parse($row->check_in) : null;
                            $breakOut = $row->break_out ? \Carbon\Carbon::parse($row->break_out) : null;
                            $breakIn = $row->break_in ? \Carbon\Carbon::parse($row->break_in) : null;
                            $checkOut = $row->check_out ? \Carbon\Carbon::parse($row->check_out) : null;

                            $workDuration = null;
                            $workHours = 0;

                            // Calculate display logic if not stored (fallback)
                            // Ideally, we rely on controller calculation, but view calculation acts as backup
                            if ($checkIn && $checkOut) {
                                $total = $checkIn->diffInMinutes($checkOut);
                                $break = ($breakIn && $breakOut) ? $breakOut->diffInMinutes($breakIn) : 0;
                                $workMinutes = max(0, $total - $break);
                                $workHours = round($workMinutes / 60, 2);
                                $workDuration = sprintf('%02d:%02d', intdiv($workMinutes, 60), $workMinutes % 60);
                            } elseif ($row->working_hours > 0) {
                                // Fallback: Use stored working hours
                                $workHours = $row->working_hours;
                                $workMinutes = round($workHours * 60);
                                $workDuration = sprintf('%02d:%02d', intdiv($workMinutes, 60), $workMinutes % 60);
                            }
                            
                            // Use stored values if available (from enhance logic), else calc
                            $ot = $row->ot_hours ?? ($workHours > 9 ? round($workHours - 9, 2) : 0);
                            $shortage = $row->shortage_hours ?? ($workHours < 9 ? round(9 - $workHours, 2) : 0);
                        @endphp
                        <tr class="text-center">
                            <td>{{ \Carbon\Carbon::parse($row->date)->format('d-m-Y') }}</td>
                            <td>{{ $row->employee_id }}</td>
                            <td>{{ $row->employee_name }}</td>
                            <td>{{ $row->check_in ? \Carbon\Carbon::parse($row->check_in)->format('H:i') : '-' }}</td>
                            <td>{{ $row->break_out ? \Carbon\Carbon::parse($row->break_out)->format('H:i') : '-' }}</td>
                            <td>{{ $row->break_in ? \Carbon\Carbon::parse($row->break_in)->format('H:i') : '-' }}</td>
                            <td>{{ $row->check_out ? \Carbon\Carbon::parse($row->check_out)->format('H:i') : '-' }}</td>
                            <td>
                                @if($workDuration)
                                    <strong>{{ $workDuration }}</strong>
                                @else
                                    -
                                @endif
                            </td>
                            <td>
                                @if($ot > 0)
                                    <span class="badge badge-success">{{ decimalToHoursMinutes($ot) }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                @if($shortage > 0)
                                    <span class="badge badge-danger">{{ decimalToHoursMinutes($shortage) }}</span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td>
                                <button type="button" class="btn btn-info btn-sm edit-btn"
                                    data-id="{{ $row->id }}"
                                    data-employee-id="{{ $row->employee_id }}"
                                    data-date="{{ $row->date ? $row->date->format('Y-m-d') : '' }}"
                                    data-check-in="{{ $row->check_in ? \Carbon\Carbon::parse($row->check_in)->format('H:i') : '' }}"
                                    data-break-out="{{ $row->break_out ? \Carbon\Carbon::parse($row->break_out)->format('H:i') : '' }}"
                                    data-break-in="{{ $row->break_in ? \Carbon\Carbon::parse($row->break_in)->format('H:i') : '' }}"
                                    data-check-out="{{ $row->check_out ? \Carbon\Carbon::parse($row->check_out)->format('H:i') : '' }}"
                                    title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <form action="{{ route('superadmin.attendance.delete', $row->id) }}" method="POST" class="d-inline" onsubmit="return confirm('Are you sure you want to delete this entry?');">
                                    @csrf
                                    @method('DELETE') 
                                    <button type="submit" class="btn btn-danger btn-sm">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Add/Edit Attendance Modal -->
<div class="modal fade" id="addAttendanceModal" tabindex="-1" role="dialog" aria-labelledby="addAttendanceModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="attendanceForm" action="{{ route('superadmin.attendance.store') }}" method="POST">
                @csrf
                <!-- Hidden Method Field for Edit -->
                <input type="hidden" name="_method" id="formMethod" value="POST">
                
                <div class="modal-header" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
                    <h5 class="modal-title text-white" id="addAttendanceModalLabel">
                        <i class="fas fa-clock mr-2"></i> <span id="modalTitle">Add Manual Attendance</span>
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label>Employee <span class="text-danger">*</span></label>
                        <select name="employee_id" id="employee_id" class="form-control" required>
                            <option value="">Select Employee</option>
                            @foreach($employees as $emp)
                                <option value="{{ $emp->employee_id }}">{{ $emp->name }} ({{ $emp->employee_id }})</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="form-group">
                        <label>Date <span class="text-danger">*</span></label>
                        <input type="date" name="date" id="date" class="form-control" required>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Check In</label>
                            <input type="time" name="check_in" id="check_in" class="form-control">
                        </div>
                        <div class="form-group col-md-6">
                            <label>Check Out</label>
                            <input type="time" name="check_out" id="check_out" class="form-control">
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="form-group col-md-6">
                            <label>Break Out</label>
                            <input type="time" name="break_out" id="break_out" class="form-control">
                        </div>
                        <div class="form-group col-md-6">
                            <label>Break In</label>
                            <input type="time" name="break_in" id="break_in" class="form-control">
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary btn-sm">Save Entry</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Upload Modal -->
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="uploadModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form action="{{ route('superadmin.attendance.import') }}" method="POST" enctype="multipart/form-data">
                @csrf
                <div class="modal-header" style="background: linear-gradient(135deg, #28a745 0%, #1e7e34 100%);">
                    <h5 class="modal-title text-white" id="uploadModalLabel">
                        <i class="fas fa-file-excel mr-2"></i> Upload Attendance File
                    </h5>
                    <button type="button" class="close text-white" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="small font-weight-bold">Excel File (.xlsx) <span class="text-danger">*</span></label>
                        <input type="file" name="import_file" class="form-control" accept=".xlsx,.xls" required>
                        <small class="text-muted">
                            <a href="{{ asset('templates/attendance_import_template.xlsx') }}" download>
                                <i class="fas fa-download mr-1"></i> Download Sample Template
                            </a>
                        </small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-sm" data-dismiss="modal">
                        <i class="fa fa-times mr-1"></i> Cancel
                    </button>
                    <button type="submit" class="btn btn-success btn-sm">
                        <i class="fa fa-upload mr-1"></i> Upload
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script>
$(document).ready(function() {
    $('#attendanceTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', className: 'btn btn-secondary btn-sm' },
            { extend: 'excel', className: 'btn btn-secondary btn-sm' },
            { extend: 'pdf', className: 'btn btn-secondary btn-sm' },
            { extend: 'print', className: 'btn btn-secondary btn-sm' },
            { extend: 'colvis', className: 'btn btn-secondary btn-sm' }
        ],
        pageLength: 25,
        responsive: true,
        order: [[ 0, "desc" ]] // Order by Date desc
    });

    // Handle Edit Click - Use event delegation for DataTables compatibility
    $(document).on('click', '.edit-btn', function(e) {
        e.preventDefault();
        e.stopPropagation();

        let $btn = $(this);
        let id = $btn.data('id');
        let empId = $btn.data('employee-id');
        let date = $btn.data('date');
        let checkIn = $btn.data('check-in');
        let breakOut = $btn.data('break-out');
        let breakIn = $btn.data('break-in');
        let checkOut = $btn.data('check-out');

        console.log('Edit button clicked - ID:', id);
        console.log('Data:', { empId, date, checkIn, breakOut, breakIn, checkOut });

        // Populate Modal
        $('#modalTitle').text('Edit Attendance Entry');

        // Use the update route structure
        let updateUrl = "{{ url('superadmin/attendance/update') }}/" + id;
        console.log('Update URL:', updateUrl);
        $('#attendanceForm').attr('action', updateUrl);

        // Set form values
        $('#employee_id').val(empId);
        $('#date').val(date);

        // Format times to HH:mm for input type="time"
        const formatTime = (timeStr) => {
            if (!timeStr) return '';
            return String(timeStr).substring(0, 5);
        };

        $('#check_in').val(formatTime(checkIn));
        $('#break_out').val(formatTime(breakOut));
        $('#break_in').val(formatTime(breakIn));
        $('#check_out').val(formatTime(checkOut));

        // Show modal
        $('#addAttendanceModal').modal('show');
    });

    // Reset Modal on Hide
    $('#addAttendanceModal').on('hidden.bs.modal', function () {
        $('#attendanceForm').trigger("reset");
        $('#modalTitle').text('Add Manual Attendance');
        $('#formMethod').val('POST');
        $('#attendanceForm').attr('action', "{{ route('superadmin.attendance.store') }}");
        $('#employee_id').val('');
    });
});
</script>
@endsection
