<?php

namespace App\Models;

use Illuminate\Support\Carbon;
use Illuminate\Database\Eloquent\Model;
use Backpack\CRUD\app\Models\Traits\CrudTrait;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class Subscription extends Model
{
    use CrudTrait;
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'customer_name',
        'email1',
        'email2',
        'email3',
        'phone1',
        'phone2',
        'phone3',
        'product_id',
        'start_date',
        'contract_value',
        'active',
        'updated_by',
        'user_id',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'id' => 'integer',
        'product_id' => 'integer',
        'start_date' => 'datetime',
        'active' => 'boolean',
        'updated_by' => 'integer',
        'user_id' => 'integer',
    ];

    public function product(): BelongsTo
    {
        return $this->belongsTo(Product::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function getNextAnniversaryAttribute()
    {
        // Get the start date as a Carbon instance
        $startDate = Carbon::parse($this->start_date);

        // Create the anniversary date for the current year
        $nextAnniversary = $startDate->copy()->year(Carbon::now()->year);

        // If the calculated anniversary has already passed this year, set it to the next year
        if ($nextAnniversary->isPast()) {
            $nextAnniversary->addYear();
        }

        return $nextAnniversary;
    }
}
