<?php

namespace App;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;

class Operator extends Model {
    # Mandant
    public function client() {
        return $this->belongsTo(Client::class);
    }

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

    public function getName() {
        return $this->name . " " . $this->firstname;
    }

    # Bearbeiter-Bild
    public function getImage() {
        if ($this->image != NULL)
            return Storage::disk("uploads")->url($this->image);
        else {
            # Überprüfen, ob Bearbeiter einen hinterlegten User hat und dann ggf. dessen Bild ausgeben
            if($this->user != NULL) {
                return $this->user->getImage();
            }
            return "/images/dummy.svg";
        }
    }

    # Aufträge mit Termin
    public function orders() {
        return $this->belongsToMany(Orders::class, 'order_appointment_operator')->withPivot('appointment_from', 'appointment_to');
    }

    public function projects() {
        return $this->belongsToMany(Project::class, 'project_operator_responsible');
    }

    # Alle Wiedervorlagen
    public function followUps() {
        return $this->hasMany(OrderFollowUp::class)->orderBy('nextUp', 'asc');
    }

    # Wiedervorlagen bis heute oder ab morgen
    public function followUpsTempus($timeSpan = "untilToday") {

        $followUpsFuture = array();

        foreach ($this->followUps as $followUp) {

            $cFollowUp = clone $followUp;

            $nextUp = Carbon::createFromFormat("Y-m-d H:i:s", $cFollowUp->nextUp);

            $timeCheck = false;
            if ($timeSpan == "untilToday") {
                if ($nextUp->isToday() or $nextUp->isPast()) {
                    $timeCheck = true;
                }
            }
            elseif ($timeSpan == "future") {
                if ($nextUp->isFuture()) {
                    $timeCheck = true;
                }
            }

            if ($timeCheck) {
                // Datum formatieren
                $cFollowUp->nextUp = $nextUp->format("d.m.Y");

                // Leere Notiz ersetzen
                if ($cFollowUp->note == "") $cFollowUp->note = "-";

                $followUpsFuture[] = $cFollowUp;
            }
        }

        return $followUpsFuture;
    }

    public function otherFollowUps() {
        return OrderFollowUp::where('operator_id', '!=', $this->id)->orderBy("nextUp")->get();
    }
}
