<?php
namespace App\Models;

class CommissionRule
{
    public $id;
    public $rule_type;
    public $formula_type;
    public $title;
    public $salesperson_user_id;
    public $product_id;
    public $valid_from;
    public $valid_to;
    public $target_users;
    public $requested_services;
    public $base_amount;
    public $fixed_budget_amount;
    public $base_rate_percent;
    public $reward_percentage;
    public $budget_source_type;
    public $standard_tier_rate_percent;
    public $collection_modifier_percent;
    public $allow_collection_modifier_override;
    public $is_active;
    public $status;
    public $created_by_user_id;
    public $updated_by_user_id;
    public $deleted_by_user_id;
    public $created_at;
    public $updated_at;
    public $deleted_at;

    // Optional assignment-history projection fields.
    public $assignment_id;
    public $scope_type;
    public $assigned_at;
    public $disabled_at;
    public $assigned_by_user_id;
    public $disabled_by_user_id;
    public $disable_reason;

    public function __construct(array $data = [])
    {
        foreach ($data as $key => $value) {
            if (property_exists($this, $key)) {
                $this->$key = $value;
            }
        }
    }

    public function getTargetUsersArray(): array
    {
        if (is_array($this->target_users)) {
            return $this->target_users;
        }
        $decoded = json_decode((string)$this->target_users, true);
        return is_array($decoded) ? $decoded : [];
    }

    public function setTargetUsersArray(array $users): void
    {
        $this->target_users = json_encode(array_values($users), JSON_UNESCAPED_UNICODE);
    }

    public function getRequestedServicesArray(): array
    {
        if (is_array($this->requested_services)) {
            return $this->requested_services;
        }
        $decoded = json_decode((string)$this->requested_services, true);
        return is_array($decoded) ? $decoded : [];
    }

    public function toArray(): array
    {
        return get_object_vars($this);
    }
}
