<?php

namespace App\Http\Controllers;

use App\OrderFollowUp;
use App\Orders;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;

use App\User;
use App\Client;
use App\Http\Controllers\OrderLogsController;

use JsValidator;

class OrderFollowUpController extends Controller {

    private $orderFollowUpValidationRules = [
        'note' => 'string|max:200'
    ];

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

        # Wiedervorlagen für Heute oder aus der Vergangenheit holen
        $followUpsUntilToday = $loggedUser->operator->followUpsTempus();

        # Wiedervorlagen für Zukunft holen
        $followUpsFuture = $loggedUser->operator->followUpsTempus("future");

        # Wenn berechtigt, Wiedervorlagen anderer Nutzer holen
        $otherFollowUps = $loggedUser->operator->otherFollowUps();

        $parameters = ["followUpsUntilToday" => $followUpsUntilToday,
            "followUpsFuture" => $followUpsFuture,
            "otherFollowUps" => $otherFollowUps];

        return View::make('order_follow_ups.list')->with($parameters);
    }

    public function edit($orderId = 0, $orderFollowUpId = 0) {
        $loggedUser = User::find(Auth::user()->id);

        # Auftragsliste lesen - nur Auftragsnummern
        $orderIdsList = $loggedUser->client->orders->pluck('order_number', 'id');

        # Datum vorbelegen mit heute + eine Woche
        $nextUp = (new Carbon())->addWeeks(1)->toDateString();

        $mode = "new";

        # Bearbeiter holen
        $operatorsList = $loggedUser->client->operatorsWithUser;
        $operatorSelected = $loggedUser->operator->id;

        # Wiedervorlage lesen, falls gegeben
        $followUp = new OrderFollowUp();

        if ($orderFollowUpId <> 0) {
            $followUp = OrderFollowUp::find($orderFollowUpId);
            if ($followUp <> null) {
                $orderId = $followUp->order_id;
                $operatorSelected = $followUp->operator_id;
                $c = Carbon::createFromFormat("Y-m-d H:i:s", $followUp->nextUp);
                $nextUp = $c->toDateString();
                $mode = "update";

                # Ist Wiedervorlage von anderem Nutzer?
                if ($loggedUser->operator->id != $followUp->operator_id) {
                    if (!UserController::checkRight("editFollowUps", $loggedUser)) {
                        return response()->json(['response' => 'error', 'message' => 'Keine Berechtigung.']);
                    }
                }

            }
        }

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

        $arguments = ["validator" => $frontValidator,
            "orderIdsList" => $orderIdsList,
            "orderIdSelected" => $orderId,
            "followUp" => $followUp,
            "followUpId" => $orderFollowUpId,
            "mode" => $mode,
            "operatorsList" => $operatorsList,
            "operatorSelected" => $operatorSelected,
            "loggedUser" => $loggedUser,
            "nextUp" => $nextUp];

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

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

    public function store() {

        $loggedUser = User::find(Auth::user()->id);

        # Input validieren
        $backValidator = Validator::make(request()->all(), $this->orderFollowUpValidationRules);

        if ($backValidator->fails()) {
            return response()->json(['response' => 'error', 'message' => 'Validierungsfehler']);
        }

        # Daten aus Request holen und konvertieren
        $newFollowUpData = json_decode(request()->get('data'));

        # Ist Wiedervorlage für anderen Nutzer?
        if ($loggedUser->operator->id == $newFollowUpData->operator_id)
            $followUpFor = "own";
        else $followUpFor = "notown";

        # ggf. Berechtigung überprüfen
        if ($followUpFor == "notown") {
            if (!UserController::checkRight("editFollowUps", $loggedUser)) {
                return response()->json(['response' => 'error', 'message' => 'Keine Berechtigung.']);
            }
        }

        $newFollowUp = self::createNewFollowUp($newFollowUpData->order_id, $newFollowUpData->operator_id,
            $newFollowUpData->note, $newFollowUpData->nextUp);

        if (!$newFollowUp)
            return response()->json(['response' => 'error', 'message' => 'Wiedervorlage nicht gespeichert.']);

        try {
            $newFollowUp->save();
        } catch (\Exception $e) {
            return response()->json(['response' => 'error', 'message' => 'Wiedervorlage nicht gespeichert.']);
        }

        # Log schreiben
        if ($followUpFor == "own") {
            OrderLogsController::writeLog(19, $newFollowUpData->order_id, $loggedUser->operator->id,
                ["{ORDERNUMBER}" => $newFollowUp->order->order_number]);
        }
        else {
            OrderLogsController::writeLog(20, $newFollowUpData->order_id, $loggedUser->operator->id,
                ["{ORDERNUMBER}" => $newFollowUp->order->order_number, "{OTHEROPERATOR}" => $newFollowUp->operator->getName()]);
        }

        # Für die Vorblendung Datum lesbar formatieren
        $newFollowUp->nextUp = $newFollowUp->nextUp->format("d.m.Y");
        $newFollowUp->operatorName = $newFollowUp->operator->getName();
        $newFollowUp->orderNumber = $newFollowUp->order->order_number;

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

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

        # Input validieren
        $backValidator = Validator::make(request()->all(), $this->orderFollowUpValidationRules);

        if ($backValidator->fails()) {
            return response()->json(['response' => 'error', 'message' => 'Validierungsfehler']);
        }

        # Daten aus Request holen und konvertieren
        $newFollowUpData = json_decode(request()->get('data'));
        $followUpId = json_decode(request()->get('followUpId'));

        # Ist Wiedervorlage für anderen Nutzer?
        if ($loggedUser->operator->id == $newFollowUpData->operator_id)
            $followUpFor = "own";
        else $followUpFor = "notown";

        # ggf. Berechtigung überprüfen
        if ($followUpFor == "notown") {
            if (!UserController::checkRight("editFollowUps", $loggedUser)) {
                return response()->json(['response' => 'error', 'message' => 'Keine Berechtigung.']);
            }
        }

        # Wiedervorlage holen
        $followUp = OrderFollowUp::find($followUpId);
        if ($followUp == null)
            return response()->json(['response' => 'error', 'message' => 'Wiedervorlage nicht gefunden.']);


        # Neue Daten setzen
        $followUp->order_id = $newFollowUpData->order_id;
        $followUp->operator_id = $newFollowUpData->operator_id;
        $followUp->note = $newFollowUpData->note;
        $followUp->nextUp = $newFollowUpData->nextUp;

        try {
            $followUp->save();
        } catch (\Exception $e) {
            return response()->json(['response' => 'error', 'message' => 'Wiedervorlage nicht gespeichert.']);
        }

        # Für die Vorblendung Datum lesbar formatieren
        $nextUp = Carbon::createFromFormat("Y-m-d", $followUp->nextUp);
        $followUp->nextUp = $nextUp->format("d.m.Y");
        $followUp->operatorName = $followUp->operator->getName();
        $followUp->orderNumber = $followUp->order->order_number;

        return response()->json(['response' => 'success', 'newFollowUp' => json_decode($followUp), 'mode' => 'update', 'followUpFor' => $followUpFor]);

    }

    public static function createNewFollowUp($orderId, $operatorId, $note, $date) {
        # Neue Wiedervorlage erstellen
        $newFollowUp = new OrderFollowUp();

        $newFollowUp->order_id = $orderId;
        $newFollowUp->operator_id = $operatorId;
        $newFollowUp->note = $note;

        # Datum datenbankkonform konvertieren
        $nextUp = Carbon::createFromFormat("Y-m-d", $date);
        $newFollowUp->nextUp = $nextUp;

        try {
            $newFollowUp->save();
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return false;
        }

        return $newFollowUp;
    }

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

        # Wiedervorlage suchen
        $followUp = OrderFollowUp::find($followUpId);

        if ($followUp == null)
            return redirect()->route('orderFollowUp.list')->withErrors("Wiedervorlage konnte nicht gefunden werden.");

        # Ist Wiedervorlage von anderem Nutzer?
        if ($loggedUser->operator->id == $followUp->operator_id)
            $followUpFor = "own";
        else $followUpFor = "notown";

        # Berechtigung prüfen
        if ($followUpFor == "notown") {
            if (!UserController::checkRight("editFollowUps", $loggedUser)) {
                return redirect()->route('orderFollowUp.list')->withErrors("Keine Berechtigung.");
            }
        }


        $operatorName = $followUp->operator->getName();
        $orderId = $followUp->order_id;
        $orderNumber = $followUp->order_number;


        try {
            $followUp->delete();
        } catch (\Exception $e) {
            return redirect()->route('orderFollowUp.list')->withErrors("Wiedervorlage konnte nicht gelöscht werden.");
        }

        # Log schreiben
        if ($followUpFor == "own") {
            OrderLogsController::writeLog(21, $orderId, $loggedUser->operator->id,
                ["{ORDERNUMBER}" => $orderNumber]);
        }
        else {
            OrderLogsController::writeLog(22, $orderId, $loggedUser->operator->id,
                ["{ORDERNUMBER}" => $orderNumber, "{OTHEROPERATOR}" => $operatorName]);
        }

        return redirect()->route('orderFollowUp.list')->with("message", "Wiedervorlage wurde erfolgreich gelöscht.");
    }

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

        $followUpId = request()->get("followupid");

        # Wiedervorlage suchen
        $followUp = OrderFollowUp::find($followUpId);

        if ($followUp == null)
            return response()->json(['response' => 'error', 'message' => 'Wiedervorlage konnte nicht gefunden werden.']);

        # Ist Wiedervorlage von anderem Nutzer?
        if ($loggedUser->operator->id == $followUp->operator_id)
            $followUpFor = "own";
        else $followUpFor = "notown";

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


        $operatorName = $followUp->operator->getName();
        $orderId = $followUp->order_id;
        $orderNumber = $followUp->order_number;

        try {
            $followUp->delete();
        } catch (\Exception $e) {
            return response()->json(['response' => 'error', 'message' => 'Wiedervorlage konnte nicht gelöscht werden.']);
        }

        # Log schreiben
        if ($followUpFor == "own") {
            OrderLogsController::writeLog(21, $orderId, $loggedUser->operator->id,
                ["{ORDERNUMBER}" => $orderNumber]);
        }
        else {
            OrderLogsController::writeLog(22, $orderId, $loggedUser->operator->id,
                ["{ORDERNUMBER}" => $orderNumber, "{OTHEROPERATOR}" => $operatorName]);
        }

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

}
