#!/usr/bin/php
<?php

require_once 'vendor/autoload.php';

// Load the .env file
$dotenv = new Dotenv\Dotenv(__DIR__);
$dotenv->load();

$client = new Redmine\Client(getenv('REDMINE_URL'), getenv('REDMINE_API_KEY'));
$client->setCheckSslCertificate(true);

$limit = 100;
$offset = 0;

list($projectsById, $projectsByDomain) = getProjectList($limit, $offset, $client);
writeDomains($projectsByDomain);
$userList = getUserList($limit, $offset, $client);
$membershipMapping = getUserMemberships($userList, $client);
writeUsers($projectsById, $membershipMapping);

function writeDomains($projectsByDomain) {
  $domainHandle = fopen('./data/domainmap.csv', 'w');
  foreach ($projectsByDomain as $domain => $identifier) {
    fwrite ($domainHandle, "$domain,$identifier\n");
  }
  fclose($domainHandle);
}

function writeUsers($projectsById, $membershipMapping) {
  $domainHandle = fopen('./data/usermap.csv', 'w');
  foreach ($membershipMapping as $email => $projectId) {
    fwrite ($domainHandle, "$email,{$projectsById[$projectId]}\n");
  }
  fclose($domainHandle);
}

function getProjectList($limit, $offset, $client) {
  //  We'll set a more realistic total user count after the first loop.
  $totalProjects = 99999;
  // Get a complete user list with email address.
  while ($offset + $limit < $totalProjects) {
    $listing = $client->project->all([
      'limit' => $limit,
      'offset' => $offset,
    ]);
    foreach ($listing['projects'] as $project) {
      // 0 is a magic number.  This might(?) fail if we ever add other project custom fields.
      if ($project['custom_fields'][0]['value']) {
        $domain = $project['custom_fields'][0]['value'];
        $projectsByDomain[$domain] = $project['identifier'];
      }
      $projectsById[$project['id']] = $project['identifier'];
    }
    $totalProjects  = $listing['total_count'];
    $offset += $limit;
  };
  $projects[] = $projectsById;
  $projects[] = $projectsByDomain;
  return $projects;
}

/*
 *  Returns an array of all users.  Key is user ID, value is email address.
 */
function getUserList($limit, $offset, $client) {
  //  We'll set a more realistic total user count after the first loop.
  $totalUsers = 99999;
  // Get a complete user list with email address.
  while ($offset + $limit < $totalUsers) {
    $listing = $client->user->all([
      'limit' => $limit,
      'offset' => $offset,
    ]);
    foreach ($listing['users'] as $user) {
      $users[$user['id']] = $user['mail'];
    }
    $totalUsers = $listing['total_count'];
    $offset += $limit;
  };
  return $users;
}
// Get the memberships of each user.  It's sad that we can't do this in bulk.
function getUserMemberships($users, $client) {
  foreach ($users as $id => $email) {
    $userDetails = $client->user->show($id, ['include' => ['memberships']])['user'];
    if (count($userDetails['memberships']) == 1) {
      $membershipMapping[$email] = $userDetails['memberships'][0]['project']['id'];
    }
  }
  return $membershipMapping;
}