<?php

class OrderJournalController extends mfBaseController {
  
  protected function init() {
    $this->needlogin=true;
    $me = new User();
    $me->loadMe();
    $this->me = $me;
    $this->layout()->set("me",$me);
    
    if(!$me->is(["Admin", "salespartner"])) {
      $this->redirect("Dashboard");
    }
  }
  
  protected function saveAction() {
    if(!$this->me->is(["Admin", "salespartner"])) {
      $this->layout()->setFlash("Keine Berechtigung", "error");
      $this->redirect("Dashboard");
    }
    
    $r = $this->request;
    $order_id = $r->order_id;
    $s = $r->s;
    
    if(!is_numeric($order_id) || $order_id < 1) {
      $this->layout()->setFlash("Bestellung nicht gefunden!", "error");
      $this->redirect("Order");
    }
    
    $order = new Order($order_id);
    if(!$order->id) {
      $this->layout()->setFlash("Bestellung nicht gefunden!", "error");
      $this->redirect("Order");
    }
    
    $text = trim(htmlentities($r->text));
    if(!$text) {
      $this->layout()->setFlash("Bitte Text eingeben", "error");
      $this->redirect("Order", "Index", ['s' => $s], "order=".$order_id);
    }
    
    
    $query = [];
    if(is_numeric($this->request->s) && $this->request->s > 0) {
      $query["s"] = $this->request->s;
    }
    if (is_array($this->request->filter)) {
      $query["filter"] = $this->request->filter;
    }
    $qs = http_build_query($query);
    
    
    $journal = new OrderJournal();
    $journal->order_id = $order_id;
    $journal->text = $text;
    $journal->create_by = $this->me->id;
    $journal->edit_by = $this->me->id;
    
    if(!$journal->save()) {
      $this->layout()->setFlash("Fehler beim speichern!", "error");
      $this->redirect("Order", "Index", $qs, "order=".$order_id);
    }
            
    $this->layout()->setFlash("Journaleintrag gespeichert", "success");
    $this->redirect("Order", "Index", $qs, "order=".$order_id);
    
    
  }
  
  
  
}