<?php

namespace App\Models;

use App\Notifications\ContractSigned;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Contract extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $guarded = [];
    /**
     * The attributes that should be cast.
     *
     * @var array
     */
    protected $casts = [
        'start_date' => 'datetime:Y-m-d',
        'contractor_signed_at' => 'datetime:Y-m-d',
        'user_signed_at' => 'datetime:Y-m-d',
        'due_date' => 'datetime:Y-m-d',
    ];

    public function user()
    {
        return $this->belongsTo(User::class)->withTrashed();
    }

    public function proposal()
    {
        return $this->belongsTo(Proposal::class);
    }

    public function project()
    {
        return $this->belongsTo(Project::class);
    }

    public function contractor()
    {
        return $this->morphTo();
    }

    public function userSign()
    {
        $this->update([
            'user_signed_at' => now(),
        ]);
        $this->save();
    }

    public function contractorSign()
    {
        $days = 0;
        foreach ($this->proposal->milestones as $milestone) {
            $days += $milestone->duration + 1;
            $milestone->update([
                'start_date' => now()->addWeekdays($days-$milestone->duration),
                'due_date' => now()->addWeekdays($days),
            ]);
            $milestone->save();
        }
        $this->update([
            'contractor_signed_at' => now(),
            'start_date' => now(),
            'due_date' => now()->addWeekdays($days),
        ]);
        $this->save();
        $this->project->update([
            'status'=> 'Processing',
           // TODO:: I think we need to update this to match the contract
           // 'amount' => $amount,
        ]);
        $this->project->user->notify(new ContractSigned($this));
        return $this;
    }
}
