<?php

namespace App\Modules\Core\Controllers;

use App\Http\Controllers\Controller;

use Illuminate\Http\Request;
use Inertia\Inertia;
use Spatie\Activitylog\Models\Activity;

class ActivityLogController extends Controller
{
    private function getSubjectMap()
    {
        return [
            'App\Modules\Core\Models\User' => '使用者',
            'App\Modules\Core\Models\Role' => '角色',
            'App\Modules\Inventory\Models\Product' => '商品',
            'App\Modules\Procurement\Models\Vendor' => '廠商',
            'App\Modules\Inventory\Models\Category' => '商品分類',
            'App\Modules\Inventory\Models\Unit' => '單位',
            'App\Modules\Procurement\Models\PurchaseOrder' => '採購單',
            'App\Modules\Inventory\Models\Warehouse' => '倉庫',
            'App\Modules\Inventory\Models\Inventory' => '庫存',
            'App\Modules\Finance\Models\UtilityFee' => '公共事業費',
            'App\Modules\Inventory\Models\GoodsReceipt' => '進貨單',
            'App\Modules\Production\Models\ProductionOrder' => '生產工單',
            'App\Modules\Production\Models\Recipe' => '生產配方',
            'App\Modules\Production\Models\RecipeItem' => '配方品項',
            'App\Modules\Production\Models\ProductionOrderItem' => '工單品項',
            'App\Modules\Inventory\Models\InventoryCountDoc' => '庫存盤點單',
            'App\Modules\Inventory\Models\InventoryAdjustDoc' => '庫存盤調單',
            'App\Modules\Inventory\Models\InventoryTransferOrder' => '庫存調撥單',
        ];
    }

    public function index(Request $request)
    {
        $perPage = $request->input('per_page', 10);
        $sortBy = $request->input('sort_by', 'created_at');
        $sortOrder = $request->input('sort_order', 'desc');

        $search = $request->input('search');
        $dateStart = $request->input('date_start');
        $dateEnd = $request->input('date_end');
        $event = $request->input('event');
        $subjectType = $request->input('subject_type');
        $causerId = $request->input('causer_id');

        $query = Activity::with('causer');

        if ($search) {
            $query->where(function ($q) use ($search) {
                $q->where('description', 'like', "%{$search}%")
                    ->orWhere('log_name', 'like', "%{$search}%")
                    ->orWhere('properties', 'like', "%{$search}%");
            });
        }

        if ($dateStart) {
            $query->whereDate('created_at', '>=', $dateStart);
        }

        if ($dateEnd) {
            $query->whereDate('created_at', '<=', $dateEnd);
        }

        if ($event) {
            $query->where('event', $event);
        }

        if ($subjectType) {
            $query->where('subject_type', $subjectType);
        }

        if ($causerId) {
            $query->where('causer_id', $causerId);
        }

        if ($sortBy === 'created_at') {
            $query->orderBy($sortBy, $sortOrder);
        } else {
            $query->latest();
        }

        $activities = $query->paginate($perPage)
            ->withQueryString()
            ->through(function ($activity) {
        $subjectMap = $this->getSubjectMap();

                $eventMap = [
                    'created' => '新增',
                    'updated' => '更新',
                    'deleted' => '刪除',
                ];

                return [
                    'id' => $activity->id,
                    'description' => $eventMap[$activity->event] ?? $activity->event,
                    'subject_type' => $subjectMap[$activity->subject_type] ?? class_basename($activity->subject_type),
                    'event' => $activity->event,
                    'causer' => $activity->causer ? $activity->causer->name : 'System',
                    'created_at' => $activity->created_at->format('Y-m-d H:i:s'),
                    'properties' => $activity->properties,
                ];
            });

        // 準備用於前端篩選的主題類型
        $subjectTypes = collect($this->getSubjectMap())->map(function ($label, $value) {
            return ['label' => $label, 'value' => $value];
        })->values();

        // 取得用於操作者篩選的使用者
        $users = \App\Modules\Core\Models\User::select('id', 'name')->orderBy('name')->get()
            ->map(function ($user) {
                return ['label' => $user->name, 'value' => (string) $user->id];
            });

        return Inertia::render('Admin/ActivityLog/Index', [
            'activities' => $activities,
            'filters' => [
                'per_page' => $request->input('per_page', '10'),
                'sort_by' => $request->input('sort_by'),
                'sort_order' => $request->input('sort_order'),
                'search' => $request->input('search'),
                'date_start' => $request->input('date_start'),
                'date_end' => $request->input('date_end'),
                'event' => $request->input('event'),
                'subject_type' => $request->input('subject_type'),
                'causer_id' => $request->input('causer_id'),
            ],
            'subject_types' => $subjectTypes,
            'users' => $users,
        ]);
    }
}
