@extends('layouts.dashboard.managerapp')

@section('title', 'Payroll Management')

@section('styles')
<style>
    .stat-card { border-left: 4px solid; }
    .stat-draft { border-left-color: #858796; }
    .stat-pending { border-left-color: #f6c23e; }
    .stat-approved { border-left-color: #36b9cc; }
    .stat-paid { border-left-color: #1cc88a; }
</style>
@endsection

@section('content')

<!-- Page Heading -->
<div class="bg-white p-2 d-sm-flex align-items-center justify-content-between mb-4">
    <h1 class="h5 mb-0 text-gray-800">UEPL | Payroll Management</h1>
    <a href="{{ route('manager.salary-structure.index') }}" class="btn btn-outline-secondary btn-sm">
        <i class="fas fa-cogs mr-1"></i> Salary Structure
    </a>
</div>

<!-- 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"><span>&times;</span></button>
    </div>
@endif

<!-- Stats Cards -->
<div class="row mb-4">
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-draft shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-secondary text-uppercase mb-1">Draft</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $stats['draft'] }}</div>
                    </div>
                    <div class="col-auto"><i class="fas fa-file-alt fa-2x text-gray-300"></i></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-pending shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Pending</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $stats['pending'] }}</div>
                    </div>
                    <div class="col-auto"><i class="fas fa-clock fa-2x text-gray-300"></i></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-approved shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-info text-uppercase mb-1">Approved</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $stats['approved'] }}</div>
                    </div>
                    <div class="col-auto"><i class="fas fa-check-circle fa-2x text-gray-300"></i></div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-xl-3 col-md-6 mb-4">
        <div class="card stat-card stat-paid shadow h-100 py-2">
            <div class="card-body">
                <div class="row no-gutters align-items-center">
                    <div class="col mr-2">
                        <div class="text-xs font-weight-bold text-success text-uppercase mb-1">Paid</div>
                        <div class="h5 mb-0 font-weight-bold text-gray-800">{{ $stats['paid'] }}</div>
                    </div>
                    <div class="col-auto"><i class="fas fa-money-bill-wave fa-2x text-gray-300"></i></div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Filter -->
<div class="card shadow mb-4">
    <div class="card-header py-2" style="background: linear-gradient(135deg, #36b9cc 0%, #1e90a6 100%);">
        <h6 class="m-0 font-weight-bold text-white"><i class="fas fa-filter mr-2"></i> Filter</h6>
    </div>
    <div class="card-body py-3">
        <div class="row align-items-end">
            <div class="col-md-3">
                <label class="small font-weight-bold">Month</label>
                <input type="month" class="form-control form-control-sm" id="monthFilter" value="{{ $month }}">
            </div>
            <div class="col-md-3">
                <button type="button" class="btn btn-primary btn-sm" id="filterBtn">
                    <i class="fas fa-search mr-1"></i> Filter
                </button>
                <button type="button" class="btn btn-success btn-sm" id="generateBtn">
                    <i class="fas fa-plus mr-1"></i> Generate Payroll
                </button>
            </div>
            <div class="col-md-6 text-right">
                <div class="small text-muted">
                    Total Gross: <strong class="text-primary">{{ number_format($stats['total_gross'], 2) }}</strong> |
                    Total Net: <strong class="text-success">{{ number_format($stats['total_net'], 2) }}</strong>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Payroll Table -->
<div class="card shadow mb-4">
    <div class="card-header py-3" style="background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-money-check-alt mr-2"></i> Payroll - {{ \Carbon\Carbon::parse($month)->format('F Y') }}
        </h6>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-sm" id="payrollTable" width="100%">
                <thead class="thead-light">
                    <tr>
                        <th>Employee</th>
                        <th>Department</th>
                        <th>Days Worked</th>
                        <th>Gross Salary</th>
                        <th>Deductions</th>
                        <th>Net Salary</th>
                        <th>Status</th>
                        <th width="120" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($payrolls as $payroll)
                        <tr id="row-{{ $payroll->id }}">
                            <td>
                                <div class="font-weight-bold">{{ $payroll->employee->name ?? '-' }}</div>
                                <small class="text-muted">{{ $payroll->employee->employee_id ?? '-' }}</small>
                            </td>
                            <td>{{ $payroll->employee->department ?? '-' }}</td>
                            <td>{{ $payroll->days_worked }}/{{ $payroll->total_days }}</td>
                            <td class="text-right">{{ number_format($payroll->gross_salary, 2) }}</td>
                            <td class="text-right text-danger">{{ number_format($payroll->total_deductions, 2) }}</td>
                            <td class="text-right font-weight-bold text-success">{{ number_format($payroll->net_salary, 2) }}</td>
                            <td>
                                @switch($payroll->status)
                                    @case('Draft') <span class="badge badge-secondary">Draft</span> @break
                                    @case('Pending') <span class="badge badge-warning">Pending</span> @break
                                    @case('Approved') <span class="badge badge-info">Approved</span> @break
                                    @case('Paid') <span class="badge badge-success">Paid</span> @break
                                @endswitch
                            </td>
                            <td class="text-center">
                                @if($payroll->status == 'Draft')
                                    <button class="btn btn-warning btn-sm edit-btn" data-id="{{ $payroll->id }}" title="Edit"><i class="fa fa-edit"></i></button>
                                    <button class="btn btn-primary btn-sm submit-btn" data-id="{{ $payroll->id }}" title="Submit"><i class="fa fa-paper-plane"></i></button>
                                @endif
                                <button class="btn btn-info btn-sm payslip-btn" data-id="{{ $payroll->id }}" title="Download Payslip"><i class="fa fa-file-pdf"></i></button>
                                <a href="{{ url('manager/payroll/'.$payroll->id.'/print') }}" class="btn btn-secondary btn-sm" target="_blank" title="Print">
                                    <i class="fa fa-print"></i>
                                </a>
                            </td>
                        </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Generate Payroll Modal -->
<div class="modal fade" id="generateModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="generateForm">
                @csrf
                <div class="modal-header" style="background: linear-gradient(135deg, #1cc88a 0%, #13855c 100%);">
                    <h5 class="modal-title text-white"><i class="fas fa-plus-circle mr-2"></i> Generate Payroll</h5>
                    <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label class="font-weight-bold">Employee <span class="text-danger">*</span></label>
                        <select class="form-control" name="employee_id" required>
                            <option value="">Select Employee</option>
                            @foreach($employees as $emp)
                                <option value="{{ $emp->id }}">{{ $emp->employee_id }} - {{ $emp->name }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Month <span class="text-danger">*</span></label>
                                <input type="month" class="form-control" name="month_year" value="{{ $month }}" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Days Worked <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="days_worked" min="0" max="31" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">OT Hours</label>
                                <input type="number" step="0.5" class="form-control" name="ot_hours" min="0">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="font-weight-bold">Deductions</label>
                                <input type="number" step="0.01" class="form-control" name="deductions" min="0">
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">Remarks</label>
                        <textarea class="form-control" name="remarks" rows="2"></textarea>
                    </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-success btn-sm"><i class="fa fa-save mr-1"></i> Generate</button>
                </div>
            </form>
        </div>
    </div>
</div>

@endsection

@section('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
$(document).ready(function() {
    $('#payrollTable').DataTable({
        dom: 'Bfrtip',
        buttons: ['copy', 'csv', 'excel', 'pdf', 'print'],
        order: [[0, 'asc']]
    });

    $('#filterBtn').on('click', function() {
        window.location.href = '{{ route("manager.payroll.index") }}?month=' + $('#monthFilter').val();
    });

    $('#generateBtn').on('click', function() {
        $('#generateForm')[0].reset();
        $('#generateModal').modal('show');
    });

    $('#generateForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '{{ route("manager.payroll.generate") }}',
            type: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                if (response.success) {
                    $('#generateModal').modal('hide');
                    Swal.fire('Success', response.message, 'success').then(() => location.reload());
                }
            },
            error: function(xhr) {
                Swal.fire('Error', xhr.responseJSON?.message || 'Failed to generate', 'error');
            }
        });
    });

    $(document).on('click', '.submit-btn', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Submit for Approval?',
            icon: 'question',
            showCancelButton: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("manager/payroll") }}/' + id + '/submit',
                    type: 'POST',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Submitted!', response.message, 'success').then(() => location.reload());
                        }
                    }
                });
            }
        });
    });

    $(document).on('click', '.payslip-btn', function() {
        window.location.href = '{{ url("manager/payroll") }}/' + $(this).data('id') + '/payslip';
    });
});
</script>
@endsection
