<?php

namespace Database\Seeders;

use App\Models\Customer;
use App\Models\Plan;
use App\Models\Settings\DataSettings\PaymentMethod;
use App\Models\Subscription;
use App\Models\User;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class SubscriptionSeeder extends Seeder
{
    public function run(): void
    {
        $faker = Faker::create();
        $customers = Customer::all();
        $plans = Plan::all();
        $coaches = User::where('role', 'coach')->get();
        $paymentMethods = PaymentMethod::all();
        $registrationDate = now();

        foreach ($customers as $customer) {
            $plan = $plans->random();
            $user = $coaches->random();
            $amount = $plan->price;
            $discount = $faker->optional(0.3)->numberBetween(0, 50) ?? 0;
            $netAmount = $amount - $discount;
            $vatValue = $netAmount * 0.15;
            $total = $netAmount + $vatValue;
            $amountPaid = $faker->optional(0.7)->numberBetween(0, $total);
            $remaining = $total - $amountPaid;
            $startDate = now()->subDay($plan->duration_days);
            $endDate = now()->addDays($plan->duration_days);

            Subscription::create([
                'code' => 'SUB-' . $registrationDate->format('Y') . '-' . str_pad($customer->id, 3, '0', STR_PAD_LEFT),
                'customer_id' => $customer->id,
                'plan_id' => $plan->id,
                'start_date' => $startDate->format('Y-m-d'),
                'end_date' => $endDate->format('Y-m-d'),
                'amount' => $amount ?? 0,
                'discount' => $discount ?? 0,
                'net_amount' => $netAmount ?? 0,
                'vat_value' => $vatValue ?? 0,
                'total' => $total ?? 0,
                'amount_paid' => $amountPaid ?? 0,
                'remaining_paid' => $remaining ?? 0,
                'payment_method_id' => $paymentMethods->random()->id ?? null,
                'status' => $faker->randomElement(['active', 'expired', 'canceled']),
                'notes' => $faker->optional(0.3)->text(100),
                'created_by' => $user->id,
            ]);
        }
    }
}
