<?php

namespace App\Http\Controllers\Finance;

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

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

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

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

        $all = Purchase::forTenant($tenantId)->get();
        $stats = [
            'totalAmount' => $all->sum('amount'),
            'totalVat' => $all->sum('vat'),
            'receivedAmount' => $all->where('status', 'received')->sum('amount'),
            'pendingAmount' => $all->where('status', 'pending')->sum('amount'),
        ];

        return response()->json(['success' => true, 'data' => $purchases, '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);

        Purchase::create([
            'tenant_id' => $tenantId, 'date' => $request->input('date'),
            'vendor' => $request->input('vendor'), 'item' => $request->input('item'),
            'category' => $request->input('category', '기타매입'),
            'amount' => $request->input('amount', 0), 'vat' => $request->input('vat', 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 = Purchase::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'),
            'item' => $request->input('item'),
            'category' => $request->input('category', $item->category),
            'amount' => $request->input('amount'), 'vat' => $request->input('vat', $item->vat),
            '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);
        Purchase::forTenant($tenantId)->findOrFail($id)->delete();

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