<?php

namespace App\Http\Controllers;

use App\Http\Requests\PurchaseOrder\StorePurchaseOrderRequest;
use App\Http\Requests\PurchaseOrder\UpdatePurchaseOrderRequest;
use App\Models\Account;
use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use App\Models\PurchaseRequest;
use App\Models\Uom;
use App\Services\PurchaseOrderService;
use App\Traits\LogsActivity;
use Illuminate\Contracts\View\View;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Yajra\DataTables\Facades\DataTables;

class PurchaseOrderController extends Controller
{
    use LogsActivity;
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $query = PurchaseOrder::query()
                ->with(['supplier'])
                ->join('purchase_requests', 'purchase_requests.id', '=', 'purchase_orders.purchase_request_id')
                // ->leftJoin('accounts', 'accounts.id', '=', 'purchase_orders.contact_id')
                ->leftJoin('accounts as vendor', 'vendor.id', '=', 'purchase_orders.contact_id')
                ->leftJoin('purchase_order_items', 'purchase_orders.id', '=', 'purchase_order_items.purchase_order_id')
                // ->select(
                //     'purchase_orders.id',
                //     'purchase_orders.po_number',
                //     'purchase_orders.purchase_request_id',
                //     'purchase_orders.supplier_id',
                //     'purchase_orders.status',
                //     'purchase_orders.total_amount',
                //     'purchase_orders.payment_status',
                //     'purchase_requests.pr_number',
                //     'accounts.name as vendor_name'
                // )
                ->select(
                    'purchase_orders.id',
                    'purchase_orders.po_number',
                    'purchase_orders.purchase_request_id',
                    'purchase_orders.supplier_id',
                    'purchase_orders.status',
                    'purchase_orders.total_amount',
                    'purchase_orders.payment_status',
                    'purchase_requests.pr_number',
                    'vendor.name as vendor_name'
                )

                ->selectRaw('COUNT(DISTINCT purchase_order_items.id) as items_count')
                ->selectRaw('DATE_FORMAT(purchase_orders.expected_date, "%Y-%m-%d") as formatted_expected_date')
                ->selectRaw('DATE_FORMAT(purchase_orders.created_at, "%Y-%m-%d %H:%i:%s") as formatted_created_at')
                ->groupBy(
                    'purchase_orders.id',
                    'purchase_orders.po_number',
                    'purchase_orders.purchase_request_id',
                    'purchase_orders.supplier_id',
                    'purchase_orders.expected_date',
                    'purchase_orders.status',
                    'purchase_orders.total_amount',
                    'purchase_orders.payment_status',
                    'purchase_orders.created_at',
                    'purchase_orders.updated_at',
                    'purchase_requests.pr_number',
                    // 'accounts.name'
                    'vendor.name'
                );

            // Filters
            // $query->where('purchase_orders.status', 'open');

            // if ($request->filled('vendor_id')) {
            //     $query->where('supplier_id', $request->string('vendor_id'));
            // }
            if ($request->filled('vendor_id')) {
                $query->where('contact_id', $request->string('vendor_id'));
            }
             if ($request->filled('status')) {
                $query->where('purchase_orders.status', $request->string('status'));
            }
            // if ($request->filled('status')) {
            // 	$query->where('status', $request->string('status'));
            // }
            if ($request->filled('payment_status')) {
                $query->where('payment_status', $request->string('payment_status'));
            }

            if ($request->filled('date_from') && $request->filled('date_to')) {
                $query->whereBetween('purchase_orders.created_at', [
                    $request->string('date_from') . ' 00:00:00',
                    $request->string('date_to') . ' 23:59:59'
                ]);
            } elseif ($request->filled('date_from')) {
                $query->whereDate('purchase_orders.created_at', '>=', $request->string('date_from'));
            } elseif ($request->filled('date_to')) {
                $query->whereDate('purchase_orders.created_at', '<=', $request->string('date_to'));
            }

            // if ($request->filled('date_from') && $request->filled('date_to')) {
            // 	$query->whereBetween('order_date', [$request->string('date_from'), $request->string('date_to')]);
            // }

