<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Str;

class ProgressPhoto extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id',
        'image_path',
        'after_image_path',
        'type',
        'time_period',
        'weight',
        'date',
        'is_public',
        'public_token',
        'views_count',
        'likes_count',
        'shared_at',
    ];

    protected $casts = [
        'date' => 'date',
        'weight' => 'decimal:2',
        'is_public' => 'boolean',
        'views_count' => 'integer',
        'likes_count' => 'integer',
        'shared_at' => 'datetime',
    ];

    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function comments(): HasMany
    {
        return $this->hasMany(PhotoComment::class, 'progress_photo_id');
    }

    public function likes(): HasMany
    {
        return $this->hasMany(PhotoLike::class, 'progress_photo_id');
    }

    public function getImagePathAttribute($value)
    {
        if (!$value) return null;
        if (str_starts_with($value, 'http')) return $value;
        if (str_starts_with($value, '/storage/')) return $value;
        return '/storage/' . $value;
    }

    public function getAfterImagePathAttribute($value)
    {
        if (!$value) return null;
        if (str_starts_with($value, 'http')) return $value;
        if (str_starts_with($value, '/storage/')) return $value;
        return '/storage/' . $value;
    }

    /**
     * Generate and assign a public token
     */
    public function makePublic(): void
    {
        if (!$this->public_token) {
            $this->public_token = Str::random(32);
        }
        $this->is_public = true;
        $this->shared_at = now();
        $this->save();
    }

    /**
     * Make photo private
     */
    public function makePrivate(): void
    {
        $this->is_public = false;
        $this->save();
    }

    /**
     * Increment views counter
     */
    public function incrementViews(): void
    {
        $this->increment('views_count');
    }

    /**
     * Get public URL
     */
    public function getPublicUrl(): ?string
    {
        if (!$this->is_public || !$this->public_token) {
            return null;
        }
        return url("/share/photo/{$this->public_token}");
    }
}
