<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\TradingPartner;
use App\Services\TradingPartnerOcrService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

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

        $query = TradingPartner::forTenant($tenantId);

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('ceo', 'like', "%{$search}%")
                    ->orWhere('manager', 'like', "%{$search}%");
            });
        }

        if ($type = $request->input('type')) {
            if ($type !== 'all') {
                $query->where('type', $type);
            }
        }

        if ($category = $request->input('category')) {
            if ($category !== 'all') {
                $query->where('category', $category);
            }
        }

        if ($status = $request->input('status')) {
            if ($status !== 'all') {
                $query->where('status', $status);
            }
        }

        $partners = $query->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($partner) {
                return [
                    'id' => $partner->id,
                    'name' => $partner->name,
                    'tradeType' => $partner->trade_type,
                    'type' => $partner->type,
                    'category' => $partner->category,
                    'bizNo' => $partner->biz_no,
                    'ceo' => $partner->ceo,
                    'bankAccount' => $partner->bank_account,
                    'contact' => $partner->contact,
                    'email' => $partner->email,
                    'address' => $partner->address,
                    'manager' => $partner->manager,
                    'managerPhone' => $partner->manager_phone,
                    'status' => $partner->status,
                    'memo' => $partner->memo,
                ];
            });

        $allPartners = TradingPartner::forTenant($tenantId);
        $stats = [
            'total' => (clone $allPartners)->count(),
            'sales' => (clone $allPartners)->where('trade_type', 'sales')->count(),
            'purchase' => (clone $allPartners)->where('trade_type', 'purchase')->count(),
            'active' => (clone $allPartners)->where('status', 'active')->count(),
        ];

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

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'name' => 'required|string|max:100',
            'type' => 'nullable|string|max:100',
            'category' => 'nullable|string|max:100',
        ]);

        $tenantId = session('selected_tenant_id', 1);

        $partner = TradingPartner::create([
            'tenant_id' => $tenantId,
            'name' => $request->input('name'),
            'trade_type' => $request->input('tradeType', 'sales'),
            'type' => $request->input('type'),
            'category' => $request->input('category'),
            'biz_no' => $request->input('bizNo'),
            'ceo' => $request->input('ceo'),
            'bank_account' => $request->input('bankAccount'),
            'contact' => $request->input('contact'),
            'email' => $request->input('email'),
            'address' => $request->input('address'),
            'manager' => $request->input('manager'),
            'manager_phone' => $request->input('managerPhone'),
            'status' => $request->input('status', 'active'),
            'memo' => $request->input('memo'),
        ]);

        return response()->json([
            'success' => true,
            'message' => '거래처가 등록되었습니다.',
            'data' => [
                'id' => $partner->id,
                'name' => $partner->name,
                'tradeType' => $partner->trade_type,
                'type' => $partner->type,
                'category' => $partner->category,
                'bizNo' => $partner->biz_no,
                'ceo' => $partner->ceo,
                'bankAccount' => $partner->bank_account,
                'contact' => $partner->contact,
                'email' => $partner->email,
                'address' => $partner->address,
                'manager' => $partner->manager,
                'managerPhone' => $partner->manager_phone,
                'status' => $partner->status,
                'memo' => $partner->memo,
            ],
        ]);
    }

    public function update(Request $request, int $id): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $partner = TradingPartner::forTenant($tenantId)->findOrFail($id);

        $request->validate([
            'name' => 'required|string|max:100',
            'type' => 'nullable|string|max:100',
            'category' => 'nullable|string|max:100',
        ]);

        $partner->update([
            'name' => $request->input('name'),
            'trade_type' => $request->input('tradeType', $partner->trade_type),
            'type' => $request->input('type'),
            'category' => $request->input('category'),
            'biz_no' => $request->input('bizNo'),
            'ceo' => $request->input('ceo'),
            'bank_account' => $request->input('bankAccount'),
            'contact' => $request->input('contact'),
            'email' => $request->input('email'),
            'address' => $request->input('address'),
            'manager' => $request->input('manager'),
            'manager_phone' => $request->input('managerPhone'),
            'status' => $request->input('status', 'active'),
            'memo' => $request->input('memo'),
        ]);

        return response()->json([
            'success' => true,
            'message' => '거래처가 수정되었습니다.',
            'data' => [
                'id' => $partner->id,
                'name' => $partner->name,
                'tradeType' => $partner->trade_type,
                'type' => $partner->type,
                'category' => $partner->category,
                'bizNo' => $partner->biz_no,
                'ceo' => $partner->ceo,
                'bankAccount' => $partner->bank_account,
                'contact' => $partner->contact,
                'email' => $partner->email,
                'address' => $partner->address,
                'manager' => $partner->manager,
                'managerPhone' => $partner->manager_phone,
                'status' => $partner->status,
                'memo' => $partner->memo,
            ],
        ]);
    }

    public function ocr(Request $request, TradingPartnerOcrService $ocrService): JsonResponse
    {
        $request->validate([
            'image' => 'required|string',
        ]);

        try {
            $result = $ocrService->extractFromImage($request->input('image'));

            return response()->json($result);
        } catch (\RuntimeException $e) {
            return response()->json([
                'ok' => false,
                'message' => $e->getMessage(),
            ], 500);
        }
    }

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

        return response()->json([
            'success' => true,
            'message' => '거래처가 삭제되었습니다.',
        ]);
    }
}
