<?php

namespace App\Services;

use App\Models\Subscription;
use App\Models\User;
use App\Models\Plan;

class SubscriptionService
{
    /**
     * Create an inactive subscription for a user.
     */
    public function createPending(User $user, Plan $plan)
    {
        // Cancel/Deactivate old inactive subscriptions
        $user->subscriptions()->where('subscription_status', 'inactive')->update([
            'subscription_status' => 'canceled'
        ]);

        return Subscription::create([
            'user_id' => $user->id,
            'plan_id' => $plan->id,
            'subscription_status' => 'inactive',
        ]);
    }

    /**
     * Activate a subscription after payment approval.
     */
    public function activate(Subscription $subscription)
    {
        $plan = $subscription->plan;
        $startDate = now();
        $endDate = $startDate->copy()->addDays($plan->duration_days);

        return $subscription->update([
            'subscription_status' => 'active',
            'start_date' => $startDate,
            'end_date' => $endDate,
        ]);
    }

    /**
     * Check if user has active subscription (Helper).
     */
    public function isUserActive(User $user): bool
    {
        return $user->subscriptions()
            ->where('subscription_status', 'active')
            ->where('end_date', '>=', now())
            ->exists();
    }
}
