<?php

namespace App\Http\Controllers;

use App\User;
use App\Client;
use App\Operator;
use App\Orders;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Log;
use JsValidator;

use App\OrderLogs;
use App\OrderLogSysMsg;

class OrderLogsController extends Controller {
    private $orderLogValidationRules = [
        "text" => "required|string|max:255"
    ];

    public function create($orderId) {
        $loggedUser = User::find(Auth::user()->id);

        # Berechtigung prüfen
        if (!UserController::checkRight("editOrders", $loggedUser))
            return response()->json(['response' => 'error', 'message' => 'Keine Berechtigung.']);

        # Bearbeiter-ID des Nutzers holen
        $operatorId = $loggedUser->operator->id;

        # Für die Vorblendung im View Namen des Bearbeiters holen
        $operatorLabel = $loggedUser->operator->name . " " . $loggedUser->operator->firstname;

        # Validierung
        $frontValidator = JsValidator::make($this->orderLogValidationRules, [], [], "#addOrderLog");

        $arguments = ["orderID" => $orderId,
            "operatorID" => $operatorId,
            "operatorLabel" => $operatorLabel,
            "validator" => $frontValidator];

        # View rendern
        $editorHTML = View::make('order_logs.create')->with($arguments)->render();

        return response()->json(['response' => 'success', 'editorHTML' => $editorHTML]);
    }


    public static function writeLog($messageID, $orderID, $operatorID, $placeholders = array(), $logType = OrderLogs::LOGTYPE_SYSLOG) {
        $now = new \DateTime();

        $order = Orders::find($orderID);
        if ($order == null) return false;

        $logEntry = new OrderLogs();
        $logEntry->order_id = $order->id;
        $logEntry->operator_id = $operatorID;
        $logEntry->type = $logType;
        $logEntry->created = $now->format("Y-m-d H:i:s");

        # Namen des Bearbeiters holen, wird in den meisten Logs gebraucht
        $operator = Operator::find($operatorID);

        # Wenn Bearbeiter nicht gefunden wird, braucht kein Log geschrieben zu werden - sinnlos
        if ($operator == null) return false;

        # Platzhalter setzen
        $standardPlaceholders = ["{ORDERNUMBER}" => $order->order_number,
            "{OPERATORID}" => $operatorID,
            "{OPERATORNAME}" => $operator->getName()];

        $placeholders = array_merge($placeholders, $standardPlaceholders);

        # Nachricht erzeugen
        $logEntry->text = self::makeLogMessage($messageID, $placeholders);

        # Speichern
        try {
            $logEntry->save();
        } catch (\Exception $e) {
            Log::error("Fehler beim Wegschreiben des Orderlogs: " . $e->getMessage());
            return false;
        }
        return true;
    }

    public static function writeCustomLog($message, $orderID, $operatorID, $logType = OrderLogs::LOGTYPE_USRLOG) {

        $operator = Operator::find($operatorID);

        # Wenn Bearbeiter nicht gefunden wird, braucht kein Log geschrieben zu werden - sinnlos
        if ($operator == null) return false;

        $now = new \DateTime();

        $logEntry = new OrderLogs();
        $logEntry->order_id = $orderID;
        $logEntry->operator_id = $operatorID;
        $logEntry->type = $logType;
        $logEntry->text = $message;
        $logEntry->created = $now->format("Y-m-d H:i:s");

        # Speichern
        try {
            $logEntry->save();
        } catch (\Exception $e) {
            Log::error("Fehler beim Wegschreiben des Orderlogs: " . $e->getMessage());
            return false;
        }
        return true;
    }

    # Log-Nachricht aus der Tabelle order_log_sys_msgs mit Platzhaltern füllen
    public static function makeLogMessage($messageID, Array $placeholders) {

        # Vorgefertigte Nachricht holen
        $messageStub = OrderLogSysMsg::find($messageID);

        if ($messageStub == null) return false;

        $messageStub = $messageStub->message;

        # Platzhalter trennen
        $placeholderKeys = array_keys($placeholders);
        $placeholderValues = array_values($placeholders);

        $message = str_replace($placeholderKeys, $placeholderValues, $messageStub);

        return $message;
        # Beispiel für eine Platzhalter-Tabelle
        # $placeholders["{NAME}"] = "Lotta";
        # $placeholders["{STATUS}"] = "wichtig";
    }


}
