<?php

class PatchingModel {
  public $termination_id = null;
  public $linework_port = null;
  public $device_type = null;
  public $device_name = null;
  public $device_port = null;
  public $patched = null;
  public $patched_by = null;
  public $patched_date = null;
  
  public $create_by = null;
  public $edit_by = null;
  public $create = null;
  public $edit = null;
  

  public static function create(Array $data) {
    $model = new Patching();
    
    foreach($data as $field => $value) {
      if(property_exists(get_called_class(), $field)) {
        $model ->$field = $value;
      }
    }
    
    $me = new User();
    $me->loadMe();

    if($model->create_by === null) {
      $model->create_by = $me->id;
    }
    if($model->edit_by === null) {
      $model->edit_by = $me->id;
    }
    
    return $model;
  }
  
  public static function getOne($id) {
    if(!is_numeric($id) || !$id) {
      throw new Exception("Invalid number", 400);
    }
    $item = [];
    $db = FronkDB::singleton();
    
    $res = $db->select("Patching", "*", "id=$id LIMIT 1");
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      $item = new Patching($data);
    }
    return $item;
  }
  
  public static function getAll() {
    $items = [];
    
    $db = FronkDB::singleton();
    
    $res = $db->select("Patching", "*");
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $items[] = new Patching($data);
      }
    }
    return $items;
    
  }
  
  public static function getFirst($filter = false) {
    $db = FronkDB::singleton();
    
    $where = self::getPatchingSqlFilter($filter);
    //var_dump($where);exit;
    $res = $db->select("Patching", "*", "$where ORDER BY termination_id");
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      $item = new Patching($data);
      if($item->id) {
        return $item;
      } else {
        return null;
      }
    }
    return null;
  }
  
  public static function getFirstByTermination($filter = false) {
    $db = FronkDB::singleton();
    
    $where = self::getTerminationSqlFilter($filter);

    $sql = "SELECT Termination.id as termination_id FROM `Order`
            LEFT JOIN OrderProduct ON (OrderProduct.order_id = `Order`.id)
            LEFT JOIN Product ON (Product.id = OrderProduct.product_id)
            LEFT JOIN Termination ON (Termination.id = OrderProduct.termination_id)
            LEFT JOIN Building ON (Building.id = Termination.building_id)
            LEFT JOIN Terminationstatus ON (Terminationstatus.id = Termination.status_id)
            LEFT JOIN Buildingstatus ON (Buildingstatus.id = Building.status_id)
            LEFT JOIN Patching ON (Patching.Termination_id = OrderProduct.termination_id)
            LEFT JOIN Workflowitem ON (Workflowitem.object_type = 'Termination')
            LEFT JOIN Workflowvalue ON (Workflowvalue.item_id = Workflowitem.id)
            WHERE Workflowitem.name = 'customer_passive_finished'
            AND Workflowvalue.object_id = OrderProduct.termination_id
            AND Workflowvalue.value_int = 1
            AND $where
            GROUP BY Termination.id
            ORDER BY Termination.id ASC";
    
    // AND (Patching.patched IS NULL OR Patching.patched = 0)
    mfLoghandler::singleton()->debug($sql);
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      $item = PatchingModel::getFirst(["termination_id" => $data->termination_id]);
      //$item = new Patching($data->termination_id);
      return $item;
    }
    
    return null;
  }
  
  public static function searchByFinishedLineworkCount($filter = false) {
    $items = [];
    $db = FronkDB::singleton();
    
    $where = self::getTerminationSqlFilter($filter);
    
    $sql = "SELECT COUNT(Termination.id) as cnt FROM `Order`
            LEFT JOIN OrderProduct ON (OrderProduct.order_id = `Order`.id)
            LEFT JOIN Product ON (Product.id = OrderProduct.product_id)
            LEFT JOIN Termination ON (Termination.id = OrderProduct.termination_id)
            LEFT JOIN Building ON (Building.id = Termination.building_id)
            LEFT JOIN Terminationstatus ON (Terminationstatus.id = Termination.status_id)
            LEFT JOIN Buildingstatus ON (Buildingstatus.id = Building.status_id)
            LEFT JOIN Patching ON (Patching.Termination_id = OrderProduct.termination_id)
            LEFT JOIN Workflowitem ON (Workflowitem.object_type = 'Termination')
            LEFT JOIN Workflowvalue ON (Workflowvalue.item_id = Workflowitem.id)
            WHERE Workflowitem.name = 'customer_passive_finished'
            AND Workflowvalue.object_id = OrderProduct.termination_id
            AND Workflowvalue.value_int = 1
            AND $where
            ORDER BY Termination.id ASC LIMIT 1";
    
    mfLoghandler::singleton()->debug($sql);
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      return $data->cnt;
    }
    
    return 0;
  }
  
  public static function searchByFinishedLinework($filter = false, $limit = false) {
    $items = [];
    $db = FronkDB::singleton();
    
    $where = self::getTerminationSqlFilter($filter);
// TEMP: vorpatchen
    $sql = "SELECT Termination.id as termination_id FROM `Order`
            LEFT JOIN OrderProduct ON (OrderProduct.order_id = `Order`.id)
            LEFT JOIN Product ON (Product.id = OrderProduct.product_id)
            LEFT JOIN Termination ON (Termination.id = OrderProduct.termination_id)
            LEFT JOIN Building ON (Building.id = Termination.building_id)
            LEFT JOIN Terminationstatus ON (Terminationstatus.id = Termination.status_id)
            LEFT JOIN Buildingstatus ON (Buildingstatus.id = Building.status_id)
            LEFT JOIN Patching ON (Patching.Termination_id = OrderProduct.termination_id)
            LEFT JOIN Workflowitem ON (Workflowitem.object_type = 'Termination')
            LEFT JOIN Workflowvalue ON (Workflowvalue.item_id = Workflowitem.id)
            WHERE Workflowitem.name = 'customer_passive_finished'
            AND Workflowvalue.object_id = OrderProduct.termination_id
            AND Workflowvalue.value_int = 1
            AND $where
            GROUP BY Termination.id
            ORDER BY Termination.id ASC";
    
    // AND (Patching.patched IS NULL OR Patching.patched = 0)
    mfLoghandler::singleton()->debug($sql);
    
    if(is_array($limit) && count($limit)) {
      if(is_numeric($limit['start']) && is_numeric($limit['count'])) {
        $sql .= " LIMIT ".$limit['start'].", ".$limit['count'];
      } elseif(is_numeric($count)) {
        $sql .= " LIMIT ".$limit['count'];
      }
    }
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $items[] = new Termination($data->termination_id);
      }
    }
    
    return $items;
  }
  
  public static function searchByEnabledPatchingCount($filter = false) {
    $items = [];
    $db = FronkDB::singleton();
    
    $where = self::getTerminationSqlFilter($filter);
    
    $sql = "SELECT COUNT(Termination.id) as cnt FROM `Order`
            LEFT JOIN OrderProduct ON (OrderProduct.order_id = `Order`.id)
            LEFT JOIN Product ON (Product.id = OrderProduct.product_id)
            LEFT JOIN Termination ON (Termination.id = OrderProduct.termination_id)
            LEFT JOIN Terminationstatus ON (Terminationstatus.id = Termination.status_id)
            LEFT JOIN Building ON (Building.id = Termination.building_id)
            LEFT JOIN Buildingstatus ON (Buildingstatus.id = Building.status_id)
            LEFT JOIN Patching ON (Patching.Termination_id = OrderProduct.termination_id)
            LEFT JOIN Workflowitem ON (Workflowitem.object_type = 'Termination')
            LEFT JOIN Workflowvalue ON (Workflowvalue.item_id = Workflowitem.id)
            WHERE Termination.patching_enabled = 1
            AND Workflowitem.name = 'customer_passive_finished'
            AND Workflowvalue.object_id = OrderProduct.termination_id
            AND Workflowvalue.value_int <> 1
            AND $where";
    
    mfLoghandler::singleton()->debug($sql);
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      return $data->cnt;
    }
    
    return 0;
  }
  
  public static function searchByEnabledPatching($filter = false, $limit = false) {
    $items = [];
    $db = FronkDB::singleton();
    
    $where = self::getTerminationSqlFilter($filter);
// TEMP: vorpatchen
    $sql = "SELECT Termination.id as termination_id FROM `Order`
            LEFT JOIN OrderProduct ON (OrderProduct.order_id = `Order`.id)
            LEFT JOIN Product ON (Product.id = OrderProduct.product_id)
            LEFT JOIN Termination ON (Termination.id = OrderProduct.termination_id)
            LEFT JOIN Terminationstatus ON (Terminationstatus.id = Termination.status_id)
            LEFT JOIN Building ON (Building.id = Termination.building_id)
            LEFT JOIN Buildingstatus ON (Buildingstatus.id = Building.status_id)
            LEFT JOIN Patching ON (Patching.Termination_id = OrderProduct.termination_id)
            LEFT JOIN Workflowitem ON (Workflowitem.object_type = 'Termination')
            LEFT JOIN Workflowvalue ON (Workflowvalue.item_id = Workflowitem.id)
            WHERE Termination.patching_enabled = 1
            AND Workflowitem.name = 'customer_passive_finished'
            AND Workflowvalue.object_id = OrderProduct.termination_id
            AND Workflowvalue.value_int <> 1
            AND $where
            GROUP BY Termination.id
            ORDER BY Termination.id ASC";
    
    // AND (Patching.patched IS NULL OR Patching.patched = 0)
    mfLoghandler::singleton()->debug($sql);
    
    if(is_array($limit) && count($limit)) {
      if(is_numeric($limit['start']) && is_numeric($limit['count'])) {
        $sql .= " LIMIT ".$limit['start'].", ".$limit['count'];
      } elseif(is_numeric($count)) {
        $sql .= " LIMIT ".$limit['count'];
      }
    }
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $items[] = new Termination($data->termination_id);
      }
    }
    
    return $items;
  }
  
  public static function search($filter = false, $limit = false) {
    $items = [];
    $db = FronkDB::singleton();
    
    $where = self::getPatchingSqlFilter($filter);
    $res = $db->select("Patching", "*", "$where ORDER BY termination_id");
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $items[] = new Patching($data);
      }
    }
    return $items;
  }
  
  private function getTerminationSqlFilter($filter = []) {
    $where = "1=1 ";
    if(!is_array($filter) || !count($filter)) {
      return $where;
    }

    //var_dump($filter);exit;
    if(array_key_exists("termination_id", $filter)) {
      $termination_id = $filter['termination_id'];
      if(is_numeric($termination_id)) {
        $where .= " AND Patching.termination_id=$termination_id";
      }
    }
    
    if(array_key_exists("patched", $filter)) {
      $patched = $filter["patched"];
      if($patched) {
        $where .= " AND Patching.patched=1";
      } else {
        $where .= " AND (Patching.patched IS NULL OR Patching.patched = 0)";
      }
    } else {
      $where .= " AND (Patching.patched IS NULL OR Patching.patched = 0)";
      
    }
    
    if(array_key_exists("hide_delayed_finish", $filter)) {
      $hide_delayed_finish = $filter["hide_delayed_finish"];
      if($hide_delayed_finish) {
        $where .= " AND (`Order`.finish_after IS NULL OR `Order`.finish_after <= ".(date("U") + (31 * 86400))." )";
      }
    }
    
    if(array_key_exists("network_id", $filter)) {
      $network_id = $filter['network_id'];
      if(is_numeric($network_id)) {
        $where .= " AND Building.network_id=$network_id";
      } elseif(is_array($network_id) && count($network_id)) {
        $where .= " AND Building.network_id IN (". implode(",", $network_id).")";
      }
    }
    
    if(array_key_exists("pop_id", $filter)) {
      $pop_id = $filter['pop_id'];
      if(is_numeric($pop_id)) {
        $where .= " AND Building.pop_id=$pop_id";
      }
    }
    
    if(array_key_exists("code", $filter)) {
      $code = FronkDB::singleton()->escape($filter['code']);
      if($code) {
        $where .= " AND Building.`code` like '%$code%'";
      }
    }
    
    if(array_key_exists("street", $filter)) {
      $street = FronkDB::singleton()->escape($filter["street"]);
      if($street) {
        $where .= " AND Building.street like '%$street%'";
      }
    }
    
    //var_dump($filter, $where);exit;
    return $where;
  }
  
  private function getPatchingSqlFilter($filter = []) {
    $where = "1=1 ";
    if(!is_array($filter) || !count($filter)) {
      return $where;
    }

    //var_dump($filter);exit;
    if(array_key_exists("termination_id", $filter)) {
      $termination_id = $filter['termination_id'];
      if(is_numeric($termination_id)) {
        $where .= " AND Patching.termination_id=$termination_id";
      }
    }
    
    if(array_key_exists("patched", $filter)) {
      $patched = $filter["patched"];
      if($patched) {
        $where .= " AND Patching.patched=1";
      } else {
        $where .= " AND (Patching.patched IS NULL OR Patching.patched = 0)";
      }
    }
    
    if(array_key_exists("hide_delayed_finish", $filter)) {
      $hide_delayed_finish = $filter["hide_delayed_finish"];
      if($hide_delayed_finish) {
        $where .= " AND (`Order`.finish_after IS NULL OR `Order`.finish_after <= ".(date("U") + (31 * 86400))." )";
      }
    }
    
    if(array_key_exists("network_id", $filter)) {
      $network_id = $filter['network_id'];
      if(is_numeric($network_id)) {
        $where .= " AND Building.network_id=$network_id";
      } elseif(is_array($network_id) && count($network_id)) {
        $where .= " AND Building.network_id IN (". implode(",", $network_id).")";
      }
    }
    
    if(array_key_exists("pop_id", $filter)) {
      $pop_id = $filter['pop_id'];
      if(is_numeric($pop_id)) {
        $where .= " AND Building.pop_id=$pop_id";
      }
    }
    
    if(array_key_exists("code", $filter)) {
      $code = FronkDB::singleton()->escape($filter['code']);
      if($code) {
        $where .= " AND Building.`code` like '%$code%'";
      }
    }
    
    if(array_key_exists("street", $filter)) {
      $street = FronkDB::singleton()->escape($filter["street"]);
      if($street) {
        $where .= " AND Building.street like '%$street%'";
      }
    }
    
    //var_dump($filter, $where);exit;
    return $where;
  }
  
}