function civicrm_api3_job_exportleaveregistration_months($params)
{
    $years = array($params['Year']);
    $months = explode(',', $params['Months']);
    echo 'Year: ' . '<br/>' . PHP_EOL;
    echo '<pre>';
    print_r($years);
    echo '</pre>';
    echo 'Months: ' . '<br/>' . PHP_EOL;
    echo '<pre>';
    print_r($months);
    echo '</pre>';
    $column_names = array(ts('Last name'), ts('First name'), ts('Full name'), ts('From'), ts('To'), ts('Message'));
    $column_days = array();
    $from = $params['Year'] . '-' . $months[0] . '-01';
    $to = $params['Year'] . '-' . end($months);
    $last_day = '';
    foreach ($years as $year) {
        foreach ($months as $month) {
            for ($day_month = 1; $day_month <= cal_days_in_month(CAL_GREGORIAN, $month, $year); $day_month++) {
                $timestamp = strtotime($year . '-' . $month . '-' . $day_month);
                $day = date('d', $timestamp);
                $column_days[] = ts($day . '-' . $month);
                $last_day = $day;
            }
        }
    }
    $to .= '-' . $last_day;
    /*echo('Columns Names / Days: ') . '<br/>' . PHP_EOL;
      echo('<pre>');
      print_r($column_names);
      print_r($column_days);
      echo('</pre>');*/
    // get all the employees, from civicrm
    $parameters = array('version' => 3, 'sequential' => 1, 'contact_type' => 'Individual', 'contact_sub_type' => 'Employee', 'options' => array('limit' => 0, 'sort' => 'last_name ASC'), 'is_deleted' => 0);
    $result = civicrm_api('Contact', 'get', $parameters);
    // if there is a error, set everything to empty expect the week, from day and to day, and set the error in the leave column
    if ($result['is_error']) {
        $row = array_merge(array('last_name' => '', 'first_name' => '', 'display_name' => '', 'from' => $from, 'to' => $to, 'message' => ts('Failt get all employees !')), $column_days);
    }
    /*echo('<pre>');
      print_r($result['values']);
      echo('</pre>');*/
    // loop through the employees
    foreach ($result['values'] as $employee) {
        $data = array();
        // define the variable that hold the class
        $lr = array();
        // set the class
        $lr = new leaveregistration('civicrm');
        // if there is a error, set sick to empty and set the error in the leave column
        if ($lr->isset_error()) {
            $rows[] = array_merge(array('last_name' => $employee['last_name'], 'first_name' => $employee['first_name'], 'display_name' => $employee['display_name'], 'from' => $from, 'to' => $to, 'message' => ts('Failt construct leave registration class !')), $column_days);
            continue;
        }
        // set the contact in the class
        $lr->set_contacts($employee['contact_id'], $employee['contact_id']);
        // if there is a error, set sick to empty and set the error in the leave column
        if ($lr->isset_error()) {
            $rows[] = array_merge(array('last_name' => $employee['last_name'], 'first_name' => $employee['first_name'], 'display_name' => $employee['display_name'], 'from' => $from, 'to' => $to, 'message' => ts('Failt set contacts leave registration class !')), $column_days);
            continue;
        }
        // set the data in the class
        $lr->set_data($years, array());
        // if there is a error, set sick to empty and set the error in the leave column
        if ($lr->isset_error()) {
            $rows[] = array_merge(array('last_name' => $employee['last_name'], 'first_name' => $employee['first_name'], 'display_name' => $employee['display_name'], 'from' => $from, 'to' => $to, 'message' => ts('Failt set contacts leave registration class !')), $column_days);
            continue;
        }
        $days = array();
        foreach ($years as $year) {
            foreach ($months as $month) {
                for ($day_month = 1; $day_month <= cal_days_in_month(CAL_GREGORIAN, $month, $year); $day_month++) {
                    $timestamp = strtotime($year . '-' . $month . '-' . $day_month);
                    $day = date('d', $timestamp);
                    // get the data from the contact, year, month and day
                    $data = $lr->data[$employee['contact_id']][$year][$month][$day];
                    // empty content
                    $content = array();
                    $leave = 0;
                    $sick = 0;
                    $time_for_time = 0;
                    if (isset($data['adjustments']['duration']) and 0 == $data['adjustments']['duration']) {
                        $content[] = 'Vrij';
                    }
                    // switch between the leave types
                    // and add the duration to the right counter (work, time for time, leave or sick)
                    if (isset($data['request']['is_request']) and 1 == $data['request']['is_request'] and 'approved' == $data['request']['status']) {
                        switch ($data['request']['leave_type']) {
                            case 'mom_dad_day':
                            case 'mom_dad_day_contiguous':
                            case 'doctor_visit':
                            case 'study_leave':
                            case 'care':
                            case 'special_leave':
                            case 'maternity':
                                $leave += $data['request']['duration'];
                                break;
                            case 'sick_less_one_day':
                            case 'sick':
                                $sick += $data['request']['duration'];
                                break;
                        }
                    }
                    // time_for_time
                    if (isset($data['time_for_time']['is_time_for_time']) and 1 == $data['time_for_time']['is_time_for_time'] and 'approved' == $data['time_for_time']['status']) {
                        $time_for_time = $data['time_for_time']['duration'];
                    }
                    // normal_leave
                    // leave type is normal_leave_less_one_day and normal_leave
                    if (isset($data['normal_leave']['is_normal_leave']) and 1 == $data['normal_leave']['is_normal_leave'] and 'approved' == $data['normal_leave']['status']) {
                        $leave += $data['normal_leave']['duration'];
                    }
                    // calculate the leave hours and the minutes from the duration (in minutes)
                    if ($leave > 0) {
                        $hours = floor($leave / 60);
                        $minutes = $leave - $hours * 60;
                        $content[] = 'V: ' . $hours . ':' . sprintf("%02s", $minutes);
                    }
                    // calculate the sick hours and the minutes from the duration (in minutes)
                    if ($leave > 0) {
                        $hours = floor($sick / 60);
                        $minutes = $sick - $hours * 60;
                        $content[] = 'Z: ' . $hours . ':' . sprintf("%02s", $minutes);
                    }
                    // create the row from the contact wiht the information
                    $days[] = implode(' ', $content);
                }
            }
        }
        $rows[] = array_merge(array('last_name' => $employee['last_name'], 'first_name' => $employee['first_name'], 'display_name' => $employee['display_name'], 'from' => $from, 'to' => $to, 'message' => ts('')), $days);
    }
    // create the actualy content of the csv file
    $content = '';
    // first the column names
    $content .= implode(';', $column_names) . ';' . implode(';', $column_days) . "\r\n";
    // loop through the rows of data
    // add them to the content for the csv file
    foreach ($rows as $key => $data) {
        $content .= implode(';', $data) . "\r\n";
    }
    echo $content . '<br/>' . PHP_EOL;
    unset($rows);
    unset($result);
    // donnot email if it is no
    if (!isset($params['doEmail']) or 'No' != $params['doEmail']) {
        civicrm_api3_job_exportleaveregistration_months_email($params, $content);
    }
}
 function buildRows($sql, &$rows)
 {
     // set days, months and years to empty
     $days = array();
     $months = array();
     $years = array();
     $year = $this->_formValues['year_value'];
     $week = $this->_formValues['week_value'];
     switch ($this->_formValues['period_value']) {
         case 'year':
             $years = [$this->_formValues['year_value']];
             $months = [];
             $first_day = date('Y-m-d', strtotime($this->_formValues['year_value'] . '-01-01'));
             $last_day = date('Y-m-d', strtotime($this->_formValues['year_value'] . '-12-31'));
             break;
         case 'month':
             $years = [$this->_formValues['year_value']];
             $months = [$this->_formValues['month_value']];
             $first_day = date('Y-m-d', strtotime($this->_formValues['year_value'] . '-' . $this->_formValues['month_value'] . '-01'));
             $last_day = date('Y-m-t', strtotime($this->_formValues['year_value'] . '-' . $this->_formValues['month_value'] . '-02'));
             break;
         case 'week':
             $dayrange = array(1, 2, 3, 4, 5, 6, 7);
             // calculate the days in the week
             for ($count = 0; $count <= 6; $count++) {
                 $week = $count == 7 ? $week + 1 : $week;
                 $week = str_pad($week, 2, '0', STR_PAD_LEFT);
                 $days[] = date('Y-m-d', strtotime($year . "W" . $week . $dayrange[$count]));
             }
             // calculate months and years from date
             // calculate years from days
             foreach ($days as $date) {
                 $year = date('Y', strtotime($date));
                 $years[$year] = $year;
                 $month = date('m', strtotime($date));
                 $months[$month] = $month;
             }
             $first_day = date('Y-m-d', strtotime($days[0]));
             $last_day = date('Y-m-d', strtotime(end($days)));
             break;
     }
     $start_date_totime = strtotime($first_day);
     $end_date_totime = strtotime($last_day);
     // create a array with all the employees, add department en business to the array, this
     $datas = [];
     $cids = [];
     $dao = CRM_Core_DAO::executeQuery($sql);
     while ($dao->fetch()) {
         $data = [];
         foreach ($this->_columnHeaders as $id => $columnheader) {
             $data[$id] = $dao->{$id};
         }
         $datas[$dao->civicrm_contact_id] = $data;
         $cids[] = $dao->civicrm_contact_id;
     }
     $lr = new leaveregistration('civicrm', 'CRM_Leaveregistration_Form_Report_LeaveRegistration');
     $lr->set_fields();
     $lr->set_contacts($cids);
     $lr->set_data($years, $months);
     for ($timestamp = $start_date_totime; $timestamp <= $end_date_totime; $timestamp = strtotime('+1 day', $timestamp)) {
         $day = date('d', $timestamp);
         $month = date('m', $timestamp);
         $year = date('Y', $timestamp);
         switch ($this->_formValues['period_value']) {
             case 'year':
                 $this->_columnHeaders[date('Y-m-d', $timestamp)] = array('title' => ts('Year') . ' ' . date('Y') . ' ' . date('m-d', $timestamp) . ' ' . ts(date('l', $timestamp)));
                 break;
             case 'month':
                 $this->_columnHeaders[date('Y-m-d', $timestamp)] = array('title' => ts('Month') . ' ' . ts(date('F', $timestamp)) . ' ' . date('m-d', $timestamp) . ' ' . ts(date('l', $timestamp)));
                 break;
             case 'week':
                 $this->_columnHeaders[date('Y-m-d', $timestamp)] = array('title' => ts('Week') . ' ' . date('W', $timestamp) . ' ' . date('m-d', $timestamp) . ' ' . ts(date('l', $timestamp)));
                 break;
         }
     }
     $rows = [];
     foreach ($datas as $cid => $data) {
         $row = [];
         // must before department and business
         foreach ($this->_columnHeaders as $id => $columnheader) {
             $row[$id] = $data[$id];
         }
         for ($timestamp = $start_date_totime; $timestamp <= $end_date_totime; $timestamp = strtotime('+1 day', $timestamp)) {
             $day = date('d', $timestamp);
             $month = date('m', $timestamp);
             $year = date('Y', $timestamp);
             // get the request from the contact, year, month and day
             $request = $lr->data[$data['civicrm_contact_id']][$year][$month][$day];
             // empty content
             $content = [];
             $leave = 0;
             $paid_leave = 0;
             $sick = 0;
             $time_for_time = 0;
             if (isset($request['adjustments']['duration']) and 0 == $request['adjustments']['duration']) {
                 $content[] = 'rv';
             }
             // switch between the leave types
             // and add the duration to the right counter (work, time for time, leave or sick)
             if (isset($request['request']['is_request']) and 1 == $request['request']['is_request'] and 'approved' == $request['request']['status']) {
                 switch ($request['request']['leave_type']) {
                     case 'mom_dad_day':
                     case 'mom_dad_day_contiguous':
                     case 'doctor_visit':
                     case 'study_leave':
                     case 'care':
                     case 'special_leave':
                     case 'maternity':
                         $paid_leave += $request['request']['duration'];
                         break;
                     case 'sick_less_one_day':
                     case 'sick':
                         $sick += $request['request']['duration'];
                         break;
                 }
             }
             // time_for_time
             if (isset($request['time_for_time']['is_time_for_time']) and 1 == $request['time_for_time']['is_time_for_time'] and 'approved' == $request['time_for_time']['status']) {
                 $time_for_time += $request['time_for_time']['duration'];
             }
             // normal_leave
             // leave type is normal_leave_less_one_day and normal_leave
             if (isset($request['normal_leave']['is_normal_leave']) and 1 == $request['normal_leave']['is_normal_leave'] and 'approved' == $request['normal_leave']['status']) {
                 $leave += $request['normal_leave']['duration'];
             }
             // calculate the leave hours and the minutes from the duration (in minutes)
             if ($leave > 0) {
                 $hours = floor($leave / 60);
                 $minutes = $leave - $hours * 60;
                 $content[] = 'v: ' . $hours . ':' . sprintf("%02s", $minutes);
             }
             if ($paid_leave > 0) {
                 $hours = floor($paid_leave / 60);
                 $minutes = $paid_leave - $hours * 60;
                 $content[] = 'bv: ' . $hours . ':' . sprintf("%02s", $minutes);
             }
             if ($sick > 0) {
                 $hours = floor($sick / 60);
                 $minutes = $sick - $hours * 60;
                 $content[] = 'z: ' . $hours . ':' . sprintf("%02s", $minutes);
             }
             if ($time_for_time > 0) {
                 $hours = floor($time_for_time / 60);
                 $minutes = $time_for_time - $hours * 60;
                 $content[] = 't: ' . $hours . ':' . sprintf("%02s", $minutes);
             }
             switch ($this->_formValues['period_value']) {
                 case 'year':
                     $row[date('Y-m-d', $timestamp)] = implode(' ', $content);
                     break;
                 case 'month':
                     $row[date('Y-m-d', $timestamp)] = implode(' ', $content);
                     break;
                 case 'week':
                     $row[date('Y-m-d', $timestamp)] = implode(' ', $content);
                     break;
             }
         }
         $rows[] = $row;
     }
 }
 public function processPart2($old_fields)
 {
     // set all fields
     $lr = new leaveregistration('civicrm', 'upgrade_2000_processPart2');
     $lr->set_fields();
     // get all request with leave type mom_dad_day, study_leave and care
     $query = "SELECT * FROM " . $lr->custom_groups['leave_request']['table_name'];
     $query .= " WHERE " . $lr->custom_fields['leave_request_leave_type']['column_name'] . " = 'mom_dad_day' ";
     $query .= " OR " . $lr->custom_fields['leave_request_leave_type']['column_name'] . " = 'mom_dad_day_contiguous' ";
     $query .= " OR " . $lr->custom_fields['leave_request_leave_type']['column_name'] . " = 'study_leave' ";
     $query .= " OR " . $lr->custom_fields['leave_request_leave_type']['column_name'] . " = 'care' ";
     $dao = CRM_Core_DAO::executeQuery($query);
     while ($dao->fetch()) {
         // copy all data
         $query = "UPDATE " . $lr->custom_groups['leave_request']['table_name'];
         $query .= " SET";
         switch ($dao->{$lr->custom_fields['leave_request_leave_type']['column_name']}) {
             case 'mom_dad_day_contiguous':
                 $query .= " " . $lr->custom_fields['leave_request_leave_type']['column_name'] . " = 'mom_dad_day'";
                 $query .= ", " . $lr->custom_fields['leave_request_daily_weekly_monthly_annually']['column_name'] . " = 'daily'";
                 $query .= ", " . $lr->custom_fields['leave_request_daily_each']['column_name'] . " = '1'";
                 $query .= ", " . $lr->custom_fields['leave_request_daily_every_day_working_day']['column_name'] . " = 'working_day'";
                 break;
             case 'mom_dad_day':
             case 'study_leave':
             case 'care':
                 switch ($dao->{$old_fields['leave_request_day_week_month_year']['column_name']}) {
                     case 'day':
                         $query .= " " . $lr->custom_fields['leave_request_daily_weekly_monthly_annually']['column_name'] . " = 'daily'";
                         $query .= ", " . $lr->custom_fields['leave_request_daily_each']['column_name'] . " = '" . $dao->{$old_fields['leave_request_each']['column_name']} . "'";
                         break;
                     case 'week':
                         $query .= " " . $lr->custom_fields['leave_request_daily_weekly_monthly_annually']['column_name'] . " = 'weekly'";
                         $query .= ", " . $lr->custom_fields['leave_request_weekly_each']['column_name'] . " = '" . $dao->{$old_fields['leave_request_each']['column_name']} . "'";
                         if ('nvt' != $dao->{$old_fields['leave_request_day_of_the_week']['column_name']}) {
                             $query .= ", " . $lr->custom_fields['leave_request_weekly_day_of_the_week']['column_name'] . " = '" . strtolower($dao->{$old_fields['leave_request_day_of_the_week']['column_name']}) . "'";
                         }
                         break;
                     case 'month':
                         $query .= " " . $lr->custom_fields['leave_request_daily_weekly_monthly_annually']['column_name'] . " = 'monthly'";
                         $query .= ", " . $lr->custom_fields['leave_request_monthly_each']['column_name'] . " = '" . $dao->{$old_fields['leave_request_each']['column_name']} . "'";
                         switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                             case 'nvt':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         // get day number of the month
                                         $day = date('d', strtotime($lr->custom_fields['leave_request_from_date']['column_name']));
                                         $query .= ", " . $lr->custom_fields['leave_request_monthly_every_day_of_the_month_day_of_the_week']['column_name'] . " = 'every_day'";
                                         $query .= ", " . $lr->custom_fields['leave_request_monthly_day_of_the_month']['column_name'] . " = '" . $day . "'";
                                         break;
                                     default:
                                         // check if it is the first, second, third, fourth or last day of the month
                                 }
                                 break;
                             case 'next':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                             case 'previous':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                             case 'first':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                             case 'last':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                         }
                         break;
                     case 'year':
                         $query .= " " . $this->custom_fields['leave_request_daily_weekly_monthly_annually']['column_name'] . " = 'annually'";
                         $query .= ", " . $this->custom_fields['leave_request_annually_each']['column_name'] . " = '" . $dao->{$old_fields['leave_request_each']['column_name']} . "'";
                         switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                             case 'nvt':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                             case 'next':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                             case 'previous':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                             case 'first':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                             case 'last':
                                 switch ($dao->{$old_fields['leave_request_on']['column_name']}) {
                                     case 'nvt':
                                         break;
                                     default:
                                 }
                                 break;
                         }
                         break;
                 }
                 break;
         }
         $query .= " WHERE id = '" . $dao->id . "' ";
         CRM_Core_DAO::executeQuery($query);
     }
     return TRUE;
 }
