<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Schema;

class StageAcademyActivation extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'user_id',
        'course_id',
        'price',
        'payment_method',
        'invoice_number',
        'created_by',
    ];

    public function user(): BelongsTo
    {
        return $this->belongsTo(StageAcademyUser::class, 'user_id');
    }

    public function course(): BelongsTo
    {
        return $this->belongsTo(StageAcademyCourse::class, 'course_id');
    }

    public function creator(): BelongsTo
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public static function generateNextInvoiceNumber(): string
    {
        if (! Schema::hasTable('stage_academy_activations')) {
            return 'CPP-SA-1001';
        }

        $maxNum = self::query()
            ->where('invoice_number', 'LIKE', 'CPP-SA-%')
            ->pluck('invoice_number')
            ->map(function ($invoiceNumber) {
                if (preg_match('/CPP-SA-(\d+)/', (string) $invoiceNumber, $matches)) {
                    return (int) $matches[1];
                }

                return 0;
            })
            ->max() ?? 0;

        $nextNum = $maxNum + 1;

        if ($nextNum < 1001) {
            $nextNum = 1001;
        }

        return 'CPP-SA-'.$nextNum;
    }
}
