<?php

class ProductController 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","netowner","pipeplanner"])) {
      $this->redirect("Dashboard");
    }
  }
  
  protected function indexAction() {
    if(!$this->me->is(["Admin"])) {
      $this->redirect("Dashboard");
    }
    $this->layout()->set("products", ProductModel::getAll());
  }
  
  protected function addAction() {
    if(!$this->me->is(["Admin"])) {
      $this->redirect("Dashboard");
    }
    $this->layout()->setTemplate("Product/Form");
    $this->layout()->set("productgroups", ProductgroupModel::getAll());
    $this->layout()->set("producttechs", ProducttechModel::getAll());
    $this->layout()->set("slas", SlaModel::getAll());
    $this->layout()->set("networks", NetworkModel::getAll());
    
  }
  
  protected function editAction() {
    if(!$this->me->is(["Admin"])) {
      $this->redirect("Dashboard");
    }
    $product_id = $this->request->id;
    $product = new Product($product_id);
    if(!$product->id) {
      $this->layout()->setFlash("Produkt nicht gefunden.", "error");
      $this->redirect("Product");
    }
    
    //var_dump($product->attributes);exit;
    
    $this->layout()->set("product", $product);
    
    return $this->addAction();
  }
  
  protected function saveAction() {
    if(!$this->me->is(["Admin"])) {
      $this->redirect("Dashboard");
    }
    
    $r = $this->request;
    //var_dump($r);exit;
    $id = $r->id;
    if(is_numeric($id) && $id > 0) {
      $mode = "edit";
      $product = new Product($id);
      if(!$product->id) {
        $this->layout()->setFlash("Produkt nicht gefunden", "error");
        $this->redirect("Product");
      }
    } else {
      $id = false;
      $mode = "add";
    }
    
    $data = [];
    $data['name'] = $r->name;
    $data['description'] = $r->description;
    if($r->sla_id) {
      $data['sla_id'] = $r->sla_id;
    }
    $data['external'] = ($r->external == 1) ? "1" : "0";
    $data['price_nne'] = ($r->price_nne) ? Layout::commaToDot($r->price_nne) : 0;
    $data['price_nbe'] = ($r->price_nbe) ? Layout::commaToDot($r->price_nbe) : 0;
    $data['price'] = ($r->price) ? Layout::commaToDot($r->price) : 0;
    $data['price_setup'] = ($r->price_setup) ? Layout::commaToDot($r->price_setup) : 0;
    $data['billing_period'] = $r->billing_period;
    $data['billing_delay'] = ($r->billing_delay) ? $r->billing_delay : 0;
    $data['ivt_id'] = ($r->ivt_id) ? $r->ivt_id : null;
    $data['note'] = $r->note;
    
    if(is_numeric($r->producttech_id)) {
      $data['producttech_id'] = $r->producttech_id;
    } else {
      $data['producttech_id'] = null;
    }
    if(is_numeric($r->productgroup_id)) {
      $data['productgroup_id'] = $r->productgroup_id;
    } else {
      $data['productgroup_id'] = null;
    }
    
    $data['edit_by'] = $this->me->id;
    
    if($mode == "add") {
      $data['create_by'] = $this->me->id;
      $product = ProductModel::create($data);
    } else {
      $product->update($data);
    }
    
    //var_dump($address);exit;
    
    $new_id = $product->save();
    if(!$new_id) {
      $this->layout()->setFlash("Fehler beim Speichern", "error");
      $this->layout()->set("product", $product);
      return $this->add();
    }
    
    // delete all networks to save networks
    $pnets = ProductNetworkModel::search(['product_id' => $new_id]);
    foreach($pnets as $pnet) {
      $pnet->delete();
    }
    
    if(is_array($r->networks) && count($r->networks)) {
      foreach($r->networks as $network_id) {
        $network = new Network($network_id);
        if(!$network->id) {
          // ignore non-existing networks
          continue;
        }
        $pnet = ProductNetworkModel::create(['product_id' => $new_id, 'network_id' => $network_id]);
        $pnet->save();
      }
    }
    
    // create new product group and tech
    
    if($r->productgroup_id == "new") {
      $ng = [];
      $ng['name'] = $r->productgroup_new_name;
      $ng['description'] = $r->productgroup_new_description;
      $ng['note'] = $r->productgroup_new_note;
      $group = ProductgroupModel::create($ng);
      $group_id = $group->save();
      $product->productgroup_id = $group_id;
      $product->save();
    }
    
    if($r->producttech_id == "new") {
      $nt = [];
      $nt['name'] = $r->producttech_new_name;
      $nt['rtrcode'] = $r->producttech_new_rtrcode;
      $nt['customer_type'] = ($r->producttech_new_customer_type == "business") ? "business" : "residential";
      $nt['description'] = $r->producttech_new_description;
      $nt['note'] = $r->producttech_new_note;
      $tech = ProducttechModel::create($nt);
      $tech_id = $tech->save();
      $product->producttech_id = $tech_id;
      $product->save();
    }
    
    if(is_array($r->attributes) && count($r->attributes)) {
      foreach($r->attributes as $pta_id => $attribute_value) {
        $attrib = ProductAttributeModel::getFirst(['product_id' => $new_id, 'producttechattribute_id' => $pta_id]);
        if(!$attrib) {
          $attrib = ProductAttributeModel::create([
            'product_id' => $new_id,
            'producttechattribute_id' => $pta_id,
          ]);
          //var_dump($attrib);exit;
        }
        $attrib->value = $attribute_value;
        $attrib->edit_by = $this->me->id;
        $attrib->save();
      }
    }
    
    $this->layout()->setFlash("Produkt erfolgreich gespeichert.", "success");
    $this->redirect("Product", "Edit", ['id' => $new_id]);
  }
  
  protected function deleteAction() {
    if(!$this->me->is(["Admin"])) {
      $this->redirect("Dashboard");
    }
    
    $id = $this->request->id;
    
    $product = new Product($id);
    if(!$product->id || $product->id != $id) {
      $this->layout()->setFlash("Produkt nicht gefunden.", "error");
      $this->redirect("Product");
    }
    
    // check if Product is unused
    $product->delete();
    $this->redirect("Product");
  }
  
  protected function apiAction() {
    if(!$this->me->is(["Admin","netowner","pipeplanner"])) {
      $this->redirect("Dashboard");
    }
    $do = $this->request->do;
    $data = [];
    
    switch($do) {
      case "getProduct":
        $return = $this->getProductApi();
        break;
      default:
        $return = false;
    }
    
    if(!is_array($return) || !count($return)) {
      $data = ["status" => "error"];
      $this->returnJson($data);
    }
    $data['status'] = "OK";
    $data['result'] = $return;
    $this->returnJson($data);
  }
  
  private function getProductApi() {
    $product_id = $this->request->product_id;
    if(!is_numeric($product_id) || $product_id < 1) {
      return false;
    }
    
    $form_id = false;
    if($this->request->form_id) {
      $form_id = $this->request->form_id;
    }
    
    $product = new Product($product_id);
    if(!$product->id) {
      return false;
    }

    if(is_array($product->attributes) && count($product->attributes)) {
      $attributes = $product->attributes;
      $product->data->attributes = [];
      foreach($attributes as $attrib) {
        $product->data->attributes[$attrib->name] = $attrib->value;
      }
    }
    
    return ["product" => $product->data, "form_id" => $form_id];
  }
}