<?php

namespace App\Http\Controllers\Finance;

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

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

        if ($search = $request->input('search')) {
            $query->where(function ($q) use ($search) {
                $q->where('customer', 'like', "%{$search}%");
            });
        }
        if ($status = $request->input('status')) {
            if ($status !== 'all') {
                $query->where('status', $status);
            }
        }

        $subscriptions = $query->orderBy('created_at', 'desc')->get()->map(fn ($item) => [
            'id' => $item->id, 'customer' => $item->customer,
            'plan' => $item->plan, 'monthlyFee' => $item->monthly_fee,
            'billingCycle' => $item->billing_cycle,
            'startDate' => $item->start_date?->format('Y-m-d'),
            'nextBilling' => $item->next_billing?->format('Y-m-d'),
            'status' => $item->status, 'users' => $item->users, 'memo' => $item->memo,
        ]);

        $all = Subscription::forTenant($tenantId)->get();
        $active = $all->where('status', 'active');
        $monthlyRecurring = $active->sum('monthly_fee');
        $stats = [
            'activeCount' => $active->count(),
            'monthlyRecurring' => $monthlyRecurring,
            'yearlyRecurring' => $monthlyRecurring * 12,
            'totalUsers' => $active->sum('users'),
        ];

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

    public function store(Request $request): JsonResponse
    {
        $request->validate(['customer' => 'required|string|max:100']);
        $tenantId = session('selected_tenant_id', 1);

        Subscription::create([
            'tenant_id' => $tenantId, 'customer' => $request->input('customer'),
            'plan' => $request->input('plan'),
            'monthly_fee' => $request->input('monthlyFee', 0),
            'billing_cycle' => $request->input('billingCycle', 'monthly'),
            'start_date' => $request->input('startDate'),
            'next_billing' => $request->input('nextBilling'),
            'status' => $request->input('status', 'active'),
            'users' => $request->input('users', 0), '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 = Subscription::forTenant($tenantId)->findOrFail($id);
        $request->validate(['customer' => 'required|string|max:100']);

        $item->update([
            'customer' => $request->input('customer'), 'plan' => $request->input('plan', $item->plan),
            'monthly_fee' => $request->input('monthlyFee', $item->monthly_fee),
            'billing_cycle' => $request->input('billingCycle', $item->billing_cycle),
            'start_date' => $request->input('startDate'),
            'next_billing' => $request->input('nextBilling'),
            'status' => $request->input('status', $item->status),
            'users' => $request->input('users', $item->users), 'memo' => $request->input('memo'),
        ]);

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

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

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