<?php

class OrderModel {
  public $owner_id;
  public $billingaddress_id;
  public $partner_number;
  public $order_date;
  public $finish_date;
  public $finish_after;
  public $finish_after_comment;
  public $billing_type;
  public $bank_account_bank;
  public $bank_account_owner;
  public $bank_account_iban;
  public $bank_account_bic;
  public $allow_contact;
  public $allow_spin;
  public $note;
  
  public $create_by = null;
  public $edit_by = null;
  public $create = null;
  public $edit = null;
  

  public static function create(Array $data) {
    $model = new Order();
    
    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("Order", "*", "id=$id LIMIT 1");
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      $item = new Order($data);
    }
    return $item;
  }
  
  public static function getAll() {
    $items = [];
    
    $db = FronkDB::singleton();
    
    $res = $db->select("Order", "*", "1=1 ORDER BY order_date, owner_id");
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $items[] = new Order($data);
      }
    }
    return $items;
    
  }
  
  public static function getFirst($filter = false) {
    $db = FronkDB::singleton();
    
    $where = self::getSqlFilter($filter);
    
    $sql = "SELECT `Order`.id as order_id, `Order`.* 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)
            
            WHERE $where
            GROUP BY `Order`.id
            ORDER BY `Order`.order_date ASC";
    $res = $db->query($sql);
    
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      $item = new Order($data);
      if($item->id) {
        return $item;
      } else {
        return null;
      }
    }
    return null;
  }
  
  public static function byProduct($filter) {
    
    
    
    $sql = "SELECT Order.id as order_id, * FROM `Order`
            LEFT JOIN OrderProduct ON (OrderProduct.order_id = `Order`.id)
            LEFT JOIN Product ON (Product.id = OrderProduct.product_id)
            WHERE
            GROUP BY `Order`.id
            ";
  }
  
  public static function byNetwork($network_id) {
    if(!is_numeric($network_id) || !$network_id) {
      return false;
    }
    $db = FronkDB::singleton();
    
    $orders = [];
    
    $sql = "SELECT `Order`.* FROM `Order`
            LEFT JOIN OrderProduct ON (OrderProduct.order_id = `Order`.id)
            LEFT JOIN Termination ON (Termination.id = OrderProduct.termination_id)
            LEFT JOIN Building ON (Building.id = Termination.building_id)

            WHERE OrderProduct.termination_id IS NOT NULL
            AND Building.network_id = $network_id
            ";
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $orders[] = new Order($data);
      }
    }
    
    return $orders;
  }
  
  public static function count($filter) {
    $db = FronkDB::singleton();
    
    $where = self::getSqlFilter($filter);
    /*$sql = "SELECT COUNT(*) 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)
            WHERE $where
            GROUP BY `Order`.id";*/
    
    $sql = "SELECT COUNT(*) as cnt FROM
              (SELECT `Order`.id FROM `Order`
              LEFT JOIN Address ON (Address.id = `Order`.owner_id)
              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)
              WHERE $where
              GROUP BY `Order`.id)
            as o";
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      return $data->cnt;
    }
    return 0;
  }
  
  public static function search($filter, $limit=false) {
    $items = [];
    $db = FronkDB::singleton();
    
    $where = self::getSqlFilter($filter);
    /*$sql = "SELECT `Order`.* FROM `Order`, OrderProduct
            WHERE OrderProduct.order_id = `Order`.id
            AND $where
            GROUP BY OrderProduct.order_id
            ORDER BY id
           ";*/
    $sql = "SELECT `Order`.id as order_id, `Order`.* FROM `Order`
            LEFT JOIN Address ON (Address.id = `Order`.owner_id)
            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)
            
            WHERE $where
            GROUP BY `Order`.id
            ORDER BY `Order`.order_date ASC";
    
    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 Order($data);
      }
    }
    
    
    return $items;
  }
  
  private function getSqlFilter($filter) {
    $where = "1=1 ";

    //var_dump($filter);exit;
    if(array_key_exists("owner_id", $filter)) {
      $ownerid = $filter['owner_id'];
      if(is_numeric($ownerid)) {
        $where .= " AND `Order`.owner_id=$ownerid";
      }
    }
    
    if(array_key_exists("owner", $filter)) {
      $owner = FronkDB::singleton()->escape($filter['owner']);
      if($owner) {
        $where .= " AND (Address.company like '%$owner%' OR Address.firstname like '%$owner%' OR Address.lastname like '%$owner%')";
      }
    }
    
    if(array_key_exists("owner", $filter)) {
      $owner = FronkDB::singleton()->escape($filter['owner']);
      if($owner) {
        $where .= " AND (Address.company like '%$owner%' OR Address.firstname like '%$owner%' OR Address.lastname like '%$owner%')";
      }
    }
    
    if(array_key_exists("partner_number", $filter)) {
      $partner_number = FronkDB::singleton()->escape($filter['partner_number']);
      if($partner_number) {
        $where .= " AND Order.partner_number like '%$partner_number%'";
      }
    }
    
    if(array_key_exists("create_by", $filter)) {
      $create_by = $filter['create_by'];
      if(is_numeric($create_by)) {
        $where .= " AND `Order`.create_by=$create_by";
      }
    }
    
    if(array_key_exists("finish_date", $filter)) {
      $finish_date = $filter['finish_date'];
      if($finish_date) {
        $where .= " AND `Order`.finish_date > 0";
      } else {
        $where .= " AND (`Order`.finish_date = 0 OR `Order`.finish_date IS NULL)";
      }
    }
    
    if(array_key_exists("name", $filter)) {
      $name = FronkDB::singleton()->escape($filter['name']);
      if($name) {
        $where .= " AND `Order`.name='$name'";
      }
    }
    
    if(array_key_exists("product_id", $filter)) {
      $product_id = $filter['product_id'];
      if($product_id) {
        if(in_array(substr($filter['product_id'], 0, 2), ["<=", ">="])) {
          $op = substr($filter['product_id'], 0, 2);
          $product_id = substr($filter['product_id'], 2);
        } elseif(in_array(substr($filter['product_id'], 0, 1), ["<", ">"])) {
          $op = substr($filter['product_id'], 0, 1);
          $product_id = substr($filter['product_id'], 1);
        } else {
          $op = "=";
          $product_id = $filter['product_id'];
        }
        if(is_numeric($product_id)) {
          $where .= " AND OrderProduct.product_id $op $product_id";
        }
      } elseif($product_id === null) {
        $where .= " AND OrderProduct.product_id IS NULL";
      }
    }
    
    if(array_key_exists("productgroup_id", $filter)) {
      $productgroup_id = $filter['productgroup_id'];
      if(is_numeric($productgroup_id)) {
        $where .= " AND Product.productgroup_id=$productgroup_id";
      }
    }
    
    if(array_key_exists("termination_id", $filter)) {
      $termination_id = $filter['termination_id'];
      if(is_numeric($termination_id)) {
        $where .= " AND OrderProduct.termination_id=$termination_id";
      } elseif($termination_id === null) {
        $where .= " AND OrderProduct.termination_id IS NULL";
      }
    }
    
    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)) {
        //var_dump($filter);exit;
        //var_dump($network_id);exit;
        if(array_key_exists("network_linked_status", $filter)) {
          $status_parts = [];
          foreach($network_id as $net_id) {
            if(!is_numeric($net_id)) {
              continue;
            }
            if(array_key_exists($net_id, $filter['network_linked_status'])) {
              if($filter['network_linked_status'][$net_id] == "term_connected") {
                $status_parts[] = "(Building.network_id = $net_id AND Terminationstatus.code >= ".TT_TERMSTATUS_CONNECTED.")";
              }
              if($filter['network_linked_status'][$net_id] == "building_connected") {
                $status_parts[] = "(Building.network_id = $net_id AND Buildingstatus.code >= ".TT_BUILDINGSTATUS_CONNECTED.")";
              }
              if($filter['network_linked_status'][$net_id] == "pipework_needed") {
                $status_parts[] = "(Building.network_id = $net_id AND Buildingstatus.code <= ".TT_BUILDINGSTATUS_CONNECTED.")";
              }
            }
          }
          if(count($status_parts)) {
            $where .= " AND (".implode(" OR ", $status_parts).")";
          }
        } else {
          // just search for networks
          $where .= " AND Building.network_id IN (". implode(",", $network_id).")";
        }
        
      }
    }
    
    if(array_key_exists("building_networksection_id", $filter)) {
      $networksection_id = $filter['building_networksection_id'];
      if(is_numeric($networksection_id)) {
        $where .= " AND Building.networksection_id=$networksection_id";
      }
    }
    
    if(array_key_exists("building_code", $filter)) {
      $code = FronkDB::singleton()->escape($filter['building_code']);
      if($code) {
        $where .= " AND Building.code LIKE '%$code%'";
      }
    }
    
    if(array_key_exists("building_status_id", $filter)) {
      $building_status_id = $filter['building_status_id'];
      if(is_numeric($building_status_id)) {
        $where .= " AND Building.status_id=$building_status_id";
      }
    }
    
    if(array_key_exists("building_street", $filter)) {
      $street = FronkDB::singleton()->escape($filter['building_street']);
      if($street) {
        $where .= " AND Building.street LIKE '%$street%'";
      }
    }
    //var_dump($filter['building_status_code']);
    if(array_key_exists("building_status_code", $filter)) {
      if(in_array(substr($filter['building_status_code'], 0, 2), ["<=", ">="])) {
        $op = substr($filter['building_status_code'], 0, 2);
        $status = substr($filter['building_status_code'], 2);
      } elseif(in_array(substr($filter['building_status_code'], 0, 1), ["<", ">"])) {
        $op = substr($filter['building_status_code'], 0, 1);
        $status = substr($filter['building_status_code'], 1);
      } else {
        $op = "=";
        $status = $filter['building_status_code'];
      }
      
      //var_dump($op, $status);exit;
      
      if(is_numeric($status)) {
        $where .= " AND Buildingstatus.code $op $status";
      } else {
        // get code of statusname
        $code = BuildingstatusModel::getOne(["name" => $status]);
        if($code) {
          $status = FronkDB::singleton()->escape($status);
          $where .= " AND Buildingstatus.code $op '$status'";
        }
        
      }
    }
    //var_dump($filter['termination_status_code']);
    if(array_key_exists("termination_status_code", $filter)) {
      if(in_array(substr($filter['termination_status_code'], 0, 2), ["<=", ">="])) {
        $op = substr($filter['termination_status_code'], 0, 2);
        $status = substr($filter['termination_status_code'], 2);
      } elseif(in_array(substr($filter['termination_status_code'], 0, 1), ["<", ">"])) {
        $op = substr($filter['termination_status_code'], 0, 1);
        $status = substr($filter['termination_status_code'], 1);
      } else {
        $op = "=";
        $status = $filter['termination_status_code'];
      }
      
      //var_dump($op, $status);exit;
      
      if(is_numeric($status)) {
        $where .= " AND Terminationstatus.code $op $status";
      } else {
        // get code of statusname
        $code = TerminationstatusModel::getOne(["name" => $status]);
        if($code) {
          $status = FronkDB::singleton()->escape($status);
          $where .= " AND Terminationstatus.code $op '$status'";
        }
        
      }
    }
    
    //var_dump($filter, $where);exit;
    return $where;
  }
  
}