<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Textblock extends Model {
    const TEXTBLOCKTYPE_ORDERMAIL = 0; # Normale Auftragsemails, wählbar im Auftrag, bearbeitbar
    const TEXTBLOCKTYPE_APPOINTMENTMAIL = 1; # Textbaustein für Terminemail, hier sollte es logischerweise nur eine geben

    public function getLabelForTextblockType() {
        $labels[self::TEXTBLOCKTYPE_ORDERMAIL] = "E-Mail";
        $labels[self::TEXTBLOCKTYPE_APPOINTMENTMAIL] = "E-Mail für Terminversand";

        if (array_key_exists($this->type, $labels))
            return $labels[$this->type];
        else
            return "";
    }


    public function subjectExcerpt($maxLength) {
        return $this->excerpt($this->subject, $maxLength);
    }

    public function textExcerpt($maxLength) {
        return $this->excerpt($this->text, $maxLength);
    }

    private function excerpt($text, $maxLength) {
        if (strlen($text) <= $maxLength) {
            return $text;
        }

        if (strlen($text) > $maxLength) {
            $text = substr($text, 0, $maxLength + 1);
            if ($last_space = strrpos($text, ' ')) {
                $text = substr($text, 0, $last_space);
                $text = rtrim($text);
            }
            $text .= '...';
        }

        return $text;
    }


    # Gibt die höchste ID der Tabelle zurück
    public function getLastId() {
        $lastId = DB::table('textblocks')
            ->select(DB::RAW('MAX(id) AS id'))
            ->first();
        return $lastId->id;
    }
}
