<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\Plan;
use App\Models\Subscription;
use App\Models\Invoice;
use Illuminate\Http\Request;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class BillingController extends Controller
{
    /**
     * Subscribe to a plan.
     */
    public function subscribe(Request $request)
    {
        $request->validate([
            'plan_id' => 'required|exists:plans,id',
        ]);

        $user = $request->user();
        $tenant = $user->tenant;

        if (!$tenant) {
            return response()->json(['message' => 'User does not belong to a tenant'], 400);
        }

        $plan = Plan::find($request->plan_id);

        try {
            DB::beginTransaction();

            // Cancel existing active subscription
            $currentSub = Subscription::where('tenant_id', $tenant->id)
                ->where('status', 'active')
                ->first();
            
            if ($currentSub) {
                $currentSub->update(['status' => 'cancelled', 'ends_at' => now()]);
            }

            // Create new subscription
            $startsAt = now();
            $endsAt = match($plan->interval) {
                'daily' => $startsAt->copy()->addDay(),
                'monthly' => $startsAt->copy()->addDays(30),
                'yearly' => $startsAt->copy()->addDays(360),
                default => $startsAt->copy()->addMonth(),
            };

            $subscription = Subscription::create([
                'tenant_id' => $tenant->id,
                'plan_id' => $plan->id,
                'status' => 'pending', // Pending payment
                'starts_at' => $startsAt,
                'ends_at' => $endsAt,
            ]);

            // Generate Invoice
            $invoice = Invoice::create([
                'tenant_id' => $tenant->id,
                'subscription_id' => $subscription->id,
                'number' => 'INV-' . strtoupper(uniqid()),
                'amount' => $plan->price,
                'status' => 'pending',
                'due_date' => now()->addDays(7),
            ]);

            DB::commit();

            return response()->json([
                'message' => 'Subscription created. Please pay the invoice.',
                'subscription' => $subscription,
                'invoice' => $invoice,
            ]);

        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['message' => 'Subscription failed: ' . $e->getMessage()], 500);
        }
    }

    /**
     * Get invoices.
     */
    public function invoices(Request $request)
    {
        $user = $request->user();
        if (!$user->tenant) {
            return response()->json(['message' => 'No tenant'], 400);
        }

        $invoices = Invoice::where('tenant_id', $user->tenant->id)->get();
        return response()->json($invoices);
    }
}
