<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Organization extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'email',
        'phone',
        'logo',
        'address',
        'is_active',
        'country',
        'state',
        'meta',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'meta'      => 'array',
        ];
    }

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

    public function subscription()
    {
        return $this->hasOne(Subscription::class)->latestOfMany();
    }

    /**
     * Return the org-admin-configured feature flags for this organisation.
     * Falls back to all features enabled when nothing has been configured.
     * The super-admin can override plan-level access per tenant via meta.features.
     *
     * @return array{pos:bool,reports:bool,inventory:bool,customers:bool,expenses:bool,api_access:bool}
     */
    public function getOrgFeatures(): array
    {
        $defaults = [
            'pos'        => true,
            'reports'    => true,
            'inventory'  => true,
            'customers'  => true,
            'expenses'   => true,
            'api_access' => true,
        ];

        return array_merge($defaults, (array) ($this->meta['features'] ?? []));
    }

    /**
     * Resolve the feature flags for this organisation's active subscription plan.
     * During an active free trial ALL features are unlocked so the user can
     * experience the full product before choosing a paid plan.
     * Falls back to free-tier defaults when there is no active subscription.
     *
     * @return array{max_users:int,max_products:int,reports_access:bool,api_access:bool,multi_branch:bool}
     */
    public function getPlanFeatures(): array
    {
        $freeDefaults = [
            'max_users'        => 2,
            'max_products'     => 50,
            'max_branches'     => 1,
            'reports_access'   => false,
            'api_access'       => false,
            'multi_branch'     => false,
            'stock_transfer'   => false,
            'audit_trail'      => false,
            'purchases_access' => false,  // Purchases, Suppliers, AR, AP — Professional+ only
        ];

        // All features unlocked during the free trial — full product experience.
        $allFeatures = [
            'max_users'        => -1,
            'max_products'     => -1,
            'max_branches'     => -1,
            'reports_access'   => true,
            'api_access'       => true,
            'multi_branch'     => true,
            'stock_transfer'   => true,
            'audit_trail'      => true,
            'purchases_access' => true,
        ];

        $subscription = $this->subscription;

        if (!$subscription || !in_array($subscription->status, ['active', 'trial'], true)) {
            return $freeDefaults;
        }

        // During the free trial the user experiences the full product.
        if ($subscription->status === 'trial') {
            return $allFeatures;
        }

        // Active paid subscription — return features from the chosen plan.
        $planModel = SubscriptionPlan::where('name', $subscription->plan)->first();

        return array_merge($freeDefaults, $planModel?->features ?? []);
    }
}
