<?php

namespace App\Http\Controllers;

use App\OrderCreditNote;
use Illuminate\Http\Request;

use App\User;
use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\View;
use JsValidator;

class OrderCreditNoteController extends Controller {
    private $orderCreditNoteValidationRules = [
        'date' => 'required',
        'fetch_number' => 'numeric',
        'credit_note_number' => 'required|numeric',
        'credit_note_value' => 'required|regex:/^\d*(\,\d{1,2})?$/',
        'reference_number' => 'numeric',
    ];

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

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

        # Neue Gutschrift erstellen
        if ($orderCreditNoteId == 0) {
            $orderCreditNote = new OrderCreditNote();
        }
        # Gutschrift bearbeiten
        else {
            # Gutschrift finden
            $orderCreditNote = OrderCreditNote::find($orderCreditNoteId);
            if ($orderCreditNote == null) {
                return response()->json(['response' => 'error', 'message' => 'Gutschrift nicht gefunden.']);
            }
        }

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

        $arguments = ["orderCreditNote" => $orderCreditNote,
            "validator" => $frontValidator];

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

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