<?php

defined('BASEPATH') or exit('No direct script access allowed');

/**
 * Get all states stored in database
 * @return array
 */
function get_all_states($countryId)
{
    return hooks()->apply_filters('all_states', get_instance()->db->where('country_id', $countryId)->order_by('short_name', 'asc')->get(db_prefix().'states')->result_array());
}
/**
 * Get state row from database based on passed state id
 * @param  mixed  $id
 * @return object
 */
function get_state($id)
{
    $CI = & get_instance();

    $state = $CI->app_object_cache->get('db-state-' . $id);

    if (!$state) {
        $CI->db->where('state_id', $id);
        $state = $CI->db->get(db_prefix().'states')->row();
        $CI->app_object_cache->add('db-state-' . $id, $state);
    }

    return $state;
}
/**
 * Get state short name by passed id
 * @param  mixed $id county id
 * @return mixed
 */
function get_state_short_name($id)
{
    $state = get_state($id);
    if ($state) {
        return $state->short_name;
    }

    return '';
}
/**
 * Get state name by passed id
 * @param  mixed $id county id
 * @return mixed
 */
function get_state_name($id)
{
    $state = get_state($id);
    if ($state) {
        return $state->long_name;
    }

    return '';
}

function get_state_id($state_name,$id_country = false)
{
    $CI = & get_instance();

    $CI->db->where('short_name', $state_name);
    $CI->db->or_where('long_name', $state_name);
    if($id_country){
      $CI->db->where('country_id', $id_country);
    }
    $state = $CI->db->get(db_prefix().'states')->row();
    if($state){
      return $state->state_id;
    }else{
      $CI->db->where('alias_value', $state_name);
      if($id_country){
        $CI->db->where('id_country', $id_country);
      }
      $state = $CI->db->get(db_prefix().'states_alias')->row();
      if($state){
        return $state->id_state;
      }
      return null;
    }
}


function format_address_line($company){
  if(isset($company['address'])){
    if(isset($company['state'])){
      if(isset($company['city'])){
        return $company['address'].', '.$company['state'].', '.$company['city'];
      }else{
        return $company['address'].', '.$company['state'];
      }
    }else{
      if(isset($company['city'])){
        return $company['address'].', '.$company['city'];
      }else{
        return $company['address'];
      }
    }
  }else{
    if(isset($company['state'])){
      if(isset($company['city'])){
        return $company['state'].', '.$company['city'];
      }else{
        return $company['state'];
      }
    }else{
      if(isset($company['city'])){
        return $company['city'];
      }else{
        return '';
      }
    }
  }
}
