<?php

namespace App\Http\Controllers\Finance;

use App\Http\Controllers\Controller;
use App\Models\Finance\CondolenceExpense;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\View\View;

class CondolenceExpenseController extends Controller
{
    public function index(Request $request): View|Response
    {
        if ($request->header('HX-Request')) {
            return response('', 200)->header('HX-Redirect', route('finance.condolence-expenses'));
        }

        return view('finance.condolence-expenses');
    }

    public function list(Request $request): JsonResponse
    {
        $tenantId = session('selected_tenant_id', 1);
        $query = CondolenceExpense::forTenant($tenantId);

        if ($year = $request->input('year')) {
            $query->whereYear('event_date', $year);
        }

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

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

        $records = $query->orderBy('event_date', 'desc')
            ->orderBy('id', 'desc')
            ->get()
            ->map(fn ($item) => [
                'id' => $item->id,
                'event_date' => $item->event_date?->format('Y-m-d'),
                'expense_date' => $item->expense_date?->format('Y-m-d'),
                'partner_name' => $item->partner_name,
                'description' => $item->description,
                'category' => $item->category,
                'has_cash' => $item->has_cash,
                'cash_method' => $item->cash_method,
                'cash_amount' => $item->cash_amount,
                'has_gift' => $item->has_gift,
                'gift_type' => $item->gift_type,
                'gift_amount' => $item->gift_amount,
                'total_amount' => $item->total_amount,
                'memo' => $item->memo,
            ]);

        $all = CondolenceExpense::forTenant($tenantId);
        if ($year) {
            $all = $all->whereYear('event_date', $year);
        }
        $all = $all->get();

        $stats = [
            'totalCount' => $all->count(),
            'totalAmount' => $all->sum('total_amount'),
            'cashTotal' => $all->sum('cash_amount'),
            'giftTotal' => $all->sum('gift_amount'),
            'congratulationCount' => $all->where('category', 'congratulation')->count(),
            'condolenceCount' => $all->where('category', 'condolence')->count(),
        ];

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

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'partner_name' => 'required|string|max:100',
            'category' => 'required|in:congratulation,condolence',
        ]);

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

        $cashAmount = (int) $request->input('cash_amount', 0);
        $giftAmount = (int) $request->input('gift_amount', 0);

        CondolenceExpense::create([
            'tenant_id' => $tenantId,
            'event_date' => $request->input('event_date'),
            'expense_date' => $request->input('expense_date'),
            'partner_name' => $request->input('partner_name'),
            'description' => $request->input('description'),
            'category' => $request->input('category'),
            'has_cash' => $request->boolean('has_cash'),
            'cash_method' => $request->input('cash_method'),
            'cash_amount' => $cashAmount,
            'has_gift' => $request->boolean('has_gift'),
            'gift_type' => $request->input('gift_type'),
            'gift_amount' => $giftAmount,
            'total_amount' => $cashAmount + $giftAmount,
            'memo' => $request->input('memo'),
            'created_by' => auth()->id(),
        ]);

        return response()->json([
            'success' => true,
            'message' => '경조사비가 등록되었습니다.',
        ]);
    }

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

        $request->validate([
            'partner_name' => 'required|string|max:100',
            'category' => 'required|in:congratulation,condolence',
        ]);

        $cashAmount = (int) $request->input('cash_amount', 0);
        $giftAmount = (int) $request->input('gift_amount', 0);

        $item->update([
            'event_date' => $request->input('event_date'),
            'expense_date' => $request->input('expense_date'),
            'partner_name' => $request->input('partner_name'),
            'description' => $request->input('description'),
            'category' => $request->input('category'),
            'has_cash' => $request->boolean('has_cash'),
            'cash_method' => $request->input('cash_method'),
            'cash_amount' => $cashAmount,
            'has_gift' => $request->boolean('has_gift'),
            'gift_type' => $request->input('gift_type'),
            'gift_amount' => $giftAmount,
            'total_amount' => $cashAmount + $giftAmount,
            'memo' => $request->input('memo'),
        ]);

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

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

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