/**
 * Implementation of hook_civicrm_install
 * 
 * Add contact sub types, relationship types, 
 * custom groups, custom fields and option groups
 */
function leaveregistration_civicrm_install()
{
    $lr = new leaveregistration('civicrm', 'leaveregistration_civicrm_install');
    // create contact_sub_types
    $contact_sub_types = $lr->__get('contact_sub_types');
    foreach ($contact_sub_types as $contact_sub_type => $array) {
        $params = array('version' => 3, 'sequential' => 1, 'parent_id' => $array['parent_id'], 'name' => $array['contact_sub_type'], 'label' => $array['contact_sub_type']);
        $result = civicrm_api('ContactType', 'get', array('version' => 3, 'sequential' => 1, 'name' => $contact_sub_type));
        if (empty($result['values'])) {
            $result = civicrm_api('ContactType', 'create', $params);
            if (!$result) {
                CRM_Core_Session::setStatus(ts('An error occurred when creating the contact type ') . $contact_sub_type . ts(' !'), ts('Creating contact type'), 'error');
            } else {
                //CRM_Core_Session::setStatus( ts('Contact type employee created !'), ts('Creating contact type'), 'success');
            }
        }
    }
    // create relationship_types
    $relationship_types = $lr->__get('relationship_types');
    foreach ($relationship_types as $relationship_type => $array) {
        $params = array('version' => 3, 'sequential' => 1, 'name_a_b' => $array['name_a_b'], 'label_a_b' => $array['name_a_b'], 'name_b_a' => $array['name_a_b'], 'label_b_a' => $array['name_a_b'], 'description' => $array['description'] . ' relationship.', 'contact_type_a' => $array['contact_type_a'], 'contact_type_b' => $array['contact_type_b'], 'contact_sub_type_a' => $array['contact_sub_type_a'], 'contact_sub_type_b' => $array['contact_sub_type_b'], 'is_active' => '1');
        $result = civicrm_api('RelationshipType', 'get', array('version' => 3, 'sequential' => 1, 'name_a_b' => $array['name_a_b']));
        if (empty($result['values'])) {
            $result = civicrm_api('RelationshipType', 'create', $params);
            if (!$result) {
                CRM_Core_Session::setStatus(ts('An error occurred when creating the relationship ') . $array['name_a_b'] . ts(' of !'), ts('Creating relationship'), 'error');
            } else {
                //CRM_Core_Session::setStatus( ts('Relationship ') . $array['name_a_b'] . ts(' created !'), ts('Creating relationship'), 'success');
            }
        }
    }
    // activity type
    $params = array('version' => 3, 'sequential' => 1, 'name' => 'Leave__Request', 'label' => 'Leave - Request', 'title' => 'Leave - Request', 'is_active' => '1', 'weight' => 3);
    $activity = civicrm_api('OptionValue', 'get', array('version' => 3, 'sequential' => 1, 'title' => 'Leave - Request', 'label' => 'Leave - Request'));
    // if don`t exists
    if (empty($activity['values'])) {
        $activity = civicrm_api('ActivityType', 'create', $params);
        if (!$activity) {
            CRM_Core_Session::setStatus(ts('An error occurred when creating the activity type Leave - Request !'), ts('Creating activity type'), 'error');
        } else {
            //CRM_Core_Session::setStatus( ts('Activity type Leave - Request created !'), ts('Creating activity type'), 'success');
        }
    }
    // custom groups
    /*$custom_groups = $lr->__get('custom_groups');
         
      foreach($custom_groups as $custom_group => $array){   
        // first create group with title as name
        $fgparams = array(
          'version' => 3,
          'sequential' => 1,
          'name' => $array['name'],
          'title' => $array['name'],
          'extends' => $array['extends'],
          'extends_entity_column_value' => $array['extends_entity_column_value'],
          'style' => $array['style'],
          'collapse_display' => '1',
          'is_active' => '1',
          'weight' => '1',
          'is_multiple' => $array['is_multiple']
        );
        
        // second update field with title as title
        $sgparams = array(
          'version' => 3,
          'sequential' => 1,
          'title' => $array['title'],
          'extends' => $array['extends'],
          'extends_entity_column_value' => $array['extends_entity_column_value'],
          'style' => $array['style'],
          'collapse_display' => '1',
          'is_active' => '1',
          'weight' => '1',
          'is_multiple' => $array['is_multiple']
        );
        
        if('leave_request' == $custom_group){
          $fgparams['extends_entity_column_value'] = '' . $activity['values'][0]['value'] . '';
          $sgparams['extends_entity_column_value'] = '' . $activity['values'][0]['value'] . '';
        }
        
        $cgroup = civicrm_api('CustomGroup', 'get', array('version' => 3,'sequential' => 1,'title' => $array['title']));
    
        // if don`t exists
        if(empty($cgroup['values'])){
          // first create group with name as title
          $cgroup = civicrm_api('CustomGroup', 'create', $fgparams);
          
          // second update group with title as title
          $sgparams['id'] = $cgroup['values'][0]['id'];
          $cgroup = civicrm_api('CustomGroup', 'create', $sgparams);
        
          if(!$cgroup){
            CRM_Core_Session::setStatus( ts('An error occurred when creating the custom group ') . $custom_group . ts(' !'), ts('Creating custom group'), 'error');
            return false;
          }else {
            //CRM_Core_Session::setStatus( ts('Custom group ') . $custom_group . ts(' created !'), ts('Creating custom group'), 'success');
          }
        }
        $custom_groups[$custom_group]['id'] = $cgroup['values'][0]['id'];
      }
      
      // option groups
      $option_groups = $lr->__get('option_groups');
      foreach($option_groups as $option_group => $array){
        
        $params = array(
          'version' => 3,
          'sequential' => 1,
          'name' => $array['name'],
          'title' => $array['label'],
          'is_active' => '1',
        );
    
        $ogroup = civicrm_api('OptionGroup', 'get', array('version' => 3, 'sequential' => 1, 'name' => $array['name']));
        
        if(empty($ogroup['values'])){
          // create option group
          $ogroup = civicrm_api('OptionGroup', 'create', $params);
          
          if(!$ogroup){
            CRM_Core_Session::setStatus( ts('An error occurred when creating the option group ') . $array['name'] . ts(' !'), ts('Creating option group'), 'error');
            return false;
          }else {
            //CRM_Core_Session::setStatus( ts('Option group ') . $array['name'] . ts(' created !'), ts('Creating option group'), 'success');
          }
        }
        $option_groups[$option_group]['id'] = $ogroup['values'][0]['id'];
      }
        
      // custom fields
      $cfweight = 1;
      $cfcur = '';
      $custom_fields = $lr->__get('custom_fields');
      foreach($custom_fields as $custom_field => $array){
        
        if($cfcur != $custom_groups[$array['custom_group_name']]['id']){
          $cfweight = 1;
        }
        
        $cfcur = $custom_groups[$array['custom_group_name']]['id'];
        
        // first create field with name as label
        $ffparams = array(
          'version' => 3,
          'sequential' => 1,
          'custom_group_id' => $custom_groups[$array['custom_group_name']]['id'],
          'name' => $array['name'],
          'label' => $array['name'],
          'data_type' => $array['data_type'],
          'html_type' => $array['html_type'],
          'default_value' => $array['default_value'],
          'is_required' => $array['is_required'],
          'is_searchable' => '1',
          'weight' => $cfweight,
          'is_active' => '1',
          'text_length' => '255',
          'date_format' => 'Null',
          'option_group_id' => 'Null',
        );
        
        // second update field with label as label
        $sfparams = array(
          'version' => 3,
          'sequential' => 1,
          'custom_group_id' => $custom_groups[$array['custom_group_name']]['id'],
          'name' => $array['name'],
          'label' => $array['label'],
          'data_type' => $array['data_type'],
          'html_type' => $array['html_type'],
          'is_required' => $array['is_required'],
          'is_searchable' => '1',
          'weight' => $cfweight,
          'is_active' => '1',
        );
        
        if(isset($array['help_pre']) and '' != $array['help_pre']){
          $ffparams['help_pre'] = $array['help_pre'];
          $sfparams['help_pre'] = $array['help_pre'];
        }
    
        if(isset($array['help_post']) and '' != $array['help_post']){
          $ffparams['help_post'] = $array['help_post'];
          $sfparams['help_post'] = $array['help_post'];
        }
    
        if('Select Date' == $array['html_type']){
          $ffparams['date_format'] = $array['date_format'];
          $ffparams['time_format'] = $array['time_format'];
    
          $sfparams['date_format'] = $array['date_format'];
          $sfparams['time_format'] = $array['time_format']; 
        }
        
        if('Select' == $array['html_type'] or 'Multi-Select' == $array['html_type'] or 'CheckBox' == $array['html_type']){
          // custom field
          $ffparams['option_group_id'] = $option_groups[$array['option_group_name']]['id'];
          $sfparams['option_group_id'] = $option_groups[$array['option_group_name']]['id'];
          
        }else {
          $ffparams['option_group_id'] = NULL;
          $sfparams['option_group_id'] = NULL;
        }
          
        if('Select Date' == $array['html_type']){
          $fparams['date_format'] = 'dd-mm-yy';
          
        }else {
          $fparams['date_format'] = NULL;
        }
        
        // custom field
        $cfield = civicrm_api('CustomField', 'get', array('version' => 3, 'sequential' => 1, 'name' => $array['name'], 'custom_group_id' => $custom_groups[$array['custom_group_name']]['id']));
        
        if(empty($cfield['values'])){
          // first create field with name as label
          $cfield = civicrm_api('CustomField', 'create', $ffparams);
          
          // second update field with label as label
          $sfparams['id'] = $cfield['values'][0]['id'];
          $cfield = civicrm_api('CustomField', 'create', $sfparams);
        
          if(!$cfield){
            CRM_Core_Session::setStatus( ts('An error occurred when creating the custom field ') . $array['name'] . ts(' !'), ts('Creating custom field'), 'error');
            return false;
          }else {
            //CRM_Core_Session::setStatus( ts('Custom field ') . $array['name'] . ts(' created !'), ts('Creating custom field'), 'success');
          }
        }else {
          // update weight, is_required, is_searchable and is_active
          $cfield = civicrm_api('CustomField', 'create', array('version' => 3, 'sequential' => 1, 'id' => $cfield['values'][0]['id'], 'weight' => $cfweight, 'is_required' => $array['is_required'], 'is_searchable' => '1', 'is_active' => '1'));
        }
        
        $cfweight++;
        
        $custom_fields[$custom_field]['id'] = $cfield['values'][0]['id'];
      }
        
      // option values
      $option_values = $lr->__get('option_values');
      foreach($option_values as $option_value => $array){
        
        $ovweight = 1;
        foreach($array['options'] as $value => $name){
          $params = array(
            'version' => 3,
            'sequential' => 1,
            'option_group_id' => $option_groups[$option_value]['id'],
            'value' => $value,
            'name' => $name,
            'weight' => $ovweight,
            'is_active' => '1'
          );
    
          $result = civicrm_api('OptionValue', 'get', array('version' => 3, 'sequential' => 1, 'value' => $value, 'name' => $name, 'option_group_id' => $option_groups[$option_value]['id']));
          
          $ovweight++;
    
          if(empty($result['values'])){
            $result = civicrm_api('OptionValue', 'create', $params);
    
            if(!$result){
              CRM_Core_Session::setStatus( ts('An error occurred when creating the option value ') . $name . ts(' !'), ts('Creating option value'), 'error');
              return false;
            }else {
              //CRM_Core_Session::setStatus( ts('Option value ') . $name . ts(' created !'), ts('Creating option value'), 'success');
            }
          }
        }
      }*/
    return TRUE;
}
 public function get_calendar_month()
 {
     $error = '';
     // cid
     if (!isset($this->data['cid']) or empty($this->data['cid'])) {
         $error = ts('Error in get_calendar_month, no cid !');
     }
     // user_cid
     if (!isset($this->data['user_cid']) or empty($this->data['user_cid'])) {
         $error = ts('Error in get_calendar_month, no user_cid !');
     }
     // year
     if (!isset($this->data['year']) or empty($this->data['year'])) {
         $error = ts('Error in get_calendar_month, no year !');
     }
     // month
     if (!isset($this->data['month']) or empty($this->data['month'])) {
         $error = ts('Error in get_calendar_month, no month !');
     }
     // user_id
     if (!isset($this->data['user_id']) or empty($this->data['user_id'])) {
         $error = ts('Error in get_calendar_month, no user_id !');
     }
     if (!empty($error)) {
         $form = array('type' => 'error', 'error' => $error);
         if ('form' == $this->data['type']) {
             return $form;
         } else {
             return $this->response('calendar_month', $form, 'error', '');
         }
     }
     $header = array();
     $header[] = array('data' => ts(date('F', strtotime($this->data['year'] . '-' . $this->data['month'] . '-01'))));
     foreach ($this->lr->data[$this->data['cid']][$this->data['year']][$this->data['month']] as $day => $array) {
         $header[] = array('data' => $day);
     }
     unset($day);
     unset($array);
     // employee self
     $datas = array();
     $class = '';
     $rel = array();
     $datas[] = array('data' => $this->lr->employees[$this->data['cid']]['display_name']);
     foreach ($this->lr->data[$this->data['cid']][$this->data['year']][$this->data['month']] as $day => $array) {
         $class = '';
         $rel = '';
         list($data, $class, $rel) = $this->get_calendar_month_day($this->lr->employees, $this->data['cid'], $this->data['user_cid'], $this->data['user_id'], $day, $this->data['month'], $this->data['year'], $array);
         $datas[] = array('data' => $data, 'class' => $class, 'rel' => rawurlencode(serialize($rel)));
     }
     unset($day);
     unset($array);
     unset($data);
     unset($class);
     unset($rel);
     $rows[] = array('data' => $datas);
     unset($datas);
     // all the colleages
     $colleages = array();
     switch ($this->lr->settings[$this->data['cid']]['show_all_colleagues']) {
         case 'business':
             foreach ($this->lr->business_colleages_ids[$this->data['cid']] as $bid => $business) {
                 foreach ($business['employees'] as $cid => $employee) {
                     if ($cid != $this->data['cid']) {
                         $colleages[htmlentities($employee['display_name'])] = $employee;
                     }
                 }
             }
             unset($bid);
             unset($business);
             unset($cid);
             unset($employee);
             break;
             /*case 'main_business':
               foreach($this->lr->department_heads_colleages_ids[$this->data['user_cid']] as $did => $department){
                 foreach($department['employees'] as $cid => $employee){
                   if($cid != $this->data['user_cid']){
                     $colleages[htmlentities($employee['display_name'])] = $employee;
                   }
                 }
               }
               break;*/
         /*case 'main_business':
           foreach($this->lr->department_heads_colleages_ids[$this->data['user_cid']] as $did => $department){
             foreach($department['employees'] as $cid => $employee){
               if($cid != $this->data['user_cid']){
                 $colleages[htmlentities($employee['display_name'])] = $employee;
               }
             }
           }
           break;*/
         default:
             foreach ($this->lr->department_colleages_ids[$this->data['cid']] as $did => $department) {
                 foreach ($department['employees'] as $cid => $employee) {
                     if ($cid != $this->data['cid']) {
                         $colleages[htmlentities($employee['display_name'])] = $employee;
                     }
                 }
             }
             unset($did);
             unset($department);
             unset($cid);
             unset($employee);
     }
     // all the department heads
     if ($this->lr->settings[$this->data['cid']]['show_department_head']) {
         foreach ($this->lr->department_heads[$this->data['cid']] as $dhid => $department_head) {
             if ($dhid != $this->data['cid']) {
                 $colleages[htmlentities($department_head['display_name'])] = $department_head;
             }
         }
         unset($dhid);
         unset($department_head);
     }
     $colids = array();
     ksort($colleages);
     foreach ($colleages as $display_name => $employee) {
         $colids[] = $employee['id'];
     }
     unset($colleages);
     unset($display_name);
     unset($employee);
     if (!empty($colids)) {
         $lrcol = new leaveregistration($this->data['error_platform'], $this->data['error_id'] . ': get_calendar_month');
         $lrcol->set_fields();
         $lrcol->set_contacts($colids);
         $lrcol->set_data($this->data['years'], $this->data['months']);
     }
     foreach ($colids as $collid) {
         $datas = array();
         $class = '';
         $rel = array();
         $datas[] = array('data' => $lrcol->employees[$collid]['display_name']);
         foreach ($lrcol->data[$collid][$this->data['year']][$this->data['month']] as $day => $array) {
             list($data, $class, $rel) = $this->get_calendar_month_day($lrcol->employees, $collid, $this->data['user_cid'], $this->data['user_id'], $day, $this->data['month'], $this->data['year'], $array);
             $datas[] = array('data' => $data, 'class' => $class, 'rel' => rawurlencode(serialize($rel)));
         }
         unset($day);
         unset($array);
         unset($data);
         unset($class);
         unset($rel);
         $rows[] = array('data' => $datas);
     }
     unset($datas);
     $form = array('type' => 'table', 'header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'calendar_months_' . $month, 'class' => 'calendar_months'), 'caption' => '', 'colgroups' => array(), 'sticky' => false, 'empty' => '');
     unset($header);
     unset($rows);
     unset($month);
     if ('form' == $this->data['type']) {
         return $form;
     } else {
         return $this->response('calendar_month', $form, 'table', 'mouseover');
     }
 }