<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Client extends Model
{
    use HasFactory;

    protected $fillable = [
        'company_name',
        'contact_person',
        'email',
        'phone',
        'website',
        'sector',
        'status',
        'onboarding_status',
        'onboarding_step',
        'onboarding_completed_at',
        'onboarding_meta',
        'currency_code',
        'timezone',
        'report_language',
        'logo_path',
        'primary_color',
        'notes',
        'internal_notes',
        'report_recipients',
        'portal_enabled',
        'portal_welcome_text',
        'created_by',
    ];

    protected $casts = [
        'report_recipients' => 'array',
        'portal_enabled' => 'boolean',
        'onboarding_meta' => 'array',
        'onboarding_completed_at' => 'datetime',
    ];

    public function platformConnections(): HasMany
    {
        return $this->hasMany(PlatformConnection::class);
    }

    public function reportSchedules(): HasMany
    {
        return $this->hasMany(ReportSchedule::class);
    }

    public function generatedReports(): HasMany
    {
        return $this->hasMany(GeneratedReport::class);
    }

    public function alertRules(): HasMany
    {
        return $this->hasMany(AlertRule::class);
    }

    public function alertLogs(): HasMany
    {
        return $this->hasMany(AlertLog::class);
    }

    public function brandKits(): HasMany
    {
        return $this->hasMany(BrandKit::class);
    }

    public function defaultBrandKit(): ?BrandKit
    {
        return $this->brandKits()
            ->active()
            ->where('is_default', true)
            ->orderBy('sort_order')
            ->first();
    }

    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class)
            ->withPivot(['role', 'is_active', 'permissions', 'last_portal_login_at'])
            ->withTimestamps();
    }

    public function operationTasks(): HasMany
    {
        return $this->hasMany(OperationTask::class);
    }

    public function onboardingIsComplete(): bool
    {
        return $this->onboarding_status === 'completed';
    }

    public function onboardingBadgeClass(): string
    {
        return match ($this->onboarding_status) {
            'completed' => 'badge-success',
            'in_progress' => 'badge-warning',
            'needs_review' => 'badge-danger',
            default => 'badge-secondary',
        };
    }

    public function onboardingStatusLabel(): string
    {
        return match ($this->onboarding_status) {
            'completed' => 'Tamamlandı',
            'in_progress' => 'Devam Ediyor',
            'needs_review' => 'Kontrol Gerekli',
            default => 'Başlamadı',
        };
    }
}