            return DataTables::of($query)
                ->editColumn('vendor_name', function (PurchaseOrder $po) {
                    return $po->vendor_name ?: '-';
                })
                // ->editColumn('order_date', function (PurchaseOrder $po) {
                // 	return $po->order_date->format('Y-m-d');
                // })
                ->editColumn('status', function (PurchaseOrder $po) {
                    // $statusColors = [
                    //     'open'               => 'secondary',
                    //     'confirmed'          => 'primary',
                    //     'partially_received' => 'warning',
                    //     'completed'          => 'success',
                    //     'cancelled'          => 'danger',
                    // ];
                    $statusColors = [
                    'open'               => 'primary',   
                    // 'confirmed'          => 'primary',
                    'partial'            => 'warning',   
                    // 'partially_received' => 'warning', 
                    // 'completed'          => 'success',
                    // 'cancelled'          => 'danger',
                    'closed'             => 'danger',
                ];


                    $color = $statusColors[$po->status] ?? 'secondary';
                    $label = ucfirst(str_replace('_', ' ', $po->status));

                    return '<span class="badge bg-' . $color . '">' . $label . '</span>';
                })
                ->editColumn('items_count', function (PurchaseOrder $po) {
                    return $po->items_count ?: 0;
                })
                ->editColumn('total_amount', function (PurchaseOrder $po) {
                    return format_currency($po->total_amount);
                })
                ->editColumn('payment_status', function (PurchaseOrder $po) {
                    return ucfirst(str_replace('_', ' ', $po->payment_status));
                })
                // ->addColumn('actions', function (PurchaseOrder $po) {
                //     $editUrl   = route('purchase-orders.edit', $po);
                //     $deleteUrl = route('purchase-orders.destroy', $po);
                //     $csrf      = csrf_field();
                //     $method    = method_field('DELETE');
                //     return '<div class="d-flex gap-2">'
                //         . '<a href="' . $editUrl . '" class="btn btn-sm btn-outline-primary" title="Edit">'
                //         . '<i class="fas fa-edit me-1"></i>Edit</a>'
                //         . '<form action="' . $deleteUrl . '" method="POST" style="display: inline;" onsubmit="return confirm(\'Are you sure you want to delete this purchase order?\')">'
                //         . $csrf . $method . '<button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">'
                //         . '<i class="fas fa-trash me-1"></i>Delete</button></form>'
                //         . '</div>';
                // })
                ->addColumn('actions', function (PurchaseOrder $po) {
                    if ($po->status !== 'closed') {
                    $editUrl = route('purchase-orders.edit', $po);

                    return '<div class="d-flex gap-2">'
                        . '<a href="' . $editUrl . '" class="btn btn-sm btn-outline-primary" title="Edit">'
                        . '<i class="fas fa-edit me-1"></i>Edit</a>'
                        . '</div>';
                    }
                })

