<?php

class LineworkController 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","pipeworker", "lineplanner", "lineworker"])) {
      $this->redirect("Dashboard");
    }
  }
  
  protected function indexAction() {
    $this->layout()->setTemplate("Linework/Index");
    $filter = [];
    $this->layout->set("filter", $this->request->filter);
    if($this->request->filter) {
      $filter = $this->getPreparedFilter($this->request->filter);
    }
    
    // pagination defaults
    $pagination = [];
    $pagination['start'] = 0;
    $pagination['count'] = 5;
    $pagination['maxItems'] = 0;
    
    if(is_numeric($this->request->s)) {
      $pagination['start'] = intval($this->request->s);
    }
    //var_dump($pagination);exit;
    $my_networks = [];
    
    // get allowed networks
    if($this->me->is("Admin")) {
      if($filter['network_id']) {
        $my_networks[] = new Network($filter['network_id']);
      } else {
        $my_networks = NetworkModel::getAll();
      }
      $this->layout()->set("mynetworks", NetworkModel::getAll());
    } else {
      $use_filter_network = false;
      $my_networks = $this->me->my_networks;
      
      foreach($my_networks as $mn) {
        if($mn->id == $filter['network_id']) {
          $use_filter_network = true;
          continue;
        }
      }
      
      if($use_filter_network) {
        $my_networks = [];
        $my_networks[] = new Network($filter['network_id']);
      }
      
      $this->layout()->set("mynetworks", $this->me->my_networks);
      
    }
    unset($filter['network_id']);
    
    // get Buildings in networks
    $my_network_ids = [];
    $terminations = [];
    foreach($my_networks as $network) {
      $my_network_ids[] = $network->id;
    }
    
    
    $termination_search = [
        "network_id" => $my_network_ids,
        "workflow_finished" => 0
    ];

    if(is_array($filter) && count($filter)) {
      foreach($filter as $name => $value) {
        $termination_search[$name] = $value;
      }
    }
    
    
    
    if($this->me->is("lineworker") && !$this->me->is(["Admin","pipeplanner", "lineplanner","netowner"])) {
      $this->log->debug("is lineworker");
      $termination_search["lineworker_id"] = ($this->me->address->parent_id) ? $this->me->address->parent_id : $this->me->address_id;
      //var_dump($filter);exit;
    }
    
    if(!array_key_exists("status_id", $filter)) {
      $termination_search["status_id"] = 3;
    }
    
    $networks = [];

    $pagination['maxItems'] = TerminationModel::count($termination_search);
    foreach(TerminationModel::search($termination_search, $pagination) as $term) {
      if(!array_key_exists($term->network->name, $networks)) {
        $networks[$term->network->name] = [];
      }
      if(!array_key_exists($term->id, $networks[$term->network->name])) {
        $networks[$term->network->name][$term->id] = $term;
      }
    }
    
    $term = reset(reset($networks));
    $item_colspan = 0;
    $i = 0;
    
    //var_dump($term);exit;
    
    // get fields between delimiters for colspan
    if(is_array($term->workflowitems) && count($term->workflowitems)) {
      foreach($term->workflowitems as $wfitem) {
        if($i == 0 && $wfitem->type == "delimiter") continue;

        if($wfitem->type == "delimiter") {
          $item_colspan = $i;
          break;
        }

        $i += ($wfitem->width) ? $wfitem->width : 1;
      }
    }
    
    $this->layout()->set("wfColspan", $item_colspan);
    $this->layout()->set("networks", $networks);
    $this->layout()->set("pagination", $pagination);
    
  }
  
  private function getPreparedFilter($filter) {
    $new_filter = [];

    if(is_numeric($filter['networksection_id']) && $filter['networksection_id']) {
      $section = new Networksection($filter['networksection_id']);
      if($section->id) {
        $filter['network_id'] = $section->network_id;
      }
    }
    
    foreach($filter as $name => $value) {
      /*if($name == 'network_id') {
        $new_filter['id'] = $value;
        continue;
      }*/
      
      $new_filter[$name] = $value;
    }
    
    return $new_filter;
  }
  
  protected function saveAction() {
    $r = $this->request;
    //var_dump($r->get());exit;
    $termination_id = $r->id;
    if(!is_numeric($termination_id) || $termination_id < 1) {
      $this->layout()->setFlash("Objekt nicht gefunden", "error");
      $this->redirect("Linework");
    }
    
    $termination = new Termination($termination_id);
    if(!$termination->id) {
      $this->layout()->setFlash("Objekt nicht gefunden", "error");
      $this->redirect("Linework");
    }
    
    //var_dump($r->get());exit;
    
    if($this->me->is(["Admin", "netowner","pipeplanner", "lineplanner"])) {
      if($r->linework_enabled == 1) {
        $termination->linework_enabled = 1;
        if($termination->status_id < 3) {
          $termination->status_id = 3;
        }
      } else {
        $termination->linework_enabled = 0;
        if($termination->status_id == 3) {
          $termination->status_id = 1;
        }
      }
      $termination->save();
    }
    
    if($termination->workflow_comment != $r->workflow_comment) {
      $termination->workflow_comment = $r->workflow_comment;
      $termination->workflow_comment_changed = date('U');
      $termination->workflow_comment_changed_by = $this->me->id;
      $termination->save();
    }
    
    $items = [];
    
    // get workflow values from request
    foreach($r->get() as $field_name => $value) {
      $m = [];
      if(preg_match('/^wfitem_(.+)$/', $field_name, $m)) {
        if(!$m[1]) {
          continue;
        }
        $items[$m[1]] = $value;
      }
    }
    
    
    
    //var_dump($items);exit;
    foreach($items as $name => $value) {
      $item = WorkflowitemModel::getFirst(["name" => $name, "object_type" => "termination"]);
      if(!$item) {
        var_dump("no item: $name");exit;
      }
      $item->setObjectId($termination_id);
      $item->value->setValue($value);
      if($item->value->is_changed) {
        $item->value->save();
      }
      
      $termination->resetProperties();
      
      // set linework finished flag in termination
      
      if($name == TT_WORKFLOW_ITEM_LINEWORK_DONE) {
        if($value && $termination->workflow_finished == 0) {
          $termination->workflow_finished = 1;
          $termination->save();
        } elseif(!$value && $termination->workflow_finished == 1) {
          $termination->workflow_finished = 0;
          $termination->save();
        }
        
        // set status to connected
        if($value && $termination->status_id < 5) {
          $termination->status_id = 5;
          $termination->save();
        }
        
        if(!$value && $termination->status_id == 5) {
          $termination->status_id = 3;
          $termination->save();
        }
        
      }
    }
    
    $item = WorkflowitemModel::getFirst(["name" => "customer_passive_finished", "object_type" => "termination"]);
    $item->setObjectId($termination_id);
    
    if(!$item->value->id) {
      $this->log->debug(__CLASS__."::save(): creating new value 0 for workflowitem because value of customer_passive_finished does not exist yet");
      $item->value->value_int = 0;
      $item->value->save();
    }
    
    /*
     * Custom checks
     */
    
    if($termination->workflowitems[TT_WORKFLOW_ITEM_LINEWORK_DONE]->value_int) {
      $required_fields = ["baugruppe","modul","ports","abschlusstyp","bb_kabel","bb_fasern","kundenkabel_typ","kundenkabel_fasern","backbone_finished","bep_deployed","customer_cable_injected","spliced_network","spliced_customer"];
      //,"inhouse_cabling_supplied","inhouse_cabling_deployed"
      
      if($termination->workflowitems['abschlusstyp']->value->value_string != "SC/APC in FTU" && $termination->workflowitems['ist_abschlusstyp']->value->value_string != "SC/APC in FTU") {
        $required_fields[] = "inhouse_cabling_supplied";
        $required_fields[] = "inhouse_cabling_deployed";
      }
      
      $can_finish = true;
      foreach($required_fields as $f) {
        $type = $termination->workflowitems[$f]->type;
        if(!$termination->workflowitems[$f]->value->{"value_$type"} && !$termination->workflowitems["ist_$f"]->value->{"value_$type"}) {
          $can_finish = false;
        }
      }
      
      if(!$can_finish) {
       $this->log->info("Resetting customer_passive_finished because of missing values");
       $termination->workflowitems[TT_WORKFLOW_ITEM_LINEWORK_DONE]->value->value_int = 0;
       $termination->workflowitems[TT_WORKFLOW_ITEM_LINEWORK_DONE]->value->save();
      }
    }
    
    // set values for all terminations in this building
    if($termination->workflowitems['bb_kabel']->value->value_string) {
      $value = $termination->workflowitems['bb_kabel']->value->value_string;
      foreach($termination->building->terminations as $t) {
        $t->workflowitems['bb_kabel']->value->value_string = $value;
        $t->workflowitems['bb_kabel']->value->save();
      }
    }
    if($termination->workflowitems['bb_kabel_steps']->value->value_string) {
      $value = $termination->workflowitems['bb_kabel_steps']->value->value_string;
      foreach($termination->building->terminations as $t) {
        $t->workflowitems['bb_kabel_steps']->value->value_string = $value;
        $t->workflowitems['bb_kabel_steps']->value->save();
      }
    }
    if($termination->workflowitems['kundenkabel_typ']->value->value_string) {
      $value = $termination->workflowitems['kundenkabel_typ']->value->value_string;
      foreach($termination->building->terminations as $t) {
        $t->workflowitems['kundenkabel_typ']->value->value_string = $value;
        $t->workflowitems['kundenkabel_typ']->value->save();
      }
    }
    $value = $termination->workflowitems['customer_cable_injected']->value->value_int;
    foreach($termination->building->terminations as $t) {
      $t->workflowitems['customer_cable_injected']->value->value_int = $value;
      $t->workflowitems['customer_cable_injected']->value->save();
    }
    
    if($termination->workflowitems['ist_bb_kabel']->value->value_string) {
      $value = $termination->workflowitems['ist_bb_kabel']->value->value_string;
      foreach($termination->building->terminations as $t) {
        $t->workflowitems['ist_bb_kabel']->value->value_string = $value;
        $t->workflowitems['ist_bb_kabel']->value->save();
      }
    }
    if($termination->workflowitems['ist_bb_kabel_steps']->value->value_string) {
      $value = $termination->workflowitems['ist_bb_kabel_steps']->value->value_string;
      foreach($termination->building->terminations as $t) {
        $t->workflowitems['ist_bb_kabel_steps']->value->value_string = $value;
        $t->workflowitems['ist_bb_kabel_steps']->value->save();
      }
    }
    if($termination->workflowitems['ist_kundenkabel_typ']->value->value_string) {
      $value = $termination->workflowitems['ist_kundenkabel_typ']->value->value_string;
      foreach($termination->building->terminations as $t) {
        $t->workflowitems['ist_kundenkabel_typ']->value->value_string = $value;
        $t->workflowitems['ist_kundenkabel_typ']->value->save();
      }
    }
    
    //var_dump(strlen($termination->workflowitems['pop_id']->value->value_string));exit;
    
    // set patching enabled for termination
    if(
      (strlen($termination->workflowitems['pop_id']->value->value_string) || strlen($termination->workflowitems['ist_pop_id']->value->value_string)) &&
      (strlen($termination->workflowitems['schrank']->value->value_string) || strlen($termination->workflowitems['ist_schrank']->value->value_string)) &&
      (strlen($termination->workflowitems['baugruppe']->value->value_string) || strlen($termination->workflowitems['ist_baugruppe']->value->value_string)) &&
      (strlen($termination->workflowitems['modul']->value->value_string) || strlen($termination->workflowitems['ist_modul']->value->value_string)) &&
      (strlen($termination->workflowitems['ports']->value->value_string) || strlen($termination->workflowitems['ist_ports']->value->value_string))
    ) {
      $this->log->debug("Linework::save: All items needed for patching set");
      if($termination->patching_enabled != 1) {
        $termination->patching_enabled = 1;
        $termination->save();
      }
    } else {
      $this->log->debug("Linework::save: Not all items needed for patching set");
      if($termination->patching_enabled == 1) {
        $termination->patching_enabled = 0;
        $termination->save();
      }
    }
    
    // file upload
    //var_dump($_FILES);exit;
    if(array_key_exists("LineworkFileUpload", $_FILES) && !$_FILES['LineworkFileUpload']['error']) {
      
      try {
        $upload = new mfUpload("LineworkFileUpload");
        $upload->setSavepath(MFUPLOAD_FILE_SAVE_PATH."/documents");
        $upload->save();

        $file_data = [];
        $file_data['name'] = ($r->file_name) ? $r->file_name : $upload->getOriginalFilename();
        $file_data['filename'] = ($r->file_filename) ? $r->file_filename : $upload->getOriginalFilename();
        $file_data['subfolder'] = "documents";
        $file_data['store_filename'] = $upload->getFilename();
        $file_data['orig_filename'] = $upload->getOriginalFilename();

        $file = FileModel::create($file_data);
        $file_id = $file->save();
        if(!$file_id) {
          $this->layout()->setFlash("Dateiupload fehlgeschlagen", "warn");
          unlink($upload->getSavepath()."/".$upload->getFilename());
        } else {
          $tf = [];
          $tf['termination_id'] = $termination_id;
          $tf['file_id'] = $file_id;
          $tf['type'] = $r->file_type;
          $tf['name'] = $file->name;

          $termfile = TerminationFileModel::create($tf);
          if(!$termfile->save()) {
            $file->delete();
            unlink($upload->getSavepath()."/".$upload->getFilename());
            $this->layout()->setFlash("Dateiupload fehlgeschlagen", "warn");
            $this->redirect("Linework");
          }
        }
      } catch(Exception $ex) {
        $this->layout->setFlash("Fehler beim Dateiupload: ".$ex->getMessage(), "warn");
        $this->redirect("Linework");
      }
      

    }
    
    $sq = "";
    $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("Workflow Eintrag erfolgreich gespeichert.", "success");
    $this->redirect("Linework","Index", $qs, "object=".$termination_id);
    
    
      
    
  }
  
}
