<?php
// app/Services/SubscriptionService.php

namespace App\Services;

use App\Models\Subscription;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;

class SubscriptionService
{
    const DAYS_IN_MONTH = 30;

    protected function getMonthlyPrice()
    {
        return env('SUBSCRIPTION_MONTHLY_PRICE', 9000);
    }

    protected function generateReference(): string
    {
        return 'SUB-' . now()->timestamp . '-' . substr(uniqid(), -4);
    }

    public function createSubscription(string $type): Subscription
    {
        $member = auth("member")->user(); // Or pass user explicitly

        $monthly = $this->getMonthlyPrice();
        $amount = 0;
        $start = now();
        $end = now();

        switch ($type) {
            case 'daily':
                $amount = round($monthly / self::DAYS_IN_MONTH, 2);
                $end->addDay()->endOfDay();
                break;
            case 'weekly':
                $amount = round(($monthly / self::DAYS_IN_MONTH) * 7, 2);
                $end->addWeek()->endOfDay();
                break;
            case 'monthly':
                $amount = $monthly;
                $end->addMonth()->endOfDay();
                break;
            default:
                throw new \Exception('Invalid duration type.');
        }

        return Subscription::create([
            'member_id'  => $member->id,
            'reference'  => $this->generateReference(),
            'amount'     => $amount,
            'duration'   => $type,
            'start_date' => $start->toDateTimeString(),
            'end_date'   => $end->toDateTimeString(),
            'active'     => false // Set to true after payment verification
        ]);
    }

    public function isActive($member): bool
    {
        return Subscription::where('member_id', $member->id)
            ->where('end_date', '>=', now())
            ->where('active', true)
            ->exists();
    }
}