                ->rawColumns(['actions', 'status'])
                ->toJson();
        }

        return view('purchase_orders.index');
    }

    public function show($purchaseOrder)
    {
        $purchaseOrder = PurchaseOrder::find($purchaseOrder);
        // dd($purchaseOrder);
        $purchaseOrder->load([
            'supplier',
            'purchaseRequest',
            'items.item.uom',
            'grns',
            'gatePasses',
            'payments'
        ]);

        return view('purchase_orders.show', compact('purchaseOrder'));
    }

    public function create(): View
    {
        // ✅ Load PRs with their items + account + uom
        $requests = PurchaseRequest::with(['items.account.uom'])
            ->whereIn('status', ['approved', 'partially_ordered'])
            ->orderByDesc('id')
            ->get();

        foreach ($requests as $request) {
            foreach ($request->items as $item) {
                $item->item_name = $item->account->name ?? ''; // Optional: only if you show item name
                $item->unit_code = $item->unit_code ?? 'N/A'; // Make sure it’s available
            }
        }

        $vendors      = Account::where('model_type', 'supplier')->orderBy('name')->get();
        // dd($vendors);
        $autoPONumber = old('po_number', PurchaseOrderService::generatePONumber());
        return view('purchase_orders.create', compact('requests', 'vendors', 'autoPONumber'));
    }

    public function createFromPR(PurchaseRequest $purchaseRequest): View
    {
        // Check if PR can be converted to PO
        if (! $purchaseRequest->can_be_converted_to_po) {
            abort(403, 'This purchase request cannot be converted to a purchase order.');
        }

        // Load PR with items and their details
        $purchaseRequest->load(['items.item', 'items.itemVariation', 'items.uom']);

        // Get vendors (suppliers from Account model)
        $vendors = Account::where('model_type', 'supplier')
            ->orderBy('name')
            ->get();

        // Get UOMs
        $uoms = Uom::orderBy('name')->select('code', 'name', 'id')->get();

        // Generate auto PO number
        $autoPONumber = PurchaseOrderService::generatePONumber();

        // Prepare PR items for PO form
        $prItems = $purchaseRequest->items->map(function ($item) {
            return [
                'pr_item_id'          => $item->id,
                'item_id'             => $item->item_id,
                'item_name'           => optional($item->item)->name ?? 'N/A',
                'item_variation_id'   => $item->item_variation_id,
                'item_variation_name' => optional($item->itemVariation)->name ?? 'N/A',
                'requested_qty'       => $item->quantity,
                'uom_id'              => $item->uom_id,
                'uom_name'            => optional($item->uom)->name ?? 'N/A',
                'unit_code'           => $item->unit_code,
                'max_qty'             => $item->quantity, // Cannot exceed PR quantity
            ];
        });
        // dd("Dd");
        return view('purchase_orders.create_from_pr', compact(
            'purchaseRequest',
            'vendors',
            'uoms',
            'prItems',
            'autoPONumber'
        ));
    }

    public function store(StorePurchaseOrderRequest $request): RedirectResponse
    {
        try {
            $po = null;
            DB::transaction(function () use ($request, &$po) {
                $validated = $request->validated();
                $items     = $validated['items'];

                // Validate PR if provided
                $purchaseRequest = null;
                if (! empty($validated['purchase_request_id'])) {
                    $purchaseRequest = PurchaseRequest::findOrFail($validated['purchase_request_id']);
                    // dd(!$purchaseRequest->can_be_converted_to_po);
                    // Validate that PR can be converted to PO
                    // if (!$purchaseRequest->can_be_converted_to_po) {
                    // 	throw new \Exception('This purchase request cannot be converted to a purchase order.');
                    // }
                }

                // Use service to validate and generate PO number if needed
                $numberService = app(\App\Services\NumberGenerationService::class);
                $poNumber      = $numberService->validateAndGenerateNumber('po', $validated['po_number'] ?? null);

                // dd($request->all(),$validated['vendor_id']);
                $po = PurchaseOrder::create([
                    'po_number'           => $poNumber,
                    'purchase_request_id' => $validated['purchase_request_id'],
                    'contact_id'          => $validated['vendor_id'] ?? 1, // Default to first contact if no vendor specified
                    // 'order_date' => $validated['order_date'],
                    // 'expected_delivery_date' => $validated['expected_delivery_date'] ?? null,
                    'expected_date'       => $validated['expected_date'] ?? null,
                    'remarks'             => $validated['remarks'] ?? null,
                    'status'              => 'open',
                    'payment_status'      => 'unpaid',
                    'total_amount'        => $validated['total_amount'] ?? 0,
                ]);

                $total = 0;
                $rows  = [];
                foreach ($items as $row) {
                    $quantity  = isset($row['quantity']) ? (float) $row['quantity'] : 0;
                    $unitPrice = isset($row['unit_price']) ? (float) $row['unit_price'] : 0;
                    if ($quantity <= 0 || $unitPrice <= 0) {
                        // Ignore incomplete/blank rows
                        continue;
                    }

                    $totalPrice = (float) ($row['total_price'] ?? 0);
                    if ($totalPrice <= 0) {
                        $totalPrice = round($quantity * $unitPrice, 4);
                    }

                    $total += $totalPrice;
                    $poItem = new PurchaseOrderItem([
                        'item_id'                  => $row['item_id'],
                        'purchase_request_item_id' => $row['purchase_request_item_id'] ?? null,
                        'quantity'                 => $quantity,
                        'unit_price'               => $unitPrice,
                        'total_price'              => $totalPrice,
                        'uom_id'                   => $row['uom_id'] ?? null,
                        'unit_code'                => $row['unit_code'] ?? null,
                    ]);

                    // Link to PR item if provided
                    if (! empty($row['purchase_request_item_id'])) {
                        $poItem->purchase_request_item_id = $row['purchase_request_item_id'];

                        // Validate quantity against PR
                        if ($purchaseRequest) {
                            $prItem = $purchaseRequest->items()->find($row['purchase_request_item_id']);
                            if ($prItem && $quantity > $prItem->quantity) {
                                throw new \Exception("Ordered quantity ({$quantity}) cannot exceed PR quantity ({$prItem->quantity}) for item: " . optional($prItem->item)->name);
                            }
                        }
                    }

                    $rows[] = $poItem;
                }
                $po->items()->saveMany($rows);

                // Update total amount if not already set
                if (empty($validated['total_amount'])) {
                    $po->update(['total_amount' => $total]);
                }

                // Create Account Transactions
                // 1. Debit: Expenses / Purchases
                $expenseCoa = \App\Models\ChartOfAccount::where('name', 'like', '%Expense%')
                    ->orWhere('name', 'like', '%Purchase%')
                    ->first();

                // if ($expenseCoa) {
                //     \App\Models\AccountTransaction::create([
                //         'account_id' => $po->contact_id,
                //         'chart_of_account_id' => $expenseCoa->id,
                //         'amount' => $total,
                //         'transaction_type' => 'debit',
                //         'reference_id' => $po->id,
                //         'reference_type' => 'App\Models\PurchaseOrder',
                //         'remarks' => 'Purchase Order - ' . $poNumber . ' - Purchases',
                //     ]);
                // }

                // // 2. Credit: Accounts Payable (Vendor)
                // $vendorAccount = \App\Models\Account::find($po->contact_id);
                // if ($vendorAccount && $vendorAccount->chart_of_account_id) {
                //     \App\Models\AccountTransaction::create([
                //         'account_id' => $po->contact_id,
                //         'chart_of_account_id' => $vendorAccount->chart_of_account_id,
                //         'amount' => $total,
                //         'transaction_type' => 'credit',
                //         'reference_id' => $po->id,
                //         'reference_type' => 'App\Models\PurchaseOrder',
                //         'remarks' => 'Purchase Order - ' . $poNumber . ' - Payable',
                //     ]);
                // }

                // PR status is now managed by workflow (draft → submitted → approved/rejected)
                // No status updates needed when creating PO
            });

            $this->logActivity('Purchase Order created', $po, [
                'action'       => 'store',
                'po_number'    => $po->po_number,
                'items_count'  => $po->items()->count(),
                'total_amount' => $po->total_amount,
            ]);

            return redirect()->route('purchase-orders.index')->with('success', 'Purchase Order created successfully.');
        } catch (\Throwable $e) {
            $this->logError('Purchase Order creation failed', $e, [
                'action'       => 'store',
                'request_data' => $request->validated(),
            ]);
            report($e);
            dd($e->getMessage(), $e->getLine(), $e->getFile());
            return back()
                ->withInput()
                ->withErrors(['error' => 'Failed to create purchase order: ' . $e->getMessage()]);
        }
    }

    public function edit(PurchaseOrder $purchase_order): View
    {
        $purchase_order->load('items');
        $requests = PurchaseRequest::query()
            ->whereIn('status', ['approved', 'partially_ordered'])
            ->orderByDesc('id')
            ->pluck('pr_number', 'id');
        return view('purchase_orders.edit', [
            'purchaseOrder' => $purchase_order,
            'requests'      => $requests,
        ]);
    }

    public function update(UpdatePurchaseOrderRequest $request, PurchaseOrder $purchase_order): RedirectResponse
    {
        try {
            if ($purchase_order->status !== 'open') {
                return back()->withErrors(['error' => 'This Purchase Order cannot be edited in its current status.']);
            }
            $oldData = $purchase_order->toArray();
            DB::transaction(function () use ($request, $purchase_order) {
                $validated = $request->validated();
                $items     = $validated['items'];

                $purchase_order->update([
                    'po_number'              => $validated['po_number'],
                    'purchase_request_id'    => $validated['purchase_request_id'] ?? null,
                    'contact_id'             => $validated['vendor_id'],
                    'order_date'             => $validated['order_date'],
                    'expected_delivery_date' => $validated['expected_delivery_date'] ?? null,
                    'status'                 => $validated['status'],
                    'payment_status'         => $validated['payment_status'],
                ]);

                $purchase_order->items()->delete();
                $total = 0;
                $rows  = [];
                foreach ($items as $row) {
                    $quantity  = (float) $row['quantity'];
                    $unitPrice = (float) $row['unit_price'];
                    $taxRate   = (float) ($row['tax_rate'] ?? 0);
                    $discount  = (float) ($row['discount'] ?? 0);
                    $line      = round(($quantity * $unitPrice) * (1 + $taxRate / 100) - $discount, 4);
                    $total += $line;
                    $rows[] = new PurchaseOrderItem([
                        'item_id'     => $row['item_id'],
                        'quantity'    => $quantity,
                        'unit_price'  => $unitPrice,
                        'tax_rate'    => $taxRate,
                        'discount'    => $discount,
                        'total_price' => $line,
                    ]);
                }
                $purchase_order->items()->saveMany($rows);
                $purchase_order->update(['total_amount' => $total]);
            });

            $this->logActivity('Purchase Order updated', $purchase_order, [
                'action'      => 'update',
                'old_data'    => $oldData,
                'new_data'    => $request->validated(),
                'items_count' => $purchase_order->items()->count(),
            ]);

            return redirect()->route('purchase-orders.index')->with('success', 'Purchase Order updated successfully.');
        } catch (\Throwable $e) {
            $this->logError('Purchase Order update failed', $e, [
                'action'            => 'update',
                'purchase_order_id' => $purchase_order->id,
                'request_data'      => $request->validated(),
            ]);

            report($e);
            return back()->withInput()->withErrors(['error' => 'Failed to update purchase order.']);
        }
    }

    // public function update(UpdatePurchaseOrderRequest $request, PurchaseOrder $purchase_order): RedirectResponse
    // {
    //     try {
    //         if ($purchase_order->status !== 'open') {
    //             return back()->withErrors(['error' => 'This Purchase Order cannot be edited in its current status.']);
    //         }

    //         $oldData = $purchase_order->toArray();

    //         DB::transaction(function () use ($request, $purchase_order) {
    //             $validated = $request->validated();
    //             $items     = $validated['items'];

    //             $purchase_order->update([
    //                 'po_number'           => $validated['po_number'],
    //                 'purchase_request_id' => $validated['purchase_request_id'] ?? $purchase_order->purchase_request_id,
    //                 'contact_id'          => $validated['vendor_id'] ?? $purchase_order->contact_id,
    //                 'expected_date'       => $validated['expected_date'] ?? $purchase_order->expected_date,
    //                 'remarks'             => $validated['remarks'] ?? null,
    //             ]);

    //             $purchase_order->items()->delete();
    //             $total = 0;
    //             $rows  = [];
    //             foreach ($items as $row) {
    //                 $quantity   = (float) $row['quantity'];
    //                 $unitPrice  = (float) $row['unit_price'];
    //                 $totalPrice = (float) ($row['total_price'] ?? round($quantity * $unitPrice, 4));
    //                 $total += $totalPrice;

    //                 $rows[] = new PurchaseOrderItem([
    //                     'item_id'                  => $row['item_id'],
    //                     'purchase_request_item_id' => $row['purchase_request_item_id'] ?? null,
    //                     'uom_id'                   => $row['uom_id'] ?? null,
    //                     'unit_code'                => $row['unit_code'] ?? null,
    //                     'quantity'                 => $quantity,
    //                     'unit_price'               => $unitPrice,
    //                     'total_price'              => $totalPrice,
    //                 ]);
    //             }
    //             $purchase_order->items()->saveMany($rows);
    //             $purchase_order->update(['total_amount' => $validated['total_amount'] ?? $total]);
    //         }); // ← transaction closes here

    //         // ← these are OUTSIDE the transaction
    //         $this->logActivity('Purchase Order updated', $purchase_order, [
    //             'action'      => 'update',
    //             'old_data'    => $oldData,
    //             'new_data'    => $request->validated(),
    //             'items_count' => $purchase_order->items()->count(),
    //         ]);

    //         return redirect()->route('purchase-orders.index')->with('success', 'Purchase Order updated successfully.');

    //     } catch (\Throwable $e) {
    //         $this->logError('Purchase Order update failed', $e, [
    //             'action'            => 'update',
    //             'purchase_order_id' => $purchase_order->id,
    //             'request_data'      => $request->validated(),
    //         ]);

    //         report($e);
    //         return back()->withInput()->withErrors(['error' => 'Failed to update purchase order.']);
    //     }
    // }

    public function cancel(Request $request, PurchaseOrder $purchaseOrder): JsonResponse
    {
        try {
            // Only creator or admin can cancel (creator approximated by the one who created PO via activity logs or add a created_by column if available)
            if (! (auth()->user()?->hasRole('admin') || auth()->user()?->hasRole('superadmin'))) {
                return response()->json([
                    'success' => false,
                    'message' => 'You are not authorized to cancel this purchase order.',
                ], 403);
            }

            $request->validate([
                'reason' => 'required|string|max:500',
            ]);

            if (! in_array($purchaseOrder->status, ['open', 'confirmed', 'partially_received'])) {
                return response()->json([
                    'success' => false,
                    'message' => 'This purchase order cannot be cancelled in its current status.',
                ], 400);
            }

            $oldStatus = $purchaseOrder->status;
            $purchaseOrder->update(['status' => 'cancelled']);

            $this->logActivity('Purchase Order cancelled', $purchaseOrder, [
                'action'       => 'cancel',
                'old_status'   => $oldStatus,
                'new_status'   => 'cancelled',
                'reason'       => $request->string('reason'),
                'cancelled_by' => auth()->id(),
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Purchase order cancelled successfully.',
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to cancel purchase order.',
            ], 500);
        }
    }

    public function updateStatus(Request $request, PurchaseOrder $purchaseOrder): JsonResponse
    {
        try {
            // $validStatuses = ['open','submitted','approved','partially_ordered','fully_ordered','closed','canceled'];
            $validStatuses = ['open', 'approved', 'rejected'];
            $status        = $request->string('status');

            if (! in_array($status, $validStatuses)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid status',
                ], 400);
            }

            $oldStatus = $purchaseOrder->status;
            $purchaseOrder->update(['status' => $status]);

            $this->logActivity('Purchase Order status updated', $purchaseOrder, [
                'action'     => 'update_status',
                'old_status' => $oldStatus,
                'new_status' => $status,
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Purchase order status updated successfully',
                'status'  => $status,
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update purchase order status',
            ], 500);
        }
    }

    public function destroy(PurchaseOrder $purchase_order): RedirectResponse
    {
        try {
            if (! $purchase_order->canDelete()) {
                return back()->withErrors(['error' => 'This Purchase Order cannot be deleted. Use cancellation instead.']);
            }
            DB::transaction(function () use ($purchase_order) {
                $purchase_order->delete();
            });
            return redirect()->route('purchase-orders.index')->with('success', 'Purchase Order deleted successfully.');
        } catch (\Throwable $e) {
            report($e);
            return back()->withErrors(['error' => 'Failed to delete purchase order.']);
        }
    }

    public function getItems(PurchaseOrder $purchaseOrder)
    {
        $items = $purchaseOrder->items()
            ->with(['item'])
            ->withSum('gatePassItems', 'dn_quantity')
            ->get()
            ->map(function ($item) {
                return [

                    'id'                => $item->id,
                    'item_id'           => $item->item_id,
                    'item_name'         => optional($item->item)->name,
                    'quantity'          => $item->quantity,
                    'received_quantity' => $item->gate_pass_items_sum_dn_quantity ?? 0,
                    'uom_id'            => $item->item->uom->id,
                    'uom_name'          => $item->item->uom->name,
                    'unit_code'         => $item->item->uom->unit_code,
                ];
            });

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

    public function searchPurchaseOrders(Request $request): JsonResponse
{
    try {
        //  Always cast search to string safely
        $search = (string) $request->input('search', '');

        $status = $request->filled('status')
            ? array_filter(explode(',', (string) $request->input('status')))
            : [];

        $poService = app(\App\Services\PurchaseOrderService::class);
        $pos = $poService->searchPurchaseOrders($search, $status);

        //  Make sure we return plain JSON array
        if ($pos instanceof \Illuminate\Support\Collection) {
            $pos = $pos->map(fn($po) => [
                'id' => $po->id,
                'po_number' => $po->po_number,
            ])->values();
        }

        return response()->json($pos);
    } catch (\Throwable $e) {
        \Log::error('PO search failed', ['error' => $e->getMessage()]);
        return response()->json(['error' => $e->getMessage()], 500);
    }
}

}
