<?php

class PipeworkController 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("Pipework/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);
    }
    
    $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 = [];
    $networks = [];
    foreach($my_networks as $network) {
      $my_network_ids[] = $network->id;
    }
      
    $building_search = [
        "network_id" => $my_network_ids,
        "workflow_finished" => 0
    ];

    if(is_array($filter) && count($filter)) {
      foreach($filter as $name => $value) {
        $building_search[$name] = $value;
      }
      //$building_search = array_merge($building_search, $filter);
    }


    if($this->me->is("pipeworker") && !$this->me->is(["Admin","pipeplanner","netowner"])) {
      $this->log->debug("is pipeworker");
      $building_search["pipeworker_id"] = ($this->me->address->parent_id) ? $this->me->address->parent_id : $this->me->address_id;
    }

    if(!array_key_exists("status_id", $filter)) {
      $building_search["status_id"] = 3;
    }

    $pagination['maxItems'] = BuildingModel::count($building_search);
    foreach(BuildingModel::search($building_search, $pagination) as $b) {
      if(!array_key_exists($b->network->name, $networks)) {
        $networks[$b->network->name] = [];
      }
      if(!array_key_exists($b->id, $networks[$b->network->name])) {
        $networks[$b->network->name][$b->id] = $b;
      }
    }
    
    $building = reset(reset($networks));
    $item_colspan = 0;
    $i = 0;
    
    // get fields between delimiters for colspan
    foreach($building->workflowitems as $wfitem) {
      if($i == 0 && $wfitem->type == "delimiter") continue;
      
      if($wfitem->type == "delimiter") {
        $item_colspan = $i;
        break;
      }
      
      $i++;
    }
    //var_dump($item_colspan);exit;
    $this->layout()->set("wfColspan", $item_colspan);
    $this->layout()->set("networks", $networks);
    $this->layout()->set("pagination", $pagination);
    //var_dump(reset(reset($networks))->workflowitems);exit;
    

  }
  
  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;
    $building_id = $r->id;
    if(!is_numeric($building_id) || $building_id < 1) {
      $this->layout()->setFlash("Objekt nicht gefunden", "error");
      $this->redirect("Pipework");
    }
    
    $building = new Building($building_id);
    if(!$building->id) {
      $this->layout()->setFlash("Objekt nicht gefunden", "error");
      $this->redirect("Pipework");
    }
    
    //var_dump($r->get());exit;
    
    if($this->me->is(["Admin", "netowner", "pipeplanner"])) {
      if($r->pipework_enabled == 1) {
        $building->pipework_enabled = 1;
        if($building->status_id < 3) {
          $building->status_id = 3;
        }
      } else {
        $building->pipework_enabled = 0;
      }
      $building->save();
    }
    
    if($building->workflow_comment != $r->workflow_comment) {
      $building->workflow_comment = $r->workflow_comment;
      $building->workflow_comment_changed = date('U');
      $building->workflow_comment_changed_by = $this->me->id;
      $building->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" => "building"]);
      if(!$item) {
        var_dump("no item: $name");exit;
      }
      $item->setObjectId($building_id);
      $item->value->setValue($value, $items);
      //var_dump($item);exit;
      $item->value->save();
      
      $building->resetProperties();
      
      // set pipework finished flag in building
      if($name == TT_WORKFLOW_ITEM_PIPEWORK_DONE) {
        if($value && $building->workflow_finished == 0) {
          $building->workflow_finished = 1;
          $building->save();
        } elseif(!$value && $building->workflow_finished == 1) {
          $building->workflow_finished = 0;
          $building->save();
        }
        
      }
    }
    
    /*
     * Custom checks
     */
    
    
    
    if($building->workflowitems['pipework_finished']->value->value_string) {
      // unset Tiefbau abgeschlossen if missing values
      if(  (!$building->workflowitems['anschlusspunkt_typ']->value->value_string && !$building->workflowitems['ist_anschlusspunkt_typ']->value->value_string)
        || (!$building->workflowitems['anschlusspunkt_name']->value->value_string && !$building->workflowitems['ist_anschlusspunkt_name']->value->value_string)
        || (!$building->workflowitems['rohrverband_name']->value->value_string && !$building->workflowitems['ist_rohrverband_name']->value->value_string)
        || (!$building->workflowitems['rohrtype']->value->value_string && !$building->workflowitems['ist_rohrtype']->value->value_string)
        || (!$building->workflowitems['rohrfarbe']->value->value_string && !$building->workflowitems['ist_rohrfarbe']->value->value_string)
      ) {
       $building->workflowitems['pipework_finished']->value->value_string = "";
       $building->workflowitems['pipework_finished']->value->save();
      }
    }
    
    // set building status if Status field was set
    if(defined("TT_WORKFLOW_ITEM_STATUS_FIELD") && defined("TT_WORKFLOW_ITEM_STATUS_VALUE_PASSED") && defined("TT_WORKFLOW_ITEM_STATUS_VALUE_CONNECTED")) {
      $status_value = $building->workflowitems[TT_WORKFLOW_ITEM_STATUS_FIELD]->value->value_string;
      if($status_value == TT_WORKFLOW_ITEM_STATUS_VALUE_PASSED && $building->status_id != 4) {
        $building->status_id = 4;
        $building->save();
      }
      if($status_value == TT_WORKFLOW_ITEM_STATUS_VALUE_CONNECTED && $building->status_id != 5) {
        $building->status_id = 5;
        $building->save();
      }
    }
    
    // file upload
    
    if(array_key_exists("PipeworkFileUpload", $_FILES) && !$_FILES['PipeworkFileUpload']['error']) {
      //var_dump($_FILES);exit;
      try {
        $upload = new mfUpload("PipeworkFileUpload");
        $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 {
          $bf = [];
          $bf['building_id'] = $building_id;
          $bf['file_id'] = $file_id;
          $bf['type'] = $r->file_type;
          $bf['name'] = $file->name;

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

    }
    
    $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("Pipework","Index", $qs, "object=".$building_id);
    
    
      
    
  }
  
}
