<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;

class WarehouseController extends Controller
{
    public function index(Request $request)
    {
        $orders = Order::query()
            ->with(['user', 'items.product', 'shippingCost'])
            ->whereIn('status', ['verify'])
            ->when($request->search, function ($query, $search) {
                $query->where(function ($q) use ($search) {
                    $q->where('order_code', 'like', "%{$search}%")
                      ->orWhereHas('user', function ($q) use ($search) {
                          $q->where('name', 'like', "%{$search}%");
                      });
                });
            })
            ->latest()
            ->paginate(10)
            ->withQueryString();

        return view('admin.warehouse', compact('orders'));
    }

    public function verify(Order $order)
    {
        try {
            $order->updateStatus('verify');
            return redirect()->back()->with('success', "Order {$order->order_code} verified, stock reduced");
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }

    public function send(Order $order)
    {
        try {
            $order->updateStatus('dikirim');
            return redirect()->back()->with('success', "Order {$order->order_code} marked as dikirim");
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $e->getMessage());
        }
    }
}
