<?php

class AddressModel {
  public $parent_id = null;
  public $customer_number = null;
  public $spin = null;
  public $company = null;
  public $firstname = null;
  public $lastname = null;
  public $street = null;
  public $zip = null;
  public $city = null;
  public $country = null;
  public $phone = null;
  public $fax = null;
  public $mobile = null;
  public $email = null;
  public $note = null;
  
  public $create_by = null;
  public $edit_by = null;
  public $create = null;
  public $edit = null;

  public static function create(Array $data) {
    $model = new Address();
    
    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;
    }
    
    if(!array_key_exists("note", $data)) {
      $model->note = "";
    }
    
    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("Address", "*", "id=$id LIMIT 1");
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      $item = new Address($data);
    }
    return $item;
  }
  
  public static function getAll() {
    $items = [];
    
    $db = FronkDB::singleton();
    
    $res = $db->select("Address", "*");
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $items[] = new Address($data);
      }
    }
    return $items;
    
  }
  
  public static function getLastCustomerNumber() {
    $db = FronkDB::singleton();
    $res = $db->select("Address","customer_number", "customer_number > 0 ORDER BY customer_number DESC LIMIT 1");
    if(!$db->num_rows($res)) {
      return false;
    }
    
    if($db->num_rows($res)) {
      $data = $db->fetch_object($res);
      return $data->customer_number;
    }
    
    return false;
  }
  
  public static function byNetwork($network_id, $addresstype) {
    if(!is_numeric($network_id) || !$network_id) {
      return false;
    }
    $db = FronkDB::singleton();
    
    $addresses = [];
    
    // get all addresses of network
    
    $sql = "SELECT Address.id as id FROM `Address`
            LEFT JOIN NetworkAddress ON (NetworkAddress.address_id = Address.id)
            WHERE NetworkAddress.type = '$addresstype'
            AND network_id = $network_id
            GROUP BY id";
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $addresses[] = new Address($data->id);
      }
    }
    
    return $addresses;
  }
  
  public static function count($filter) {
    $db = FronkDB::singleton();
    
    $where = self::getSqlFilter($filter);
    $sql = "SELECT COUNT(*) as cnt FROM (
              SELECT Address.id as address_id
              FROM Address
              LEFT JOIN Addresstype ON (Addresstype.address_id = Address.id)
              WHERE $where
              GROUP BY Address.id
            ) as tbl";
    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 search($filter, $limit = false) {
    //var_dump($filter);exit;
    $items = [];
    $db = FronkDB::singleton();
    
    $where = self::getSqlFilter($filter);
    $have = [];
    /*$sql = "SELECT Address.* FROM Address, Addresstype
            WHERE Addresstype.address_id = Address.id
            AND $where
            GROUP BY Addresstype.address_id
            ORDER BY Address.id";*/
    $sql = "SELECT Address.* FROM Address
            LEFT JOIN Addresstype ON (Addresstype.address_id = Address.id)
            WHERE $where
            GROUP BY Address.id
            ORDER BY company, lastname, firstname, zip, city, Address.id";
    
    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'];
      }
    }
    
    mfLoghandler::singleton()->debug($sql);
    
    $res = $db->query($sql);
    if($db->num_rows($res)) {
      while($data = $db->fetch_object($res)) {
        $items[] = new Address($data);
        //$have[] = $data->id;
      }
    }
    /*
    if(!array_key_exists("addresstype", $filter)) {
      if($have) {
        $res = $db->select("Address", "*", "$where AND id NOT IN (".implode(",", $have).")");
      } else {
        $res = $db->select("Address", "*", "$where AND id");
      }
      if($db->num_rows()) {
        while($data = $db->fetch_object($res)) {
          $items[] = new Address($data);
        }
      }
    }*/
    
    return $items;
  }
  
  private function getSqlFilter($filter) {
    $where = "1=1 ";
    
    //var_dump($filter);exit;
    if(array_key_exists("customer_number", $filter)) {
      $cn = $filter["customer_number"];
      if(is_numeric($cn)) {
        $where .= " AND customer_number=$cn";
      }
    }
    
    if(array_key_exists("spin", $filter)) {
      $spin = FronkDB::singleton()->escape($filter["spin"]);
      if($spin) {
        $where .= " AND spin='$spin'";
      }
    }
    
    if(array_key_exists("company", $filter)) {
      $company = FronkDB::singleton()->escape($filter["company"]);
      if($company) {
        $where .= " AND company like '%$company%'";
      }
    }
    
    if(array_key_exists("firstname", $filter)) {
      $firstname = FronkDB::singleton()->escape($filter["firstname"]);
      if($firstname) {
        $where .= " AND firstname like '%$firstname%'";
      }
    }
    
    if(array_key_exists("lastname", $filter)) {
      $lastname = FronkDB::singleton()->escape($filter["lastname"]);
      if($lastname) {
        $where .= " AND lastname like '%$lastname%'";
      }
    }
    
    if(array_key_exists("street", $filter)) {
      $street = FronkDB::singleton()->escape($filter["street"]);
      if($street) {
        $where .= " AND street like '%$street%'";
      }
    }
    
    if(array_key_exists("zip", $filter)) {
      $zip = FronkDB::singleton()->escape($filter["zip"]);
      if($zip) {
        $where .= " AND zip like '%$zip%'";
      }
    }
    
    if(array_key_exists("city", $filter)) {
      $city = FronkDB::singleton()->escape($filter["city"]);
      if($city) {
        $where .= " AND city like '%$city%'";
      }
    }
    
    if(array_key_exists("country", $filter)) {
      $country = FronkDB::singleton()->escape($filter["country"]);
      if($country) {
        $where .= " AND country like '%$country%'";
      }
    }
    
    if(array_key_exists("email", $filter)) {
      $email = FronkDB::singleton()->escape($filter["email"]);
      if($email) {
        $where .= " AND email like '%$email%'";
      }
    }
    
    if(array_key_exists("pfm", $filter)) {
      $pfm = FronkDB::singleton()->escape($filter["pfm"]);
      if($pfm) {
        $where .= " AND (phone like '%$pfm%' OR fax like '%$pfm%' OR mobile like '%$pfm%' )";
      }
    }
    
    /*
     * Address Type
     */
    if(is_array($filter['addresstype']) && count($filter['addresstype'])) {
      $at = $filter['addresstype'];
      $in = [];
      foreach(TT_ROLES as $role) {
        if(in_array($role, $at)) {
          $in[] = "Addresstype.type = '$role'";
        }
      }
      
      $or = "";
      if(count($in)) {
        $or = implode(" OR ", $in);
        $where .= " AND ( $or )";
      }
    }
    
    //var_dump($filter);exit;
    if(array_key_exists("parent_id", $filter)) {
      $parentid = $filter['parent_id'];
      if($parentid === null || $parent_id == "null") {
        $where .= " AND parent_id IS NULL";
      } elseif(is_numeric($parentid)) {
        $where .= " AND parent_id=$parentid";
      }
    }
    
    if(array_key_exists("create_by", $filter)) {
      $create_by = $filter['create_by'];
      if(is_numeric($create_by)) {
        $where .= " AND Address.create_by=$create_by";
      } elseif(is_array($create_by) && count($create_by)) {
        $where .= " AND Address.create_by IN (". implode(",",$create_by).")";
      }
    }
    
    if(array_key_exists("parents_only", $filter)) {
      $po = $filter['parents_only'];
      if($po) {
        $where .= " AND parent_id IS NULL";
      }
    }
    //var_dump($filter, $where);exit;
    return $where;
  }
  
}