<?php

namespace App\Http\Controllers\Finance;

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

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

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('vendor', '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);
            }
        }

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

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

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

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

        Expense::create([
            'tenant_id' => $tenantId, 'date' => $request->input('date'),
            'vendor' => $request->input('vendor'), 'description' => $request->input('description'),
            'category' => $request->input('category', '기타지출'),
            'amount' => $request->input('amount', 0),
            'status' => $request->input('status', 'pending'),
            'payment_method' => $request->input('paymentMethod'),
            '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 = Expense::forTenant($tenantId)->findOrFail($id);
        $request->validate(['vendor' => 'required|string|max:100', 'amount' => 'required|integer|min:0']);

        $item->update([
            'date' => $request->input('date'), 'vendor' => $request->input('vendor'),
            'description' => $request->input('description'),
            'category' => $request->input('category', $item->category),
            'amount' => $request->input('amount'),
            'status' => $request->input('status', $item->status),
            'payment_method' => $request->input('paymentMethod'),
            '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);
        Expense::forTenant($tenantId)->findOrFail($id)->delete();

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