<?php

function materio_contactops_materials($current_user){
  // dsm($current_user, 'current_user');

  global $language;
  global $user;
  // dsm($user, 'user');



  // get user company tag
  $company_tid = $current_user->field_company['und'][0]['tid'];
  // dsm($company_tid,'company_tid');

  # retrieve viewmode and then use it to define the query range
  $viewmode = isset($user->data['materiosearchapi_viewmode'])
    ? $user->data['materiosearchapi_viewmode']
    : variable_get('defaultviewmode', 'full');

  $limit = variable_get($viewmode.'_limite', '10');
  // dsm($limit, "limit");

  $offset = pager_find_page() * $limit; //$page*$limit;//
  // dsm($offset, "offset");

  // get materials taged with this company
  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->entityCondition('bundle', array('materiau'))
    // ->fieldCondition('field_company_distrib', 'tid', $company_tid, '=')
    ->fieldCondition('field_company_fab', 'tid', $company_tid, '=')
    ->propertyOrderBy('created', 'DESC')
    ->range($offset,$limit);
  $result = $query->execute();
  // dsm($result, '$result');
  foreach ($result['node'] as $nid => $n) {
    $items[] = node_load($nid);
  }

  $count_query = new EntityFieldQuery;
  $count_query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->entityCondition('bundle', array('materiau'))
    // ->fieldCondition('field_company_distrib', 'tid', $company_tid, '=')
    ->fieldCondition('field_company_fab', 'tid', $company_tid, '=');
  // dsm($count, 'count');

  $count = $count_query->count()->execute();

  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->entityCondition('bundle', array('materiau'))
    ->fieldCondition('field_company_distrib', 'tid', $company_tid, '=')
    // ->fieldCondition('field_company_fab', 'tid', $company_tid, '=')
    ->propertyOrderBy('created', 'DESC')
    ->range($offset,$limit);
  $result = $query->execute();
  // dsm($result, '$result');
  foreach ($result['node'] as $nid => $n) {
    $items[] = node_load($nid);
  }

  $count_query = new EntityFieldQuery;
  $count_query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->entityCondition('bundle', array('materiau'))
    // ->fieldCondition('field_company_distrib', 'tid', $company_tid, '=')
    ->fieldCondition('field_company_fab', 'tid', $company_tid, '=');
  // dsm($count, 'count');

  $count += $count_query->count()->execute();

  pager_default_initialize($count, $limit);

  drupal_set_title(t(''));

  return theme('materio_contactops_materials', array(
    'items' => $items,
    'view_mode' => $viewmode,
    'count' => $count,
    'pager' => theme('pager'),
  ));
}


function materio_companies_export(){
  // get materials taged with this company
  $query = new EntityFieldQuery;
  $query
    ->entityCondition('entity_type', 'node')
    ->propertyCondition('status', 1)
    ->entityCondition('bundle', array('company'))
    ->propertyOrderBy('title', 'ASC');

  $result = $query->execute();
  // dsm($result, '$result');
  $headers = array("name", "email", "materials");
  // $k=1;
  $items = [];
  if(isset($result['node'])){
    $companies = $result['node'];

    // At first we need to get field's id.
    // If you already know field id, you can ommit this step
    // Get all fields attached to a given node type
    $company_fields = field_info_instances('node', 'company');
    // dsm($company_fields, 'fields');
    $materiau_fields = field_info_instances('node', 'materiau');
    // dsm($materiau_fields, 'fields');

    // Attach a field of selected id only to get value for it
    $field_tode_company_id = $company_fields['field_tode_company']['field_id'];
    field_attach_load('node', $companies, FIELD_LOAD_CURRENT, array('field_id' => $field_tode_company_id));
    $field_public_email_id = $company_fields['field_public_email']['field_id'];
    field_attach_load('node', $companies, FIELD_LOAD_CURRENT, array('field_id' => $field_public_email_id));

    $title_field_materio_id = $materiau_fields['title_field']['field_id'];
    $field_reference_materio_id = $materiau_fields['field_reference_materio']['field_id'];

    // dsm($companies, "companies");

    foreach ($companies as $comp_nid => $company) {
      // if($k)
      //   dsm($company, "company");


      // title
      $title = db_query('SELECT title FROM {node} WHERE nid = :nid', array(':nid' => $comp_nid))->fetchField();
      // if($k)
      //   dsm($title, "title");
      $item = array(trim($title));

      // emails
      $email = $company->field_public_email['und'][0]["email"];
      $item[] = trim($email);

      // get the company taxo terme (tode)
      $tid = $company->field_tode_company['und'][0]['tid'];

      // dsm($tid, "tid");
      // get all materials tagued with this terme
      $materials_query = new EntityFieldQuery;
      $materials_query
        ->entityCondition('entity_type', 'node')
        ->propertyCondition('status', 1)
        ->entityCondition('bundle', array('materiau'))
        ->fieldCondition('field_company_fab', 'tid', $tid, '=')
        ->propertyOrderBy('created', 'DESC');
      $materials_result = $materials_query->execute();
      // if($k)
      //   dsm($materials_result , 'materials_result');

      if(isset($materials_result['node'])){
        $materials = $materials_result['node'];

        field_attach_load('node', $materials, FIELD_LOAD_CURRENT, array('field_id' => $title_field_materio_id));
        field_attach_load('node', $materials, FIELD_LOAD_CURRENT, array('field_id' => $field_reference_materio_id));

        $materials_output = [];
        // $m=1;
        foreach ($materials as $mnid => $mn) {
          // if($k && $m)
          //   dsm($mn, "materiau");

          $name = trim($mn->title_field['fr'][0]['value']);
          $ref = trim($mn->field_reference_materio['und'][0]['value']);

          // if($k && $m){
          //   dsm($name, "name");
          //   dsm($ref, "ref");
          // }

          $materials_output[] = $name." (".$ref.")";
          // $m=0;
        }
        // if($k)
        //   dsm($materials_output, 'materials_output');

        $item[] = implode(",", $materials_output);
      }

      // record the csv line
      $items[] = $item;
      // $k=0;
    }

    // dsm($items, "items");
  }
  // drupal_set_title("Companies export");
  drupal_add_http_header('Content-Type', 'text/csv; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment;filename=materio_companies.csv');

  $separator=";";
  $rows = implode($separator, $headers) . "\r\n";
  foreach ($items as $count => $item_row):
    $rows .= implode($separator, $item_row) . "\r\n";
  endforeach;
  print $rows;
}


