<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;

class Plan extends Model
{
    protected $fillable = [
        'stripe_price_id',
        'name',
        'title',
        'description',
        'price',
        'public_page_limit',
        'page_creation_limit',
        'paid',
    ];

    protected $appends = ['discount'];

    protected function casts(): array
    {
        return [
            'price' => 'double',
            'paid' => 'boolean'
        ];
    }

    protected function discount(): Attribute {
        return Attribute::make(
            get: function () {
                if ($this->name !== 'advanced') return 0;
                $starter = self::whereName('starter')->first();
                $perCharges = [
                    'advanced' => $this->price / ($this->public_page_limit + $this->page_creation_limit),
                    'starter' => $starter->price / ($starter->public_page_limit + $starter->page_creation_limit),
                ];
                $percent = ($perCharges['starter'] - $perCharges['advanced']) / $perCharges['starter'];
                return ceil($percent * 100);
            },
        );
    }

    public function users() {
        return $this->hasMany(User::class);
    }
}
