<?php

namespace App\Http\Controllers\Finance;

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

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

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

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

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

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

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

        if ($startDate = $request->input('startDate')) {
            $query->where('transaction_date', '>=', $startDate);
        }
        if ($endDate = $request->input('endDate')) {
            $query->where('transaction_date', '<=', $endDate);
        }

        $transactions = $query->orderBy('transaction_date', 'desc')
            ->orderBy('time', 'desc')
            ->get()
            ->map(function ($tx) {
                return [
                    'id' => $tx->id,
                    'cardId' => $tx->card_id,
                    'date' => $tx->transaction_date?->format('Y-m-d'),
                    'time' => $tx->time,
                    'merchant' => $tx->merchant,
                    'category' => $tx->category,
                    'amount' => $tx->amount,
                    'approvalNo' => $tx->approval_no,
                    'status' => $tx->status,
                    'memo' => $tx->memo,
                ];
            });

        // 통계
        $stats = [
            'total' => $transactions->count(),
            'totalAmount' => $transactions->sum('amount'),
            'approvedAmount' => $transactions->where('status', 'approved')->sum('amount'),
            'cancelledAmount' => $transactions->where('status', 'cancelled')->sum(fn ($t) => abs($t['amount'])),
        ];

        // 카드 목록
        $cards = CorporateCard::forTenant($tenantId)
            ->orderBy('card_name')
            ->get()
            ->map(function ($card) {
                return [
                    'id' => $card->id,
                    'cardName' => $card->card_name,
                    'cardNumber' => $card->card_number,
                    'holder' => $card->holder_name,
                ];
            });

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

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'merchant' => 'required|string|max:200',
            'amount' => 'required|integer',
            'date' => 'required|date',
        ]);

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

        $tx = CardTransaction::create([
            'tenant_id' => $tenantId,
            'card_id' => $request->input('cardId'),
            'transaction_date' => $request->input('date'),
            'time' => $request->input('time'),
            'merchant' => $request->input('merchant'),
            'category' => $request->input('category', '기타'),
            'amount' => $request->input('amount'),
            'approval_no' => $request->input('approvalNo'),
            'status' => $request->input('status', 'approved'),
            'memo' => $request->input('memo'),
        ]);

        return response()->json([
            'success' => true,
            'message' => '거래가 등록되었습니다.',
            'data' => ['id' => $tx->id],
        ]);
    }

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

        $request->validate([
            'merchant' => 'required|string|max:200',
            'amount' => 'required|integer',
            'date' => 'required|date',
        ]);

        $tx->update([
            'card_id' => $request->input('cardId'),
            'transaction_date' => $request->input('date'),
            'time' => $request->input('time'),
            'merchant' => $request->input('merchant'),
            'category' => $request->input('category'),
            'amount' => $request->input('amount'),
            'approval_no' => $request->input('approvalNo'),
            'status' => $request->input('status'),
            'memo' => $request->input('memo'),
        ]);

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

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

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