<?php

class CpeprovisioningController 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"])) {
      $this->redirect("Dashboard");
    }
  }
  
  protected function indexAction() {
    $this->layout()->setTemplate("Cpeprovisioning/Index");
    $cpeproducts = [];
    
    $this->layout->set("filter", $this->request->filter);
    $filter = $this->getPreparedFilter($this->request->filter);
    // pagination defaults
    $pagination = [];
    $pagination['start'] = 0;
    $pagination['count'] = 20;
    $pagination['maxItems'] = 0;
    
    $order_filter = $filter;
    $order_filter["finish_date"] = null;
    //var_dump($filter);exit;
    /*
     * Get orderproducts in need of sending a CPE
     */
    //var_dump($order_filter);exit;
    $orders = OrderModel::search($order_filter);
    
    foreach($orders as $order) {
      if($order->finish_after) {
        // show at most 4 weeks before finish_after date
        $after_ts = Layout::dateToInt($order->finish_after);
        if($after_ts > date("U") + (31 * 86400)) {
          $this->log->debug("Before 4 weeks before finish_after oid ".$order->id);
          continue;
        }
      }
      
      if(is_array($order->terminations) && count($order->terminations)) {
        if(!$order->cpeprovisioning_enabled && $order->terminations[0]->status->code < TT_TERMSTATUS_CONNECTED) {
          continue;
        }
      }
      
      foreach($order->products as $orderproduct) {
        if($orderproduct->cpeprovisioning->routerconfig_finished == 1) {
          if(!$filter['routerconfig_finished']) continue;
        } else {
          if($filter['routerconfig_finished']) continue;
        }
        $product = $orderproduct->product;
        
        if(is_array($product->attributes) && count($product->attributes)) {
          // filter out products without bras_type
          if(array_key_exists("bras_type", $product->attributes) && $product->attributes['bras_type']->value) {
            $cpeproducts[] = $orderproduct;
          } else {
            $this->log->debug("no bras_type oid ".$order->id);
            continue;
          }
        } else {
          // ignore products without attributes
          $this->log->debug("no attributes oid ".$order->id);
          continue;
        }
        
      }
    }
    
    $this->layout()->set("products", $cpeproducts);
  }
  
  private function getPreparedFilter($filter) {
    $new_filter = [];
    
    if(array_key_exists("hide_delayed_finish", $filter)) {
      if($filter["hide_delayed_finish"] == "1") {
        $new_filter["hide_delayed_finish"] = true;
      } else {
        $new_filter["hide_delayed_finish"] = false;
      }
      unset($filter["hide_delayed_finish"]);
    } else {
      $new_filter["hide_delayed_finish"] = true;
    }
    
    if(array_key_exists("routerconfig_finished", $filter)) {
      if($filter["routerconfig_finished"] == "1") {
        $new_filter["routerconfig_finished"] = true;
        $new_filter["hide_delayed_finish"] = false;
      } else {
        $new_filter["routerconfig_finished"] = false;
      }
      unset($filter["routerconfig_finished"]);
    } else {
      $new_filter["routerconfig_finished"] = false;
    }
    
    
    
    foreach($filter as $name => $value) {
      $new_filter[$name] = $value;
    }
    //var_dump($new_filter);exit;
    return $new_filter;
  }
  
  protected function saveAction() {
    $r = $this->request;
    $id = $r->id;
    //var_dump($r);exit;
    if(is_numeric($id) && $id > 0) {
      $mode = "edit";
      $cpeprovisioning = new Cpeprovisioning($id);
      if(!$cpeprovisioning->id) {
        $this->layout()->setFlash("Eintrag nicht gefunden", "error");
        $this->redirect("Cpeprovisioning");
      }
    } else {
      $mode = "add";
    }
    
    $order_id = $r->order_id;
    $termination_id = $r->termination_id;
    if(!(is_numeric($termination_id) && $termination_id > 0) && !(is_numeric($order_id) && $order_id > 0)) {
      $this->layout()->setFlash("Anschluss oder Bestellung nicht gefunden", "error");
      $this->redirect("Cpeprovisioning");
    }
    
    $orderproduct = OrderProductModel::getFirst(["order_id" => $order_id, "termination_id" => $termination_id]);
    if(!$orderproduct) {
      $this->layout()->setFlash("Anschluss gehört nicht zur Bestellung", "error");
      $this->redirect("Cpeprovisioning");
    }
    
    $prov_data = [];
    $prov_data["termination_id"] = ($r->termination_id) ? $r->termination_id : null;
    $prov_data["order_id"] = $r->order_id;
    $prov_data["orderproduct_id"] = $r->orderproduct_id;
    $prov_data["routerconfig_finished"] = ($r->routerconfig_finished) ? 1 : 0;
    $prov_data["routertype"] = $r->routertype;
    $prov_data["shipping"] = ($r->shipping) ? 1 : 0;
    $prov_data["wifi_ssid"] = $r->wifi_ssid;
    $prov_data["wifi_pass"] = $r->wifi_pass;
    $prov_data["mac"] = $r->mac;
    $prov_data["vlan_public"] = (strlen($r->vlan_public)) ? $r->vlan_public : null;
    $prov_data["vlan_nat"] = (strlen($r->vlan_nat)) ? $r->vlan_nat : null;
    $prov_data["vlan_ipv6"] = (strlen($r->vlan_ipv6)) ? $r->vlan_ipv6 : null;
    $prov_data["ship_weight"] = (strlen($r->ship_weight)) ? $r->ship_weight : null;
    $prov_data["ship_length"] = (strlen($r->ship_length)) ? $r->ship_length : null;
    $prov_data["ship_width"] = (strlen($r->ship_width)) ? $r->ship_width : null;
    $prov_data["ship_height"] = (strlen($r->ship_height)) ? $r->ship_height : null;
    $prov_data["note"] = $r->note;
    
    $prov_data["edit_by"] = $this->me->id;
    
    if($mode == "add") {
      $prov_data["create_by"] = $this->me->id;
      $cpeprovisioning = CpeprovisioningModel::create($prov_data);
    } else {
      $cpeprovisioning->update($prov_data);
    }
    
    //var_dump($prov_data);exit;
    $new_id = $cpeprovisioning->save();
    if(!$new_id) {
      $this->layout()->setFlash("Fehler beim Speichern", "error");
      $this->redirect("Cpeprovisioning");
    }
    
    // saved successfully, if routerconfig_finished make Journal entry in Order
    
    if($cpeprovisioning->routerconfig_finished) {
      $order_product = new OrderProduct($r->orderproduct_id);
    
      if($cpeprovisioning->shipping) {
        $text = "CPE zu Produkt \"".$order_product->product->name."\" zum Versand vorbereitet.\n\n";
      } else {
        $text = "CPE zu Produkt \"".$order_product->product->name."\" vorbereitet für Techniker zur Vorortinstallation.\n\n";
      }
      $text .= "Router: ".$cpeprovisioning->routertype."\n";
      $text .= "Zugangstyp: ".$order_product->product->attributes['bras_type']->value."\n";
      if($cpeprovisioning->vlan_public) {
        $text .= "Vlan Public: ".$cpeprovisioning->vlan_public."\n";
      }
      if($cpeprovisioning->vlan_nat) {
        $text .= "Vlan NAT: ".$cpeprovisioning->vlan_nat."\n";
      }
      if($cpeprovisioning->vlan_ipv6) {
        $text .= "Vlan IPv6: ".$cpeprovisioning->vlan_ipv6."\n";
      }

      $journal = new OrderJournal();
      $journal->order_id = $order_id;
      $journal->text = $text;
      $journal->create_by = $this->me->id;
      $journal->edit_by = $this->me->id;
      
      $journal_id = $journal->save();
      if(!$journal_id) {
        $this->layout()->setFlash("Konnte nicht ins Bestelljournal schreiben!", "warning");
      } else {
        $cpeprovisioning->order_journal_id = $journal_id;
        $cpeprovisioning->save();
      }
    }
    
    // save ONT sn
    if($r->ont_sn) {
      $termination = new Termination($termination_id);
      $orig_sn = $termination->getWorkflowvalue("ont_sn", "string");
      if($r->ont_sn != $orig_sn) {
        $termination->workflowitems["ont_sn"]->value->setValue($r->ont_sn);
        $termination->workflowitems["ont_sn"]->value->save();
      }
    }
    
    
    
    $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);
    
    $this->layout()->setFlash("Eintrag erfolgreich gespeichert.", "success");
    $this->redirect("Cpeprovisioning","Index", $qs);
    
  }
  
}
