<?php

namespace App\Traits;

use App\Models\Deliverable;
use App\Models\Milestone;
use Exception;
use Illuminate\Support\Facades\DB;

trait HasMilestones
{

    public function addMilestone(array $milestone)
    {
        try {
            $transaction = DB::transaction(function () use ($milestone) {
                $newMileStone = $this->milestones()->create([
                    'name' => $milestone['name'],
                    'amount' => $milestone['amount'],
                    'duration' => $milestone['duration'],
                ]);
                if (isset($milestone['deliverables'])) {
                    foreach ($milestone['deliverables'] as $deliverable) {
                        $newMileStone->deliverables()->create([
                            'name' => $deliverable['name'],
                        ]);
                    }
                }
                        });
            return is_null($transaction) ? back(303)->with(['success' => 'success']) : $transaction;
        } catch (Exception $exception) {
            return back(303)->with(['error' => $exception->getMessage()]);
        }
    }

    public function milestones()
    {
        return $this->morphMany(Milestone::class, 'milestonable');
    }

    public function deliverables()
    {
        $deliverables = [];
        foreach ($this->milestones()->get() as $milestone) {
            $deliverables[] = $milestone->deliverables()->get();
        }
        return collect($deliverables)->flatten();
    }
}
