<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Project extends Model
{
    protected $fillable = [
        'name',
        'customer_id',
        'programmer_id',
        'total_price',
        'commission_amount',
        'progress_percent',
        'status',
        'notes',
        'start_date',
        'end_date',
        'invoice_id',
    ];

    protected $casts = [
        'total_price' => 'decimal:2',
        'commission_amount' => 'decimal:2',
        'progress_percent' => 'integer',
        'start_date' => 'date',
        'end_date' => 'date',
    ];

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

    public function programmer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'programmer_id');
    }

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

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

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


    /**
     * Get the amount already paid to the programmer for this project.
     */
    public function getPaidToProgrammerAttribute()
    {
        return $this->payments()->sum('amount');
    }

    /**
     * Get the remaining commission amount to be paid to the programmer.
     */
    public function getRemainingProgrammerBalanceAttribute()
    {
        return $this->commission_amount - $this->paid_to_programmer;
    }
}
