<?php

namespace App\Http\Controllers\Admin\Office;

use App\Http\Controllers\Controller;
use App\Models\Office\ApprovalTemplate;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApprovalTemplateController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = ApprovalTemplate::query();
        $query->when($request->type, fn($q, $v) => $q->where('type', $v));
        $query->when($request->has('status'), fn($q) => $q->where('status', $request->status));

        return $this->paginate($query->orderBy('sort')->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'required|string|max:100',
            'type' => 'required|integer|in:1,2,3,4,5',
            'form_fields' => 'nullable|array',
            'flow_nodes' => 'nullable|array',
            'status' => 'sometimes|integer|in:0,1',
            'sort' => 'sometimes|integer',
        ]);

        return $this->success(ApprovalTemplate::create($validated));
    }

    public function show(ApprovalTemplate $approvalTemplate): JsonResponse
    {
        return $this->success($approvalTemplate);
    }

    public function update(Request $request, ApprovalTemplate $approvalTemplate): JsonResponse
    {
        $validated = $request->validate([
            'name' => 'sometimes|string|max:100',
            'type' => 'sometimes|integer|in:1,2,3,4,5',
            'form_fields' => 'nullable|array',
            'flow_nodes' => 'nullable|array',
            'status' => 'sometimes|integer|in:0,1',
            'sort' => 'sometimes|integer',
        ]);
        $approvalTemplate->update($validated);

        return $this->success($approvalTemplate);
    }

    public function destroy(ApprovalTemplate $approvalTemplate): JsonResponse
    {
        $approvalTemplate->delete();
        return $this->success(null);
    }
}
