<?php

namespace App\Http\Controllers\Finance;

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

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

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

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

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

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

        $refunds = $query->orderBy('created_at', 'desc')
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'type' => $item->type,
                    'customerName' => $item->customer_name,
                    'requestDate' => $item->request_date?->format('Y-m-d'),
                    'productName' => $item->product_name,
                    'originalAmount' => $item->original_amount,
                    'refundAmount' => $item->refund_amount,
                    'reason' => $item->reason,
                    'status' => $item->status,
                    'processDate' => $item->process_date?->format('Y-m-d'),
                    'note' => $item->note,
                ];
            });

        $all = Refund::forTenant($tenantId)->get();

        $stats = [
            'pending' => $all->where('status', 'pending')->count(),
            'completed' => $all->where('status', 'completed')->count(),
            'rejected' => $all->where('status', 'rejected')->count(),
            'totalRefunded' => $all->whereIn('status', ['completed', 'approved'])->sum('refund_amount'),
        ];

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

    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'customerName' => 'required|string|max:100',
            'productName' => 'required|string|max:100',
            'originalAmount' => 'required|integer|min:0',
            'type' => 'required|in:refund,cancel',
        ]);

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

        Refund::create([
            'tenant_id' => $tenantId,
            'type' => $request->input('type', 'refund'),
            'customer_name' => $request->input('customerName'),
            'request_date' => $request->input('requestDate'),
            'product_name' => $request->input('productName'),
            'original_amount' => $request->input('originalAmount', 0),
            'refund_amount' => 0,
            'reason' => $request->input('reason'),
            'status' => 'pending',
            'note' => $request->input('note'),
        ]);

        return response()->json([
            'success' => true,
            'message' => '환불/해지 요청이 등록되었습니다.',
        ]);
    }

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

        $request->validate([
            'customerName' => 'required|string|max:100',
            'productName' => 'required|string|max:100',
            'originalAmount' => 'required|integer|min:0',
        ]);

        $refund->update([
            'type' => $request->input('type', $refund->type),
            'customer_name' => $request->input('customerName'),
            'request_date' => $request->input('requestDate'),
            'product_name' => $request->input('productName'),
            'original_amount' => $request->input('originalAmount'),
            'refund_amount' => $request->input('refundAmount', $refund->refund_amount),
            'reason' => $request->input('reason'),
            'status' => $request->input('status', $refund->status),
            'process_date' => $request->input('processDate'),
            'note' => $request->input('note'),
        ]);

        return response()->json([
            'success' => true,
            'message' => '환불/해지 요청이 수정되었습니다.',
        ]);
    }

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

        $request->validate([
            'action' => 'required|in:approved,completed,rejected',
        ]);

        $action = $request->input('action');
        $today = now()->format('Y-m-d');

        if ($action === 'rejected') {
            $refund->update([
                'status' => 'rejected',
                'refund_amount' => 0,
                'process_date' => $today,
                'note' => $request->input('note'),
            ]);
        } else {
            $refund->update([
                'status' => $action,
                'refund_amount' => $request->input('refundAmount', 0),
                'process_date' => $today,
                'note' => $request->input('note'),
            ]);
        }

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

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

        return response()->json([
            'success' => true,
            'message' => '환불/해지 요청이 삭제되었습니다.',
        ]);
    }
}
