<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppSetting;
use App\Models\Branch;
use App\Models\Customer;
use App\Models\PaymentMethod;
use App\Models\Product;
use App\Models\SalesType;
use App\Models\User;
use App\Services\TransactionService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Exception;

class POSController extends Controller
{
    protected $transactionService;

    public function __construct(TransactionService $transactionService)
    {
        $this->transactionService = $transactionService;
    }
    /**
     * Authenticate Cashier/User via Two-Step Verification.
     */
    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|string',
            'pin' => 'nullable|string|size:6',
            'branch_id' => 'nullable|exists:branches,id',
        ]);

        $user = User::where('email', $request->email)->where('is_active', true)->first();
        if (!$user || !Hash::check($request->password, $user->password)) {
            return response()->json(['message' => 'Email atau Password salah.'], 401);
        }

        if (!$request->pin) {
            return response()->json([
                'requires_pin' => true,
                'message' => 'Kredensial valid. Masukkan PIN Kasir Anda.',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                ],
            ]);
        }

        if ($user->pin !== $request->pin) {
            return response()->json(['message' => 'PIN Kasir salah.'], 401);
        }

        $branches = $this->getAccessibleBranches($user);

        if ($branches->isEmpty()) {
            return response()->json(['message' => 'Akun ini belum memiliki akses cabang. Hubungi admin.'], 403);
        }

        if (!$request->branch_id && $branches->count() > 1) {
            return response()->json([
                'requires_branch_selection' => true,
                'message' => 'Pilih cabang yang ingin diakses.',
                'user' => [
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'roles' => $user->getRoleNames(),
                ],
                'branches' => $branches,
            ]);
        }

        $selectedBranch = $this->resolveSelectedBranch($user, $request->branch_id, $branches);

        if (!$selectedBranch) {
            return response()->json(['message' => 'Cabang yang dipilih tidak ada di hak akses akun ini.'], 403);
        }

        // Generate Sanctum Token
        $token = $user->createToken('pos-token')->plainTextToken;

        return response()->json([
            'token' => $token,
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'branch_id' => $selectedBranch['id'],
                'branch_name' => $selectedBranch['name'],
                'branch_address' => $selectedBranch['address'] ?? null,
                'branch_whatsapp' => $selectedBranch['whatsapp'] ?? null,
                'roles' => $user->getRoleNames(),
            ]
        ]);
    }

    protected function getAccessibleBranches(User $user)
    {
        $branches = $user->branches()
            ->select('branches.id', 'branches.name', 'branches.address', 'branches.whatsapp')
            ->orderBy('branches.name')
            ->get()
            ->map(function ($branch) {
                return [
                    'id' => $branch->id,
                    'name' => $branch->name,
                    'address' => $branch->address,
                    'whatsapp' => $branch->whatsapp,
                ];
            });

        if ($branches->isEmpty() && $user->branch) {
            $branches = collect([
                [
                    'id' => $user->branch->id,
                    'name' => $user->branch->name,
                    'address' => $user->branch->address,
                    'whatsapp' => $user->branch->whatsapp,
                ],
            ]);
        }

        return $branches->values();
    }

    protected function resolveSelectedBranch(User $user, $branchId, $branches): ?array
    {
        $requestedBranchId = (int) $branchId;

        if ($requestedBranchId) {
            $selected = $branches->firstWhere('id', $requestedBranchId);
            if ($selected) {
                return $selected;
            }
            return null;
        }

        if ($user->branch_id) {
            $selected = $branches->firstWhere('id', (int) $user->branch_id);
            if ($selected) {
                return $selected;
            }
        }

        return $branches->first();
    }

    /**
     * Retrieve products list with branch-specific overrides.
     */
    public function products(Request $request)
    {
        $branchId = $this->resolveBranchId($request);
        $defaultSalesType = SalesType::where('is_default', true)->first() ?? SalesType::first();
        $salesTypeId = $request->sales_type_id ?? ($defaultSalesType ? $defaultSalesType->id : null);

        $products = Product::where('is_active', true)
            ->with(['category', 'prices', 'variants'])
            ->get()
            ->map(function ($product) use ($branchId, $salesTypeId) {
                $variants = $product->variants
                    ->map(function ($variant) use ($salesTypeId) {
                        $salesType = SalesType::find($salesTypeId);
                        $defaultSalesType = SalesType::where('is_default', true)->first();
                        
                        $variantPrice = (float) $variant->base_price;
                        
                        // If it's a non-default sales type and has a markup percentage, apply it
                        if ($defaultSalesType && $salesTypeId != $defaultSalesType->id && $salesType && $salesType->markup_percentage > 0) {
                            $variantPrice = $variantPrice * (1 + ((float)$salesType->markup_percentage / 100));
                        }
                        
                        return [
                            'id' => $variant->id,
                            'name' => $variant->name,
                            'base_price' => (float) $variantPrice,
                        ];
                    })
                    ->values();
                return [
                    'id' => $product->id,
                    'name' => $product->name,
                    'category' => $product->category->name,
                    'category_id' => $product->category_id,
                    'price' => (float)$product->getPriceFor($branchId, $salesTypeId),
                    'base_price' => (float)$product->price,
                    'variant' => $variants->isNotEmpty() ? $variants->pluck('name')->implode(', ') : $product->variant,
                    'variants' => $variants,
                    'barcode' => $product->barcode,
                ];
            });

        return response()->json($products);
    }

    /**
     * Retrieve customer directory.
     */
    public function customers()
    {
        $customers = Customer::orderBy('name')->get();
        return response()->json($customers);
    }

    /**
     * Retrieve active payment methods.
     */
    public function paymentMethods()
    {
        $methods = PaymentMethod::all();
        return response()->json($methods);
    }

    /**
     * Retrieve all sales types.
     */
    public function salesTypes()
    {
        $salesTypes = SalesType::with('paymentMethods')->get();
        return response()->json($salesTypes);
    }

    /**
     * Get global POS settings.
     */
    public function settings()
    {
        return response()->json([
            'tax_rate' => (float) (AppSetting::where('key', 'tax_rate')->value('value') ?? 11),
            'tax_enabled' => (bool) (AppSetting::where('key', 'tax_enabled')->value('value') ?? true),
            'pb1_rate' => (float) (AppSetting::where('key', 'pb1_rate')->value('value') ?? 10),
            'pb1_enabled' => (bool) (AppSetting::where('key', 'pb1_enabled')->value('value') ?? false),
            'service_charge_rate' => (float) (AppSetting::where('key', 'service_charge_rate')->value('value') ?? 5),
            'service_charge_enabled' => (bool) (AppSetting::where('key', 'service_charge_enabled')->value('value') ?? true),
            'company_name' => AppSetting::where('key', 'company_name')->value('value') ?? 'Bebek Mba Reina',
            'company_phone' => AppSetting::where('key', 'company_phone')->value('value') ?? '',
            'company_logo' => AppSetting::where('key', 'company_logo')->value('value') ? asset('storage/' . AppSetting::where('key', 'company_logo')->value('value')) : null,
            'table_number_enabled' => (bool) (AppSetting::where('key', 'table_number_enabled')->value('value') ?? true),
            'printer_settings' => json_decode(AppSetting::where('key', 'pos_printer_settings')->value('value') ?? '{}', true),
        ]);
    }

    /**
     * Save POS printer / receipt settings to database.
     */
    public function saveSettings(Request $request)
    {
        $request->validate([
            'printer_settings' => 'required|array',
        ]);

        AppSetting::updateOrCreate(
            ['key' => 'pos_printer_settings'],
            ['value' => json_encode($request->printer_settings)]
        );

        return response()->json([
            'message' => 'Pengaturan struk & printer berhasil disimpan di server!',
            'printer_settings' => $request->printer_settings
        ]);
    }

    /**
     * Place POS order / sale transaction.
     */
    public function storeSale(Request $request)
    {
        $request->validate([
            'sales_type_id' => 'required|exists:sales_types,id',
            'customer_id' => 'nullable|exists:customers,id',
            'payment_method_id' => 'nullable|exists:payment_methods,id',
            'paid_amount' => 'required|numeric|min:0',
            'discount_amount' => 'nullable|numeric|min:0',
            'service_charge' => 'nullable|numeric|min:0',
            'table_number' => 'nullable|string',
            'items' => 'required|array|min:1',
            'items.*.product_id' => 'required|exists:products,id',
            'items.*.variant_name' => 'nullable|string|max:100',
            'items.*.price' => 'required|numeric|min:0',
            'items.*.quantity' => 'required|integer|min:1',
            'items.*.discount_amount' => 'nullable|numeric|min:0',
            'items.*.tax_amount' => 'nullable|numeric|min:0',
            'preorder_date' => 'nullable|date',
            'fulfillment_status' => 'nullable|string|in:pending,preparing,ready,fulfilled',
            'unpaid_sale_id' => 'nullable|string|exists:sales,id',
        ]);

        $branchId = $this->resolveBranchId($request);
        if (!$branchId) {
            return response()->json(['message' => 'Silakan pilih cabang akses terlebih dahulu.'], 400);
        }

        $data = $request->all();
        $data['branch_id'] = $branchId;
        $data['source'] = 'pos';

        try {
            $sale = $this->transactionService->createSale($data);
            return response()->json([
                'message' => 'Transaksi berhasil disimpan!',
                'sale' => $sale->load(['items.product', 'customer', 'paymentMethod', 'salesType']),
            ], 201);
        } catch (Exception $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    /**
     * Update preorder fulfillment status.
     */
    public function updateFulfillmentStatus(Request $request, $id)
    {
        $request->validate([
            'fulfillment_status' => 'required|string|in:pending,preparing,ready,fulfilled',
        ]);

        try {
            $sale = \App\Models\Sale::withoutGlobalScopes()->findOrFail($id);
            $sale->fulfillment_status = $request->fulfillment_status;
            $sale->save();

            return response()->json([
                'message' => 'Status fulfillment pesanan berhasil diperbarui!',
                'sale' => $sale->load(['items.product', 'customer', 'paymentMethod', 'salesType']),
            ]);
        } catch (Exception $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    /**
     * Cancel/Void transaction and reverse general ledger + customer balance.
     */
    public function voidSale(Request $request, $id)
    {
        try {
            $sale = \Illuminate\Support\Facades\DB::transaction(function () use ($id) {
                $sale = \App\Models\Sale::withoutGlobalScopes()->findOrFail($id);

                if ($sale->status === 'cancelled') {
                    throw new Exception('Transaksi sudah dibatalkan sebelumnya.');
                }

                // Restore Customer Balance/Debt/Deposit if applicable
                if ($sale->customer_id) {
                    $customer = \App\Models\Customer::find($sale->customer_id);
                    if ($customer) {
                        $paymentMethod = $sale->paymentMethod;
                        if ($paymentMethod && str_contains(strtolower($paymentMethod->name), 'deposit')) {
                            // Refund deposit
                            $customer->increment('balance', (float)$sale->grand_total);
                        } elseif ($sale->payment_status !== 'paid') {
                            // Restore debt amount
                            $debtAmount = (float)$sale->grand_total - (float)$sale->paid_amount;
                            if ($debtAmount > 0) {
                                $customer->increment('balance', $debtAmount);
                            }
                        }
                    }
                }

                // Delete associated GL Journal Entries
                \App\Models\JournalEntry::where('reference_number', $sale->invoice_number)->delete();

                // Update Status to cancelled
                $sale->status = 'cancelled';
                $sale->save();

                return $sale;
            });

            return response()->json([
                'message' => 'Transaksi berhasil di-VOID!',
                'sale' => $sale->load(['items.product', 'customer', 'paymentMethod', 'salesType'])
            ]);
        } catch (Exception $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    /**
     * Get branch transaction history.
     */
    public function history(Request $request)
    {
        $branchId = $this->resolveBranchId($request);
        $sales = \App\Models\Sale::withoutGlobalScopes()
            ->where('branch_id', $branchId)
            ->with(['items.product', 'customer', 'paymentMethod', 'salesType'])
            ->orderBy('created_at', 'desc')
            ->get();
        return response()->json($sales);
    }

    /**
     * Get saved orders that are truly unpaid (not partially paid).
     */
    public function unpaid(Request $request)
    {
        $branchId = $this->resolveBranchId($request);
        $sales = \App\Models\Sale::withoutGlobalScopes()
            ->where('branch_id', $branchId)
            ->where('payment_status', 'unpaid')
            ->with(['items.product', 'customer', 'salesType'])
            ->orderBy('created_at', 'desc')
            ->get();
        return response()->json($sales);
    }

    /**
     * Merge multiple unpaid bills into a single invoice.
     */
    public function mergeSales(Request $request)
    {
        $request->validate([
            'sale_ids' => 'required|array|min:2',
            'sale_ids.*' => 'exists:sales,id',
        ]);

        try {
            $mergedSale = \Illuminate\Support\Facades\DB::transaction(function() use ($request) {
                $sales = \App\Models\Sale::withoutGlobalScopes()->whereIn('id', $request->sale_ids)->with('items')->get();
                $first = $sales->first();
                
                // Consolidate items
                $consolidatedItems = [];
                foreach ($sales as $s) {
                    foreach ($s->items as $item) {
                        $pId = $item->product_id;
                        if (isset($consolidatedItems[$pId])) {
                            $consolidatedItems[$pId]['quantity'] += $item->quantity;
                        } else {
                            $consolidatedItems[$pId] = [
                                'product_id' => $pId,
                                'price' => (float)$item->price,
                                'quantity' => (int)$item->quantity,
                                'tax_amount' => (float)$item->tax_amount,
                                'discount_amount' => (float)$item->discount_amount,
                            ];
                        }
                    }
                }

                // Create the new combined sale
                $newSaleData = [
                    'branch_id' => $first->branch_id,
                    'sales_type_id' => $first->sales_type_id,
                    'customer_id' => $first->customer_id,
                    'table_number' => 'Merge Bill',
                    'paid_amount' => 0.00,
                    'discount_amount' => $sales->sum('discount_amount'),
                    'service_charge' => $sales->sum('service_charge'),
                    'items' => array_values($consolidatedItems),
                    'source' => 'pos',
                ];

                $merged = $this->transactionService->createSale($newSaleData);

                // Delete old merged draft/unpaid records
                \App\Models\Sale::withoutGlobalScopes()->whereIn('id', $request->sale_ids)->delete();

                return $merged;
            });

            return response()->json([
                'message' => 'Bill berhasil digabungkan!',
                'sale' => $mergedSale->load(['items.product', 'customer', 'salesType']),
            ]);
        } catch (Exception $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    /**
     * Cashier records daily small operational expenses.
     */
    public function storeExpense(Request $request)
    {
        $request->validate([
            'amount' => 'required|numeric|min:1',
            'expense_account_id' => 'required|exists:chart_of_accounts,id',
            'payment_method_id' => 'required|exists:payment_methods,id',
            'description' => 'required|string',
            'recipient' => 'nullable|string',
            'employee_id' => 'nullable|exists:users,id',
            'supplier_id' => 'nullable|exists:suppliers,id',
        ]);

        $coa = \App\Models\ChartOfAccount::find($request->expense_account_id);
        $isKasbon = false;
        if ($coa) {
            $code = (string) $coa->code;
            $name = strtolower((string) $coa->name);
            if (str_starts_with($code, '116') || $code === '61101' || str_contains($name, 'kasbon')) {
                $isKasbon = true;
            }
        }

        if ($isKasbon) {
            if (!$request->employee_id) {
                return response()->json(['message' => 'Jika kategori pengeluaran KASBON, Penerima Karyawan wajib diisi.'], 422);
            }
        } else {
            if (!$request->supplier_id) {
                return response()->json(['message' => 'Untuk pengeluaran operasional harian, Penerima Vendor wajib diisi.'], 422);
            }
        }

        $branchId = $this->resolveBranchId($request);
        if (!$branchId) {
            return response()->json(['message' => 'Silakan pilih cabang akses terlebih dahulu.'], 400);
        }

        $data = $request->all();
        $data['branch_id'] = $branchId;

        // If employee is selected, automatically populate recipient with the employee's name for consistency
        if ($request->employee_id) {
            $emp = User::find($request->employee_id);
            if ($emp) {
                $data['recipient'] = $emp->name;
            }
        } elseif ($request->supplier_id) {
            $sup = \App\Models\Supplier::find($request->supplier_id);
            if ($sup) {
                $data['recipient'] = $sup->name;
            }
        }

        try {
            $expense = $this->transactionService->createExpense($data);
            return response()->json([
                'message' => 'Pengeluaran kasir berhasil dicatat!',
                'expense' => $expense,
            ], 201);
        } catch (Exception $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }
    }

    /**
     * Quick register customer from POS terminal.
     */
    public function storeCustomer(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string',
        ]);

        $customer = Customer::create($request->all());

        return response()->json([
            'message' => 'Pelanggan berhasil didaftarkan!',
            'customer' => $customer,
        ], 201);
    }

    /**
     * Update customer details from POS terminal.
     */
    public function updateCustomer(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'phone' => 'nullable|string|max:20',
            'address' => 'nullable|string',
        ]);

        $customer = Customer::findOrFail($id);
        $customer->update($request->all());

        return response()->json([
            'message' => 'Pelanggan berhasil diperbarui!',
            'customer' => $customer,
        ]);
    }

    /**
     * Delete customer from POS terminal.
     */
    public function destroyCustomer($id)
    {
        try {
            $customer = Customer::findOrFail($id);
            
            // Prevent deleting Cash/Default customer if any exists
            if ($id == 1 || str_contains(strtolower($customer->name), 'umum') || str_contains(strtolower($customer->name), 'cash')) {
                return response()->json(['message' => 'Pelanggan default/umum tidak boleh dihapus!'], 422);
            }

            // Prevent deleting customer with transaction history
            if ($customer->sales()->exists()) {
                return response()->json(['message' => 'Pelanggan tidak dapat dihapus karena sudah memiliki riwayat transaksi/penjualan.'], 422);
            }

            $customer->delete();

            return response()->json([
                'message' => 'Pelanggan berhasil dihapus!',
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'message' => 'Gagal menghapus pelanggan: ' . $e->getMessage(),
            ], 422);
        }
    }

    /**
     * Get branch-applicable active discounts.
     */
    public function discounts(Request $request)
    {
        $branchId = $this->resolveBranchId($request);
        $discounts = \App\Models\Discount::where('is_active', true)
            ->where(function($q) use ($branchId) {
                $q->whereNull('branch_id')->orWhere('branch_id', $branchId);
            })
            ->get();
        return response()->json($discounts);
    }

    /**
     * Get accessible branches for the authenticated cashier user.
     */
    public function myBranches(Request $request)
    {
        $user = $request->user();
        $branches = $this->getAccessibleBranches($user);
        return response()->json($branches);
    }

    public function coas()
    {
        $coas = \App\Models\ChartOfAccount::where('type', 'Expense')
            ->where('is_active', true)
            ->orderBy('code', 'asc')
            ->get();
        return response()->json($coas);
    }

    /**
     * Get active employees (users) for the branch or globally.
     */
    public function employees(Request $request)
    {
        $branchId = $this->resolveBranchId($request);
        
        $query = User::where('is_active', true);
        if ($branchId) {
            $query->where(function($q) use ($branchId) {
                $q->where('branch_id', $branchId)->orWhereNull('branch_id');
            });
        }
        
        $employees = $query->select('id', 'name')->get();
        return response()->json($employees);
    }

    /**
     * Get active suppliers (vendors) for POS.
     */
    public function suppliers()
    {
        $suppliers = \App\Models\Supplier::select('id', 'name')->get();
        return response()->json($suppliers);
    }

    protected function resolveBranchId(Request $request): ?int
    {
        $user = $request->user();
        $requestedBranchId = (int) ($request->header('X-Branch-Id') ?? $request->branch_id ?? 0);
        $branches = $this->getAccessibleBranches($user);

        if ($branches->isEmpty()) {
            return $user->branch_id ? (int) $user->branch_id : null;
        }

        if ($requestedBranchId) {
            $allowed = $branches->firstWhere('id', $requestedBranchId);
            return $allowed ? (int) $allowed['id'] : null;
        }

        if ($user->branch_id) {
            $allowed = $branches->firstWhere('id', (int) $user->branch_id);
            if ($allowed) {
                return (int) $allowed['id'];
            }
        }

        $first = $branches->first();
        return $first ? (int) $first['id'] : null;
    }

    /**
     * Retrieve attendance recap, overtimes, kasbon totals, and payroll slip for the authenticated staff user.
     */
    public function myStaffPortal(Request $request)
    {
        $user = $request->user();
        $month = (int) ($request->month ?? date('m'));
        $year = (int) ($request->year ?? date('Y'));

        // Query attendance records for this month & year
        $attendances = \App\Models\Attendance::where('user_id', $user->id)
            ->whereMonth('date', $month)
            ->whereYear('date', $year)
            ->orderBy('date', 'desc')
            ->get();

        $presentCount = $attendances->where('status', 'present')->count();
        $sickCount = $attendances->where('status', 'sick')->count();
        $leaveCount = $attendances->where('status', 'leave')->count();
        $alphaCount = $attendances->where('status', 'alpha')->count();

        // Overtime stats
        $overtimeHours = \App\Models\Overtime::where('user_id', $user->id)
            ->whereMonth('date', $month)
            ->whereYear('date', $year)
            ->sum('hours');

        $overtimePay = \App\Models\Overtime::where('user_id', $user->id)
            ->whereMonth('date', $month)
            ->whereYear('date', $year)
            ->sum('total_amount');

        // Kasbon total
        $kasbonTotal = (float)\App\Models\Expense::where('employee_id', $user->id)
            ->whereMonth('created_at', $month)
            ->whereYear('created_at', $year)
            ->where(function($q) {
                $q->whereHas('expenseAccount', function($sub) {
                    $sub->where('code', 'like', '116%')
                        ->orWhere('code', '61101')
                        ->orWhere('name', 'like', '%kasbon%');
                })->orWhere('description', 'like', '%kasbon%');
            })
            ->sum('amount');

        // Payroll info for this month if exists
        $payroll = \App\Models\Payroll::where('user_id', $user->id)
            ->where('month', $month)
            ->where('year', $year)
            ->first();

        return response()->json([
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'position' => $user->salary->position ?? 'Karyawan',
            ],
            'period' => [
                'month' => $month,
                'year' => $year,
            ],
            'summary' => [
                'present' => $presentCount,
                'sick' => $sickCount,
                'leave' => $leaveCount,
                'alpha' => $alphaCount,
                'overtime_hours' => (float) $overtimeHours,
                'overtime_pay' => (float) $overtimePay,
                'kasbon_total' => $kasbonTotal,
            ],
            'attendances' => $attendances->map(function($att) {
                return [
                    'date' => $att->date instanceof \Carbon\Carbon ? $att->date->format('Y-m-d') : date('Y-m-d', strtotime($att->date)),
                    'status' => $att->status,
                    'check_in' => $att->check_in ? ($att->check_in instanceof \Carbon\Carbon ? $att->check_in->format('H:i') : date('H:i', strtotime($att->check_in))) : null,
                    'check_out' => $att->check_out ? ($att->check_out instanceof \Carbon\Carbon ? $att->check_out->format('H:i') : date('H:i', strtotime($att->check_out))) : null,
                    'notes' => $att->notes,
                ];
            }),
            'payroll' => $payroll ? [
                'payroll_number' => $payroll->payroll_number,
                'basic_salary' => (float) $payroll->basic_salary,
                'allowance_total' => (float) $payroll->allowance_total,
                'deduction_total' => (float) $payroll->deduction_total,
                'net_salary' => (float) $payroll->net_salary,
                'status' => $payroll->status,
                'slip_png' => $payroll->payroll_number ? asset("storage/slips/slip_{$payroll->payroll_number}.png") : null,
            ] : null,
        ]);
    }
}
