@extends('layouts.dashboard.superadminapp')

@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>
    <div>
        <a href="{{ route('superadmin.salary-structure.index') }}" class="btn btn-outline-secondary btn-sm mr-2">
            <i class="fas fa-cogs mr-1"></i> Salary Structure
        </a>
    </div>
</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 Approval</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 & Actions -->
<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 & Actions</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-3">
                <button type="button" class="btn btn-info btn-sm" id="bulkGenerateBtn">
                    <i class="fas fa-users mr-1"></i> Bulk Generate
                </button>
                <button type="button" class="btn btn-warning btn-sm" id="bulkApproveBtn">
                    <i class="fas fa-check-double mr-1"></i> Bulk Approve
                </button>
            </div>
            <div class="col-md-3 text-right">
                <div class="small text-muted">
                    Total Gross: <strong class="text-primary">{{ number_format($stats['total_gross'], 2) }}</strong><br>
                    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><input type="checkbox" id="selectAll"></th>
                        <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="150" class="text-center">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach($payrolls as $payroll)
                        <tr id="row-{{ $payroll->id }}">
                            <td><input type="checkbox" class="row-checkbox" value="{{ $payroll->id }}"></td>
                            <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
                                    @default <span class="badge badge-secondary">{{ $payroll->status }}</span>
                                @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
                                @if($payroll->status == 'Pending')
                                    <button class="btn btn-success btn-sm approve-btn" data-id="{{ $payroll->id }}" title="Approve"><i class="fa fa-check"></i></button>
                                @endif
                                @if($payroll->status == 'Approved')
                                    <button class="btn btn-success btn-sm paid-btn" data-id="{{ $payroll->id }}" title="Mark Paid"><i class="fa fa-money-bill"></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>
                                @if($payroll->status != 'Paid')
                                    <button class="btn btn-danger btn-sm delete-btn" data-id="{{ $payroll->id }}" title="Delete"><i class="fa fa-trash"></i></button>
                                @endif
                            </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" id="gen_employee_id" 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" id="gen_month_year" 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" id="gen_days_worked" name="days_worked" min="0" max="31" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-4">
                            <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-4">
                            <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 class="col-md-4">
                            <div class="form-group">
                                <label class="font-weight-bold">Bonus</label>
                                <input type="number" step="0.01" class="form-control" name="bonus" 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>

<!-- Mark Paid Modal -->
<div class="modal fade" id="paidModal" tabindex="-1" role="dialog">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <form id="paidForm">
                @csrf
                <input type="hidden" id="paid_payroll_id">
                <div class="modal-header bg-success text-white">
                    <h5 class="modal-title"><i class="fas fa-money-bill-wave mr-2"></i> Mark as Paid</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">Payment Date <span class="text-danger">*</span></label>
                        <input type="date" class="form-control" name="payment_date" value="{{ date('Y-m-d') }}" required>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">Payment Mode <span class="text-danger">*</span></label>
                        <select class="form-control" name="payment_mode" required>
                            <option value="Bank Transfer">Bank Transfer</option>
                            <option value="Cash">Cash</option>
                            <option value="Cheque">Cheque</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="font-weight-bold">Reference Number</label>
                        <input type="text" class="form-control" name="reference_number" placeholder="Transaction ID / Cheque No.">
                    </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-check mr-1"></i> Mark Paid</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: [[1, 'asc']]
    });

    // Select All
    $('#selectAll').on('change', function() {
        $('.row-checkbox').prop('checked', $(this).is(':checked'));
    });

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

    // Generate Modal
    $('#generateBtn').on('click', function() {
        $('#generateForm')[0].reset();
        $('#gen_month_year').val('{{ $month }}');
        $('#generateModal').modal('show');
    });

    // Generate Form Submit
    $('#generateForm').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url: '{{ route("superadmin.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');
            }
        });
    });

    // Bulk Generate
    $('#bulkGenerateBtn').on('click', function() {
        const month = $('#monthFilter').val();
        Swal.fire({
            title: 'Bulk Generate Payroll?',
            text: 'This will generate payroll for all active employees for ' + month,
            icon: 'question',
            showCancelButton: true,
            confirmButtonText: 'Yes, Generate'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ route("superadmin.payroll.bulk-generate") }}',
                    type: 'POST',
                    data: { _token: '{{ csrf_token() }}', month_year: month },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Success', response.message, 'success').then(() => location.reload());
                        }
                    },
                    error: function(xhr) {
                        Swal.fire('Error', xhr.responseJSON?.message || 'Failed', 'error');
                    }
                });
            }
        });
    });

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

    // Approve
    $(document).on('click', '.approve-btn', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Approve Payroll?',
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#1cc88a',
            confirmButtonText: 'Yes, Approve'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("superadmin/payroll") }}/' + id + '/approve',
                    type: 'POST',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Approved!', response.message, 'success').then(() => location.reload());
                        }
                    }
                });
            }
        });
    });

    // Bulk Approve
    $('#bulkApproveBtn').on('click', function() {
        const ids = [];
        $('.row-checkbox:checked').each(function() {
            ids.push($(this).val());
        });
        if (ids.length === 0) {
            Swal.fire('Warning', 'Please select payroll records to approve', 'warning');
            return;
        }
        $.ajax({
            url: '{{ route("superadmin.payroll.bulk-approve") }}',
            type: 'POST',
            data: { _token: '{{ csrf_token() }}', ids: ids },
            success: function(response) {
                if (response.success) {
                    Swal.fire('Success', response.message, 'success').then(() => location.reload());
                }
            }
        });
    });

    // Mark Paid Modal
    $(document).on('click', '.paid-btn', function() {
        $('#paid_payroll_id').val($(this).data('id'));
        $('#paidModal').modal('show');
    });

    // Mark Paid Form
    $('#paidForm').on('submit', function(e) {
        e.preventDefault();
        const id = $('#paid_payroll_id').val();
        $.ajax({
            url: '{{ url("superadmin/payroll") }}/' + id + '/mark-paid',
            type: 'POST',
            data: $(this).serialize(),
            success: function(response) {
                if (response.success) {
                    $('#paidModal').modal('hide');
                    Swal.fire('Success', response.message, 'success').then(() => location.reload());
                }
            }
        });
    });

    // Download Payslip
    $(document).on('click', '.payslip-btn', function() {
        const id = $(this).data('id');
        window.location.href = '{{ url("superadmin/payroll") }}/' + id + '/payslip';
    });

    // Delete
    $(document).on('click', '.delete-btn', function() {
        const id = $(this).data('id');
        Swal.fire({
            title: 'Delete Payroll?',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#e74a3b',
            confirmButtonText: 'Yes, Delete'
        }).then((result) => {
            if (result.isConfirmed) {
                $.ajax({
                    url: '{{ url("superadmin/payroll") }}/' + id,
                    type: 'DELETE',
                    data: { _token: '{{ csrf_token() }}' },
                    success: function(response) {
                        if (response.success) {
                            Swal.fire('Deleted!', response.message, 'success');
                            $('#row-' + id).fadeOut();
                        }
                    }
                });
            }
        });
    });
});
</script>
@endsection
