<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    /** @use HasFactory<\Database\Factories\UserFactory> */
    use HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'first_name',
        'last_name',
        'email',
        'password',
        'phone',
        'cni',
        'gender',
        'birth_date',
        'birth_place',
        'nationality',
        'residence',
        'address',
        'role',
        'status',
        'registration_number',
        'passport_number',
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var list<string>
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'birth_date' => 'date',
        ];
    }

    /**
     * Relations
     */
    public function projects()
    {
        return $this->belongsToMany(Project::class, 'project_members')
            ->withPivot('joined_at')
            ->withTimestamps();
    }

    public function contributions()
    {
        return $this->hasMany(Contribution::class);
    }

    public function expectedContributions()
    {
        return $this->hasMany(ExpectedContribution::class);
    }

    /**
     * Helpers
     */
    public function isAdmin(): bool
    {
        return $this->role === 'admin';
    }

    public function isAyantDroit(): bool
    {
        return $this->role === 'ayant_droit';
    }

    public function isMembre(): bool
    {
        return in_array($this->role, ['membre', 'admin']);
    }

    public function canManage(): bool
    {
        return $this->isAdmin() || $this->isAyantDroit();
    }

    public function isActive(): bool
    {
        return $this->status === 'active';
    }

    public function getTotalPaidForProject(int $projectId): float
    {
        return $this->contributions()
            ->where('project_id', $projectId)
            ->where('status', 'paye')
            ->sum('amount');
    }

    public function getRemainingBalanceForProject(int $projectId): float
    {
        // Total attendu pour ce projet (jusqu'à aujourd'hui inclus)
        $expected = $this->expectedContributions()
            ->where('project_id', $projectId)
            ->whereDate('due_date', '<=', now())
            ->sum('amount');

        // Total payé pour ce projet
        $paid = $this->getTotalPaidForProject($projectId);

        // Reste à payer (arriérés)
        return max(0, $expected - $paid);
    }

    public function getFullNameAttribute(): string
    {
        return trim(($this->first_name ?? '') . ' ' . ($this->last_name ?? ''));
    }
}
