<?php

namespace App\Modules\Integration\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Integration\Models\SalesOrder;
use Illuminate\Http\Request;
use Inertia\Inertia;

class SalesOrderController extends Controller
{
    /**
     * 顯示銷售訂單列表
     */
    public function index(Request $request)
    {
        $query = SalesOrder::query();

        // 搜尋篩選 (外部訂單號)
        if ($request->filled('search')) {
            $query->where('external_order_id', 'like', '%' . $request->search . '%');
        }

        // 來源篩選
        if ($request->filled('source')) {
            $query->where('source', $request->source);
        }

        // 排序
        $query->orderBy('sold_at', 'desc');

        $defaultPerPage = \App\Modules\Core\Models\SystemSetting::getVal('display.per_page', 10);
        $perPage = (int) $request->input('per_page', $defaultPerPage);
        if (!in_array($perPage, [10, 20, 50, 100])) {
            $perPage = $defaultPerPage;
        }

        $orders = $query->paginate($perPage)
            ->withQueryString();

        return Inertia::render('Integration/SalesOrders/Index', [
            'orders' => $orders,
            'filters' => $request->only(['search', 'per_page', 'source']),
        ]);
    }

    /**
     * 顯示單一銷售訂單詳情
     */
    public function show(SalesOrder $salesOrder)
    {
        $salesOrder->load(['items']);

        return Inertia::render('Integration/SalesOrders/Show', [
            'order' => $salesOrder,
        ]);
    }
}
