'boolean', 'use_count' => 'integer', 'last_used_at' => 'datetime', ]; /** * مقادیر پیش‌فرض روی instance — برای اینکه در لحظهٔ create * (و قبل از refresh از DB) مقدار use_count/is_default در دسترس باشد. * SQLite مقادیر default ستون‌ها را بلافاصله روی مدل در حافظه بازنویسی نمی‌کند. */ protected $attributes = [ 'use_count' => 0, 'is_default' => false, ]; // === Relationships === public function user(): BelongsTo { return $this->belongsTo(User::class); } // === Scopes === public function scopeForUser($query, int $userId) { return $query->where('user_id', $userId); } public function scopeOfRole($query, string $role) { return $query->where('role', $role); } // === Helpers === /** * داده‌های آمادهٔ پر کردن فیلدهای فرم سفارش * کلیدها عیناً با prefix نقش مطابق فرم وردپرس برمی‌گردند. */ public function toFormFieldData(): array { $prefix = $this->role === self::ROLE_SENDER ? 'sender' : 'receiver'; return [ 'id' => $this->id, 'role' => $this->role, 'label' => $this->label, 'is_default' => $this->is_default, "{$prefix}_name" => $this->name, "{$prefix}_phone" => $this->phone, "{$prefix}_state" => $this->state, "{$prefix}_city" => $this->city, "{$prefix}_postal_code" => $this->postal_code, "{$prefix}_national_id" => $this->national_id, "{$prefix}_address" => $this->address, ]; } /** * پیدا کردن رکورد تکراری (همان نقش + همان تلفن + همان آدرس) * برای جلوگیری از انباشت رکوردهای دوباره هنگام «ذخیره این آدرس». */ public static function findDuplicate(int $userId, string $role, string $phone, string $address): ?self { return static::forUser($userId) ->ofRole($role) ->where('phone', $phone) ->where('address', $address) ->first(); } /** * ثبت استفاده: افزایش شمارنده و بروزرسانی زمان آخرین استفاده */ public function markUsed(): void { $this->increment('use_count'); $this->forceFill(['last_used_at' => now()])->save(); } /** * این رکورد را پیش‌فرض نقش خودش می‌کند (سایر رکوردهای همان نقش off می‌شوند) */ public function makeDefault(): void { static::forUser($this->user_id) ->ofRole($this->role) ->where('id', '!=', $this->id) ->update(['is_default' => false]); $this->forceFill(['is_default' => true])->save(); } /** * برچسب نمایشی در dropdown فرم */ public function getDisplayLabelAttribute(): string { $parts = []; if ($this->label) { $parts[] = $this->label; } $parts[] = $this->name; if ($this->city) { $parts[] = $this->city; } return implode(' — ', $parts); } }