<?php

namespace App\Models;

use App\Services\IdGenerator;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Facades\Image;

class Profile extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<string>
     */
    protected $fillable = [
        'display_name',
        'pronouns',
        'bio',
        'twitter',
        'instagram',
        'youtube',
        'discord',
        'coaster_credits',
        'dark_ride_credits',
        'flat_ride_credits',
        'water_ride_credits',
    ];

    /**
     * Get the user that owns the profile
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the avatar URL or generate a default one
     */
    public function getAvatarUrl(): string
    {
        if ($this->avatar) {
            return Storage::disk('public')->url($this->avatar);
        }

        // Get first letter of username for default avatar
        $firstLetter = strtoupper(substr($this->user->name, 0, 1));
        $avatarPath = "avatars/letters/{$firstLetter}_avatar.png";

        // Check if letter avatar exists, if not use default
        if (Storage::disk('public')->exists($avatarPath)) {
            return Storage::disk('public')->url($avatarPath);
        }

        return asset('images/default-avatar.png');
    }

    /**
     * Set the avatar image
     */
    public function setAvatar($file): void
    {
        if ($this->avatar) {
            Storage::disk('public')->delete($this->avatar);
        }

        $filename = 'avatars/' . uniqid() . '.' . $file->getClientOriginalExtension();
        
        // Process and save the image
        $image = Image::make($file)
            ->fit(200, 200)
            ->encode();

        Storage::disk('public')->put($filename, $image);
        
        $this->update(['avatar' => $filename]);
    }

    /**
     * Generate a letter avatar
     */
    protected function generateLetterAvatar(string $letter): void
    {
        $letter = strtoupper($letter);
        $image = Image::canvas(200, 200, '#007bff');
        
        $image->text($letter, 100, 100, function ($font) {
            $font->file(public_path('fonts/Roboto-Bold.ttf'));
            $font->size(120);
            $font->color('#ffffff');
            $font->align('center');
            $font->valign('center');
        });

        $filename = "avatars/letters/{$letter}_avatar.png";
        Storage::disk('public')->put($filename, $image->encode('png'));
    }

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function (Profile $profile) {
            if (!$profile->profile_id) {
                $profile->profile_id = IdGenerator::generate(Profile::class, 'profile_id');
            }
            if (!$profile->display_name) {
                $profile->display_name = $profile->user->name;
            }
        });

        static::created(function (Profile $profile) {
            // Generate letter avatar if it doesn't exist
            $letter = strtoupper(substr($profile->user->name, 0, 1));
            $avatarPath = "avatars/letters/{$letter}_avatar.png";
            
            if (!Storage::disk('public')->exists($avatarPath)) {
                $profile->generateLetterAvatar($letter);
            }
        });
    }
}