<?php

namespace App\Models;

use App\Models\Traits\HasHexId;
use Illuminate\Database\Eloquent\Model;

class Creator extends Model
{
    use HasHexId {
        toArray as hexIdToArray;
    }

    protected $table = 'creators';
    public $incrementing = false;
    protected $keyType = 'string';

    protected $fillable = [
        'id', 'organization_id', 'created_by_id', 'creator_name',
        'tiktok_link', 'tiktok_cid', 'instagram_link', 'facebook_link',
        'contact_email', 'contact_phone', 'contact_zalo',
        'followers', 'gmv', 'items', 'average_views', 'audience', 'advantages',
        'address', 'notes', 'content'
    ];

    protected $casts = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    protected $appends = ['classification'];

    public function setFollowersAttribute($value)
    {
        $this->attributes['followers'] = ($value === '' || $value === null) ? 0 : (string)$value;
    }

    public function setGmvAttribute($value)
    {
        $this->attributes['gmv'] = ($value === '' || $value === null) ? 0 : (string)$value;
    }

    public function setItemsAttribute($value)
    {
        $this->attributes['items'] = ($value === '' || $value === null) ? 0 : (string)$value;
    }

    public function setAverageViewsAttribute($value)
    {
        $this->attributes['average_views'] = $value === '' ? null : (string)$value;
    }

    public function organization()
    {
        return $this->belongsTo(Organization::class, 'organization_id', 'id');
    }

    public function createdBy()
    {
        return $this->belongsTo(User::class, 'created_by_id', 'id');
    }

    public function bookings()
    {
        return $this->hasMany(Booking::class, 'creator_id', 'id');
    }

    public function getClassificationAttribute()
    {
        $followers = (int)($this->attributes['followers'] ?? 0);

        if ($followers >= 100000) {
            return 'Macro KOC';
        }
        if ($followers >= 10000) {
            return 'Micro KOC';
        }
        if ($followers >= 1000) {
            return 'Nano KOC';
        }

        return '';
    }

    public function toArray()
    {
        $data = $this->hexIdToArray();
        if (array_key_exists('organization_id', $data)) {
            $data['organization_id'] = (string)($this->formatBinaryToHex($this->attributes['organization_id'] ?? null) ?? $data['organization_id']);
        }
        if (array_key_exists('created_by_id', $data)) {
            $data['created_by_id'] = (string)($this->formatBinaryToHex($this->attributes['created_by_id'] ?? null) ?? $data['created_by_id']);
        }
        return $data;
    }
}
