<?php

namespace App\Http\Controllers\Finance;

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

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

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

        $incomes = $query->orderBy('date', 'desc')->get()->map(fn ($item) => [
            'id' => $item->id, 'date' => $item->date?->format('Y-m-d'),
            'customer' => $item->customer, 'description' => $item->description,
            'category' => $item->category, 'amount' => $item->amount,
            'status' => $item->status, 'invoiceNo' => $item->invoice_no, 'memo' => $item->memo,
        ]);

        $all = Income::forTenant($tenantId)->get();
        $stats = [
            'totalAmount' => $all->sum('amount'),
            'completedAmount' => $all->where('status', 'completed')->sum('amount'),
            'pendingAmount' => $all->where('status', 'pending')->sum('amount'),
            'count' => $all->count(),
        ];

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

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

        Income::create([
            'tenant_id' => $tenantId, 'date' => $request->input('date'),
            'customer' => $request->input('customer'), 'description' => $request->input('description'),
            'category' => $request->input('category', '기타수입'),
            'amount' => $request->input('amount', 0),
            'status' => $request->input('status', 'pending'),
            'invoice_no' => $request->input('invoiceNo'), '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 = Income::forTenant($tenantId)->findOrFail($id);
        $request->validate(['customer' => 'required|string|max:100', 'amount' => 'required|integer|min:0']);

        $item->update([
            'date' => $request->input('date'), 'customer' => $request->input('customer'),
            'description' => $request->input('description'),
            'category' => $request->input('category', $item->category),
            'amount' => $request->input('amount'),
            'status' => $request->input('status', $item->status),
            'invoice_no' => $request->input('invoiceNo'), 'memo' => $request->input('memo'),
        ]);

        return response()->json(['success' => true, 'message' => '수입이 수정되었습니다.']);
    }

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

        return response()->json(['success' => true, 'message' => '수입이 삭제되었습니다.']);
    }
}
