<?php

namespace App\Http\Controllers\Api\Subscription;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Subscription;
use App\Models\SubscriptionPlan;

class SubscriptionController extends Controller
{
    // 🔹 list subscription user
    public function index()
    {
        return Subscription::where('user_id',auth()->id())
            ->with('plan')
            ->latest()
            ->get();
    }

    // 🔹 subscribe plan
    public function subscribe(Request $request)
    {
        $request->validate([
            'plan_id' => 'required'
        ]);

        $plan = SubscriptionPlan::findOrFail($request->plan_id);

        // expire lama (jika ada)
        Subscription::where('user_id',auth()->id())
            ->where('status','active')
            ->update(['status'=>'expired']);

        $sub = Subscription::create([
            'user_id' => auth()->id(),
            'plan_id' => $plan->id,
            'status' => 'active',
            'start_date' => now(),
            'end_date' => now()->addMonth(),
            'amount_paid' => $plan->price
        ]);

        return $sub;
    }

    // 🔹 cancel
    public function cancel($id)
    {
        $sub = Subscription::findOrFail($id);

        $sub->update([
            'status' => 'cancelled',
            'cancelled_at' => now()
        ]);

        return $sub;
    }
}