<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\ConsultingFee;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ConsultingFeeController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $query = ConsultingFee::forTenant($tenantId);

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('consultant', 'like', "%{$search}%")
                    ->orWhere('customer', 'like', "%{$search}%");
            });
        }
        if ($status = $request->input('status')) {
            if ($status !== 'all') {
                $query->where('status', $status);
            }
        }

        $fees = $query->orderBy('date', 'desc')->get()->map(fn ($item) => [
            'id' => $item->id, 'date' => $item->date?->format('Y-m-d'),
            'consultant' => $item->consultant, 'customer' => $item->customer,
            'service' => $item->service, 'hours' => $item->hours,
            'hourlyRate' => $item->hourly_rate, 'amount' => $item->amount,
            'status' => $item->status, 'memo' => $item->memo,
        ]);

        $all = ConsultingFee::forTenant($tenantId)->get();
        $stats = [
            'totalAmount' => $all->sum('amount'),
            'paidAmount' => $all->where('status', 'paid')->sum('amount'),
            'pendingAmount' => $all->where('status', 'pending')->sum('amount'),
            'totalHours' => $all->sum('hours'),
        ];

        return response()->json(['success' => true, 'data' => $fees, 'stats' => $stats]);
    }

    public function store(Request $request): JsonResponse
    {
        $request->validate(['consultant' => 'required|string|max:100', 'amount' => 'required|integer|min:0']);
        $tenantId = session('selected_tenant_id', 1);

        ConsultingFee::create([
            'tenant_id' => $tenantId, 'date' => $request->input('date'),
            'consultant' => $request->input('consultant'), 'customer' => $request->input('customer'),
            'service' => $request->input('service'), 'hours' => $request->input('hours', 0),
            'hourly_rate' => $request->input('hourlyRate', 0),
            'amount' => $request->input('amount', 0),
            'status' => $request->input('status', 'pending'), 'memo' => $request->input('memo'),
        ]);

        return response()->json(['success' => true, 'message' => '컨설팅비가 등록되었습니다.']);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $item = ConsultingFee::forTenant($tenantId)->findOrFail($id);
        $request->validate(['consultant' => 'required|string|max:100', 'amount' => 'required|integer|min:0']);

        $item->update([
            'date' => $request->input('date'), 'consultant' => $request->input('consultant'),
            'customer' => $request->input('customer'), 'service' => $request->input('service'),
            'hours' => $request->input('hours', $item->hours),
            'hourly_rate' => $request->input('hourlyRate', $item->hourly_rate),
            'amount' => $request->input('amount'),
            'status' => $request->input('status', $item->status), 'memo' => $request->input('memo'),
        ]);

        return response()->json(['success' => true, 'message' => '컨설팅비가 수정되었습니다.']);
    }

    public function destroy(int $id): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        ConsultingFee::forTenant($tenantId)->findOrFail($id)->delete();

        return response()->json(['success' => true, 'message' => '컨설팅비가 삭제되었습니다.']);
    }
}
