@extends('layouts.app')

@section('title', 'Pending Approvals')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col">
            <h1 class="h3">Pending Approvals</h1>
        </div>
    </div>
    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>Employee</th>
                            <th>Change Type</th>
                            <th>Requested By</th>
                            <th>Date</th>
                            <th>Changes</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($pendingApprovals as $approval)
                        @php
                            $changeLog = $approval->approvable;
                            $employee = $changeLog->employee ?? null;
                        @endphp
                        @if($employee)
                        <tr>
                            <td>
                                <strong>{{ $employee->employee_id }}</strong><br>
                                {{ $employee->full_name }}
                            </td>
                            <td>
                                <span class="badge bg-info">{{ ucfirst(str_replace('_', ' ', $changeLog->change_type)) }}</span>
                            </td>
                            <td>{{ $approval->requester->name }}</td>
                            <td>{{ $changeLog->created_at->format('d/m/Y') }}</td>
                            <td>
                                @foreach($changeLog->changed_fields as $field => $changes)
                                <div class="small mb-1">
                                    <strong>{{ str_replace('_', ' ', $field) }}:</strong>
                                    <span class="text-danger">{{ $changes['old'] ?? 'N/A' }}</span>
                                    <i class="bi bi-arrow-right mx-1"></i>
                                    <span class="text-success">{{ $changes['new'] ?? 'N/A' }}</span>
                                </div>
                                @endforeach
                             </td>
                            <td>
                                <div class="btn-group" role="group">
                                    <button type="button" class="btn btn-sm btn-success"
                                        onclick="approveChange({{ $changeLog->id }})">
                                        <i class="bi bi-check"></i> Approve
                                    </button>
                                    <button type="button" class="btn btn-sm btn-danger"
                                        data-bs-toggle="modal"
                                        data-bs-target="#rejectModal{{ $changeLog->id }}">
                                        <i class="bi bi-x"></i> Reject
                                    </button>
                                    <a href="{{ route('employee_profile.show', $employee) }}"
                                       class="btn btn-sm btn-info">
                                        <i class="bi bi-eye"></i> View
                                    </a>
                                </div>
                             </td>
                        </tr>

                        <!-- Reject Modal for each approval -->
                        <div class="modal fade" id="rejectModal{{ $changeLog->id }}" tabindex="-1" aria-labelledby="rejectModalLabel{{ $changeLog->id }}" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header bg-danger text-white">
                                        <h5 class="modal-title" id="rejectModalLabel{{ $changeLog->id }}">
                                            <i class="bi bi-exclamation-triangle"></i> Reject Change Request
                                        </h5>
                                        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <form action="{{ route('approvals.reject', $approval) }}" method="POST" id="rejectForm{{ $changeLog->id }}">
                                        @csrf
                                        @method('PUT')
                                        <div class="modal-body">
                                            <div class="mb-3">
                                                <label class="form-label fw-bold">Change Details</label>
                                                <div class="alert alert-light border">
                                                    <div><strong>Employee:</strong> {{ $employee->full_name }} ({{ $employee->employee_id }})</div>
                                                    <div><strong>Change Type:</strong> {{ ucfirst(str_replace('_', ' ', $changeLog->change_type)) }}</div>
                                                    <div><strong>Requested By:</strong> {{ $approval->requester->name }}</div>
                                                    <div><strong>Date:</strong> {{ $changeLog->created_at->format('d/m/Y H:i') }}</div>
                                                </div>
                                            </div>
                                            <div class="mb-3">
                                                <label for="rejection_reason" class="form-label fw-bold">Rejection Reason <span class="text-danger">*</span></label>
                                                <textarea 
                                                    class="form-control" 
                                                    id="rejection_reason" 
                                                    name="rejection_reason" 
                                                    rows="4" 
                                                    required
                                                    placeholder="Please provide a reason for rejecting this change request..."
                                                ></textarea>
                                                <div class="form-text">This reason will be sent to the requester.</div>
                                            </div>
                                        </div>
                                        <div class="modal-footer">
                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                                                <i class="bi bi-x-circle"></i> Cancel
                                            </button>
                                            <button type="submit" class="btn btn-danger">
                                                <i class="bi bi-check-circle"></i> Confirm Rejection
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                        @endif
                        @endforeach
                    </tbody>
                </table>
            </div>

            @if($pendingApprovals->isEmpty())
            <div class="text-center py-5">
                <i class="bi bi-check-circle display-1 text-success"></i>
                <h4 class="mt-3">No pending approvals</h4>
                <p class="text-muted">All changes have been processed.</p>
            </div>
            @endif
        </div>
    </div>
</div>

@push('scripts')
<script>
function approveChange(changeLogId) {
    if (confirm('Are you sure you want to approve this change?')) {
        // Create a form dynamically
        const form = document.createElement('form');
        form.method = 'POST';
        form.action = `/approvals/${changeLogId}/approve`;
        
        // Add CSRF token
        const csrfInput = document.createElement('input');
        csrfInput.type = 'hidden';
        csrfInput.name = '_token';
        csrfInput.value = '{{ csrf_token() }}';
        form.appendChild(csrfInput);
        
        // Add method spoofing for PUT
        const methodInput = document.createElement('input');
        methodInput.type = 'hidden';
        methodInput.name = '_method';
        methodInput.value = 'PUT';
        form.appendChild(methodInput);
        
        document.body.appendChild(form);
        form.submit();
    }
}

// Optional: Add client-side validation for rejection reason
document.querySelectorAll('form[id^="rejectForm"]').forEach(form => {
    form.addEventListener('submit', function(e) {
        const reason = this.querySelector('#rejection_reason');
        if (reason && reason.value.trim() === '') {
            e.preventDefault();
            alert('Please provide a rejection reason.');
            reason.focus();
        }
    });
});
</script>
@endpush

@push('styles')
<style>
    .modal-header.bg-danger {
        background-color: #dc3545 !important;
    }
    .alert-light {
        background-color: #f8f9fa;
        border-left: 4px solid #ffc107;
    }
    .table td {
        vertical-align: middle;
    }
    .btn-group .btn {
        margin: 0 2px;
    }
    textarea:focus {
        border-color: #dc3545;
        box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25);
    }
</style>
@endpush
@endsection