<?php

namespace App\Http\Controllers;

use App\OrderAppointmentOperator;
use App\Textblock;
use App\User;
use App\Client;
use App\Customer;
use App\Orders;
use App\OrderInvoice;
use App\OrderInvoicePosition;
use App\OrderDocuments;
use App\Product;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use JsValidator;

use App\Mail\OrderMail;
use App\OrderMailLog;
use Illuminate\Http\Request;

use App\Jobs\SendOrderMailJob;
use Illuminate\Support\Facades\Storage;

use PDF;

class OrderInvoiceController extends Controller {
    private $validationRules = [
        'project_name' => 'required|max:190',
        'date_of_issue' => 'required',
        'service_provision_date' => 'required',
    ];

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

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

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

        # Auftragsdaten holen
        $order = Orders::find($orderId);
        if ($order == null)
            return response()->json(['response' => 'error']);

        # Mögliche Artikel holen
        $products = Product::where("client_id", $loggedUser->client_id)->get();

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

        $arguments = array_merge($arguments, ["order" => $order,
            "operatorID" => $operatorId,
            "products" => $products,
            "validator" => $frontValidator]);

        # View rendern
        $editorHTML = View::make('order_invoices.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->validationRules);

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

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

        $orderId = request()->get('id');
        $order = Orders::find($orderId);
        $orderInvoice = new OrderInvoice();
        $orderInvoiceNumber = $loggedUser->client->numberRangeOrderInvoices->getNextNumber();
        $orderInvoice->invoice_number = $orderInvoiceNumber;

        $orderInvoice->order_id = $orderId;

        // Auftraggeberdaten
        $customer = Customer::find($order->customer->id);
        $orderInvoice->customer_id = $customer->id;
        $orderInvoice->date_of_issue = request()->get('date_of_issue');
        $orderInvoice->project_name = request()->get('project_name');
        $orderInvoice->service_provision_date = request()->get('service_provision_date');
        $orderInvoice->company = $customer->company;
        $orderInvoice->street = $customer->street;
        $orderInvoice->house_number = $customer->house_number;
        $orderInvoice->zipcode = $customer->zipcode;
        $orderInvoice->place = $customer->place;
        $orderInvoice->country = $customer->country;

        try {
            $orderInvoice->save();
        } catch (\Exception $e) {
            Log::error($e->getMessage());
            return response()->json(['response' => 'error', 'message' => 'Speichern der Rechnung fehlgeschlagen']);
        }

        // Positionen anlegen
        $positions = request()->get('products');
        for($i=0; $i<count($positions);$i++)
        {
          $orderInvoicePosition = new OrderInvoicePosition();
          $product = Product::find($positions[$i][0]["productId"]);
          $orderInvoicePosition->order_invoice_id = $orderInvoice->id;
          $orderInvoicePosition->products_id = $product->id;
          $orderInvoicePosition->product_number = $product->product_number;
          $orderInvoicePosition->name = $product->name;
          $orderInvoicePosition->quantity = $positions[$i][0]["quantity"];
          $orderInvoicePosition->price = $positions[$i][0]["price"];
          $orderInvoicePosition->save();
        }

        try
        {
          // Rechnungsdokumente anlegen und zum Auftrag speichern
          $docPath = "/files/order_files/order_".$orderId."/Rechnung_".$orderInvoiceNumber.".pdf";

          $this->createPdf($orderInvoice->id, 0, $docPath);

          $doc = new OrderDocuments();
          $doc->order_id = $orderId;
          $doc->prettyName = "Rechnung_".$orderInvoiceNumber.".pdf";
          $doc->path = $docPath;
          $doc->save();
        }
        catch (\Exception $e)
        {
            Log::error($e->getMessage());
            return response()->json(['response' => 'error', 'message' => 'Das Rechnungsdokument konnte nicht erstellt werden.']);
        }

        # Log schreiben
        // 'Bearbeiter {OPERATORNAME} hat zum Auftrag {ORDERNUMBER} die Rechnung {ORDERINVOICENUMBER} erstellt.',
        OrderLogsController::writeLog(23, $orderId, $loggedUser->operator->id,
            ["{ORDERNUMBER}" => $order->order_number, "{ORDERINVOICENUMBER}" => $orderInvoiceNumber]);

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

    public function createPdfPrint($orderInvoiceId)
    {
      return $this->createPdf($orderInvoiceId, 1, null);
    }

    public function createPdf($orderInvoiceId, $print = 0, $path = null)
    {
      $orderInvoice = OrderInvoice::find($orderInvoiceId);
      $order = $orderInvoice->order;
      $customer = $order->customer;

      $parameters = [
          "customer" => $customer,
          "order" => $order,
          "orderInvoice" => $orderInvoice,
          "withoutBackground" => $print
        ];

      # https://github.com/barryvdh/laravel-dompdf
      PDF::setOptions(['dpi' => 300, 'defaultFont' => 'sans-serif', 'defaultPaperSize' => 'A4']);

      $pdfName = "Rechnung_".$orderInvoice->invoice_number;
      if($print == 1)
        $pdfName.="_druck";

      $pdfName.=".pdf";

      // PDF generieren
      $pdf = PDF::loadView('order_invoices.generatePdf', $parameters);

      if($path==null)
      {
        // Rechnung soll generiert und im Browser ausgegeben werden
        return $pdf->download($pdfName);
      }
      else{
        // Rechnung soll generiert und im System abgelegt werden
        Storage::disk("uploads")->put($path, $pdf->download());
      }

    }
}
