<?php

namespace App\Models;

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

class CustomVariable extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'key',
        'value',
        'type',
        'description',
        'is_global',
    ];

    protected $casts = [
        'is_global' => 'boolean',
    ];

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

    public static function replaceVariables($text, $userId, $customVars = [])
    {
        // Get all user's variables
        $variables = self::where('user_id', $userId)->get();
        
        foreach ($variables as $variable) {
            $placeholder = '{' . $variable->key . '}';
            $text = str_replace($placeholder, $variable->value, $text);
        }

        // Replace custom variables passed in
        foreach ($customVars as $key => $value) {
            $placeholder = '{' . $key . '}';
            $text = str_replace($placeholder, $value, $text);
        }

        return $text;
    }

    public function getFormattedValue()
    {
        switch ($this->type) {
            case 'number':
                return (float) $this->value;
            case 'date':
                return \Carbon\Carbon::parse($this->value)->format('Y-m-d');
            case 'json':
                return json_decode($this->value, true);
            default:
                return $this->value;
        }
    }
}