function materio_contactops_export(){
  $role = user_role_load_by_name('Contact opérationnel');
  $uids = db_select('users_roles', 'ur')
      ->fields('ur', array('uid'))
      ->condition('ur.rid', $role->rid, '=')
      ->execute()
      ->fetchCol();
  // dsm($uids, "uids");
  $users = user_load_multiple($uids);
  // dsm($users, "users");

  $companies = array(); // cache array
  $companies_material_cache = array(); // cache array
  $items = [];
  $headers = ['company', 'mail', 'materials'];
  foreach ($users as $uid => $user) {
    // $item = [];
    // TODO: get company from
    $company_tid = $user->field_company['und'][0]['tid'];
    if(isset($companies[$company_tid])){
      $company = $companies[$company_tid];
    }else{
      $company = taxonomy_term_load($company_tid);
      $companies[$company_tid] = $company;
    }

    // avoid users withour company
    if(!isset($company->name)){
      continue;
    }

    // if(count($items) < 1){
    //   dsm($user, "user");
    //   dsm($company, "company");
    // }

    if(!isset($companies_material_cache[$company->name])){
      // get all materials tagued with this company terme
      $materials_query = new EntityFieldQuery;
      $materials_query
        ->entityCondition('entity_type', 'node')
        ->propertyCondition('status', 1)
        ->entityCondition('bundle', array('materiau'))
        ->fieldCondition('field_company_fab', 'tid', $company_tid, '=')
        ->propertyOrderBy('created', 'DESC');
      $materials_result = $materials_query->execute();
      //
      $materials_array = [];
      //
      if(isset($materials_result['node'])){
        $materials = $materials_result['node'];

        field_attach_load('node', $materials, FIELD_LOAD_CURRENT, array('field_id' => $title_field_materio_id));
        field_attach_load('node', $materials, FIELD_LOAD_CURRENT, array('field_id' => $field_reference_materio_id));

        foreach ($materials as $mnid => $mn) {
          $name = trim($mn->title_field['fr'][0]['value']);
          $ref = trim($mn->field_reference_materio['und'][0]['value']);
          $materials_array[] = $name." (".$ref.")";
        }

        $companies_material_cache[$company->name] = implode(",", $materials_array);
      }
    }

    $item = array(
      "company" => $company->name,
      "mail" => $user->mail,
      "materials" => $companies_material_cache[$company->name]
    );

    $items[] = $item;
  }

  // Obtient une liste de colonnes
  foreach ($items as $key => $row) {
      $company_col[$key]  = $row['company'];
  }

  // Trie les données par company croissant
  // Ajoute $items en tant que dernier paramètre, pour trier par la clé commune
  array_multisort($company_col, SORT_ASC, $items);

  // dsm($items);

  // drupal_set_title("Companies export");
  drupal_add_http_header('Content-Type', 'text/csv; utf-8');
  drupal_add_http_header('Content-Disposition', 'attachment;filename=materio_companies.csv');

  $separator=";";
  $rows = implode($separator, $headers) . "\r\n";
  foreach ($items as $count => $item_row):
    $rows .= implode($separator, $item_row) . "\r\n";
  endforeach;
  print $rows;
}
