<?php

namespace App\Http\Controllers\Admin\Crm;

use App\Http\Controllers\Controller;
use App\Models\Crm\Complaint;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ComplaintController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $query = Complaint::query()->with(['customer', 'handler']);
        $query->when($request->customer_id, fn($q, $v) => $q->where('customer_id', $v));
        $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->latest()->paginate($request->input('per_page', 15)));
    }

    public function store(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'customer_id' => 'required|exists:customers,id',
            'type' => 'nullable|integer|in:1,2,3,4',
            'content' => 'required|string',
            'images' => 'nullable|array',
        ]);
        $validated['status'] = 0;

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

    public function show(Complaint $complaint): JsonResponse
    {
        return $this->success($complaint->load(['customer', 'handler']));
    }

    public function update(Request $request, Complaint $complaint): JsonResponse
    {
        $validated = $request->validate([
            'type' => 'nullable|integer|in:1,2,3,4',
            'content' => 'sometimes|string',
            'images' => 'nullable|array',
        ]);
        $complaint->update($validated);
        return $this->success($complaint);
    }

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

    public function handle(Request $request, Complaint $complaint): JsonResponse
    {
        if ($complaint->status >= 2) {
            return $this->error('该投诉已处理', 40001);
        }
        $validated = $request->validate([
            'handle_result' => 'required|string',
            'status' => 'required|integer|in:2,3',
        ]);
        $complaint->update([
            'handle_result' => $validated['handle_result'],
            'status' => $validated['status'],
            'handler_id' => auth()->id(),
            'handle_at' => now(),
        ]);
        return $this->success($complaint);
    }
}
