@extends('layouts.app')
@section('title', 'Pay Slip')
@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="#">Payroll</a></li>
    <li class="breadcrumb-item active">Pay Slip</li>
@endsection

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title"><i class="bi bi-receipt me-2 text-primary"></i>Pay Slip</h1>
        <p class="page-subtitle">Filter employees, then print or email personalized pay slips with their PDF attachment.</p>
    </div>
</div>

@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif
@if(session('info'))
<div class="alert alert-info alert-dismissible d-flex gap-2 mb-3">
    <i class="bi bi-info-circle flex-shrink-0"></i><div>{{ session('info') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="card mb-4">
    <div class="card-header fw-semibold">Filters</div>
    <div class="card-body">
        <form method="GET" action="{{ route('payroll.pay-slip.index') }}" id="paySlipFilterForm">
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label fw-semibold">Period (Payroll Voucher)</label>
                    <select name="voucher_id" class="form-select payslip-auto-filter" {{ empty($voucherOptions) ? 'disabled' : '' }}>
                        @forelse($voucherOptions as $id => $label)
                        <option value="{{ $id }}" {{ (int) ($selectedVoucher?->id ?? 0) === (int) $id ? 'selected' : '' }}>{{ $label }}</option>
                        @empty
                        <option value="">No approved salary vouchers</option>
                        @endforelse
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label fw-semibold">Search</label>
                    <input type="text" name="search" class="form-control" placeholder="Name, ID, designation or department" value="{{ $listFilters['search'] }}">
                </div>
                <div class="col-md-6 col-lg">
                    <label class="form-label fw-semibold">Employee</label>
                    <select name="employee_id" class="form-select payslip-auto-filter">
                        <option value="">All employees</option>
                        @foreach($employees as $id => $label)
                        <option value="{{ $id }}" {{ (int) $listFilters['employee_id'] === (int) $id ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 col-lg">
                    <label class="form-label fw-semibold">Department</label>
                    <select name="department" class="form-select payslip-auto-filter">
                        <option value="">All departments</option>
                        @foreach($departments as $name => $label)
                        <option value="{{ $name }}" {{ $listFilters['department'] === $name ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 col-lg">
                    <label class="form-label fw-semibold">Designation</label>
                    <select name="designation" class="form-select payslip-auto-filter">
                        <option value="">All designations</option>
                        @foreach($designations as $name => $label)
                        <option value="{{ $name }}" {{ $listFilters['designation'] === $name ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 col-lg">
                    <label class="form-label fw-semibold">Project</label>
                    <select name="project" class="form-select payslip-auto-filter">
                        <option value="">All projects</option>
                        @foreach($projects as $name => $label)
                        <option value="{{ $name }}" {{ $listFilters['project'] === $name ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-6 col-lg">
                    <label class="form-label fw-semibold">Branch</label>
                    <select name="branch" class="form-select payslip-auto-filter">
                        <option value="">All branches</option>
                        @foreach($branches as $name => $label)
                        <option value="{{ $name }}" {{ $listFilters['branch'] === $name ? 'selected' : '' }}>{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
            </div>
        </form>
    </div>
</div>

@if($selectedVoucher)
<div class="card">
    <div class="card-body p-0">
        <div class="d-flex flex-wrap align-items-center gap-2 px-3 py-2 border-bottom bg-light">
            <span class="text-muted" style="font-size:13px" id="selectionSummary">
                <strong id="selectedCount">0</strong> selected ·
                <strong>{{ $rows->count() }}</strong> shown ·
                <strong>{{ $totalCount }}</strong> total
            </span>
            <div class="ms-auto d-flex flex-wrap gap-2">
                <button type="button" class="btn btn-outline-secondary btn-sm" id="selectAllBtn">Select All</button>
                <button type="button" class="btn btn-outline-secondary btn-sm" id="deselectAllBtn">Deselect All</button>
                <button type="button" class="btn btn-primary btn-sm" id="printSelectedBtn" disabled>
                    <i class="bi bi-printer me-1"></i>Print Selected (<span id="printSelectedCount">0</span>)
                </button>
                <button type="button" class="btn btn-outline-primary btn-sm" id="emailSelectedBtn" disabled>
                    <i class="bi bi-envelope me-1"></i>Email Selected (<span id="emailSelectedCount">0</span>)
                </button>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover mb-0" style="min-width:1100px">
                <thead class="table-light">
                    <tr>
                        <th class="ps-3" style="width:36px"><input type="checkbox" class="form-check-input" id="checkAllRows" aria-label="Select all"></th>
                        <th>Period</th>
                        <th>Employee ID</th>
                        <th>Name</th>
                        <th>Designation</th>
                        <th>Department</th>
                        <th>Project</th>
                        <th>Branch</th>
                        <th>Email</th>
                        <th class="text-end">Net Salary</th>
                        <th class="text-end pe-3">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($rows as $row)
                    @php $emp = $row['employee']; @endphp
                    <tr>
                        <td class="ps-3">
                            <input type="checkbox" class="form-check-input row-check" value="{{ $emp->id }}" aria-label="Select {{ $emp->display_name ?: $emp->name }}">
                        </td>
                        <td style="font-size:13px">{{ $row['period_label'] }}</td>
                        <td style="font-size:13px">{{ $emp->code ?? '—' }}</td>
                        <td class="fw-semibold" style="font-size:13.5px">{{ $emp->display_name ?: $emp->name }}</td>
                        <td style="font-size:13px">{{ $emp->designation ?? '—' }}</td>
                        <td style="font-size:13px">{{ $emp->department ?? '—' }}</td>
                        <td style="font-size:13px">{{ $emp->project ?: 'HQ' }}</td>
                        <td style="font-size:13px">{{ $emp->branch ?? '—' }}</td>
                        <td style="font-size:13px">{{ $emp->email ?? '—' }}</td>
                        <td class="text-end" style="font-size:13px">{{ \App\Helpers\NumberHelper::formatAmount((float) $row['net_salary'], auth()->user()->company_id) }}</td>
                        <td class="text-end pe-3">
                            <a href="{{ route('payroll.pay-slip.print', ['payrollVoucher' => $selectedVoucher->id, 'employee' => $emp->id]) }}"
                               target="_blank"
                               class="btn btn-link btn-sm p-0">Print</a>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="11" class="text-center py-5 text-muted">
                            <i class="bi bi-receipt display-5 d-block mb-2"></i>
                            No employees match the selected filters.
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
</div>

<form method="POST" action="{{ route('payroll.pay-slip.email') }}" id="emailForm" class="d-none">
    @csrf
    <input type="hidden" name="voucher_id" value="{{ $selectedVoucher->id }}">
</form>
@else
<div class="card">
    <div class="card-body text-center py-5 text-muted">
        <i class="bi bi-receipt display-5 d-block mb-2"></i>
        <p class="mb-0">Approve a salary sheet voucher first to generate pay slips.</p>
    </div>
</div>
@endif
@endsection

@push('scripts')
<script>
(function () {
    const form = document.getElementById('paySlipFilterForm');
    form?.querySelectorAll('.payslip-auto-filter').forEach(function (el) {
        el.addEventListener('change', function () { form.submit(); });
    });

    const checks = () => Array.from(document.querySelectorAll('.row-check'));
    const selected = () => checks().filter(function (c) { return c.checked; });
    const printBase = @json(route('payroll.pay-slip.print', ['payrollVoucher' => $selectedVoucher?->id ?? 0]));
    const voucherId = @json($selectedVoucher?->id);

    function updateSelectionUi() {
        const count = selected().length;
        document.getElementById('selectedCount').textContent = count;
        document.getElementById('printSelectedCount').textContent = count;
        document.getElementById('emailSelectedCount').textContent = count;
        document.getElementById('printSelectedBtn').disabled = count === 0;
        document.getElementById('emailSelectedBtn').disabled = count === 0;
        const all = checks();
        const checkAll = document.getElementById('checkAllRows');
        if (checkAll) {
            checkAll.checked = all.length > 0 && count === all.length;
            checkAll.indeterminate = count > 0 && count < all.length;
        }
    }

    document.getElementById('checkAllRows')?.addEventListener('change', function () {
        checks().forEach(function (c) { c.checked = this.checked; }.bind(this));
        updateSelectionUi();
    });

    checks().forEach(function (c) {
        c.addEventListener('change', updateSelectionUi);
    });

    document.getElementById('selectAllBtn')?.addEventListener('click', function () {
        checks().forEach(function (c) { c.checked = true; });
        updateSelectionUi();
    });

    document.getElementById('deselectAllBtn')?.addEventListener('click', function () {
        checks().forEach(function (c) { c.checked = false; });
        updateSelectionUi();
    });

    document.getElementById('printSelectedBtn')?.addEventListener('click', function () {
        if (!voucherId || selected().length === 0) return;
        const params = new URLSearchParams();
        selected().forEach(function (c) { params.append('employees[]', c.value); });
        window.open(printBase + '?' + params.toString(), '_blank');
    });

    document.getElementById('emailSelectedBtn')?.addEventListener('click', function () {
        const emailForm = document.getElementById('emailForm');
        if (!emailForm || selected().length === 0) return;
        emailForm.querySelectorAll('input[name="employee_ids[]"]').forEach(function (el) { el.remove(); });
        selected().forEach(function (c) {
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'employee_ids[]';
            input.value = c.value;
            emailForm.appendChild(input);
        });
        emailForm.submit();
    });

    updateSelectionUi();
})();
</script>
@endpush
