<?php

require_once 'classes/ExportPlugin.php';

/**
* @package Plugins
*/
class PluginClientdata extends ExportPlugin
{
    var $name = /*T*/'Export Client Data'/*/T*/;

    function getForm()
    {
        $this->tpl->define(array('PluginClientdata' => 'views/admin/PluginClientdata.tpl'));

        $fields = $this->_getCustomersFields();
        for ($i = 0; $i < count($fields); $i++) {
            $this->tpl->setkey('inputname', str_replace(array(' ', '_'), array('_', '__'), $fields[$i]));
            $this->tpl->setkey('fieldname', $this->user->varLang($fields[$i]));
            if (in_array($fields[$i], array('id', 'First Name', 'Last Name', 'Email', 'Phone'))) {
                $this->tpl->setkey('checked', 'checked');
            } else {
                $this->tpl->setkey('checked', '');
            }
            $this->tpl->parse('trash', '.clients_field');
            if (!(($i+1) % 3)) {
                $this->tpl->parse('trash', '.clients_fields_column');
                $this->tpl->clear_dynamic('clients_field');
            }
        }
        // print last unfilled column
        if (((--$i+1) % 3)) {
            $this->tpl->parse('trash', '.clients_fields_column');
            $this->tpl->clear_dynamic('clients_field');
        }

        return $this->tpl->subst('PluginClientdata_out', 'PluginClientdata');
    }

    function _getCustomersFields()
    {
        $query = "SELECT name FROM customuserfields WHERE inSignup = 1 OR inSettings = 1";
        $result = $this->db->query($query);
        $arrReturn = array('id', 'Status', 'Date Created');
        while ($row = $result->fetch()) {
            $arrReturn[] = $row['name'];
        }

        return $arrReturn;
    }

    function process($post)
    {
        $fields = array();
        foreach ($post as $fieldname => $value) {
            if (strpos($fieldname, 'clients_field_') === 0) {
                $fields[] = str_replace(array('__', '_'), array('_', ' '), substr($fieldname, 14));
            }
        }
        if (!$fields) {
            NE_Lib::redirectPage("index.php?fuse=reports&view=ViewExport");
        }
        $csv = $this->_getCustomersCSV($fields);
        NE_Lib::download($csv, $this->user->lang("customers").'.csv');
    }

    function _getCustomersCSV($fields)
    {
        $numFields = count($fields);
        $fieldsFiltered = array();
        $fieldstranslated = "";
        $numOfTheField = 1;
        foreach ($fields as $field) {
            $fieldsFiltered[] = $this->db->escape_string($field);
            if ($numOfTheField == $numFields) {
                $fieldstranslated .= '"'.$this->user->varLang($field).'"';
            } else {
        	$fieldstranslated .= '"'.$this->user->varLang($field).'",';
            }
            $numOfTheField ++;
        }
        $fields_str = implode("', '", $fieldsFiltered);
        $csv = $fieldstranslated. "\n";
        $users = array();
        $query = "SELECT u.id, u.status, u.dateActivated, cu.name, u_cu.value FROM users u, user_customuserfields u_cu, customuserfields cu "
                ."WHERE u.groupid = 1 AND u.id = u_cu.userid AND u_cu.customid = cu.id AND cu.name IN('$fields_str')";
        $result = $this->db->query($query);

        // special cases
        $showId = in_array('id', $fields);
        $showStatus = in_array('Status', $fields);
        $showDateCreated = in_array('Date Created', $fields);

        while ($row = $result->fetch()) {
            if ($showId) {
                $users[$row['id']]['id'] = $row['id'];
            }
            if ($showStatus) {
                switch ($row['status']) {
                    case 1:
                        $status = $this->user->lang('Active');
                        break;
                    case 0:
                        $status = $this->user->lang('Pending');
                        break;
                    case -1:
                        $status = $this->user->lang('Inactive');
                        break;
                    case -2:
                        $status = $this->user->lang('Cancelled');
                        break;
                    case -3:
                        $status = $this->user->lang('Fraud');
                        break;
                }
                $users[$row['id']]['Status'] = $status;
            }
            if ($showDateCreated) {
                $users[$row['id']]['Date Created'] = NE_Lib::db_to_form($row['dateActivated'], $this->settings->get('Date Format'), '/');
            }
            $users[$row['id']][$row['name']] = $row['value'];
        }

        foreach ($users as $userItem) {
            for ($i = 0; $i < $numFields; $i++) {
                // I tried more elegant ways, but this one assures field order :-P
                $csv .= "\"";
                if(isset($fields[$i])) {
                    if(isset($userItem[$fields[$i]])) {
                    	$csv .= $userItem[$fields[$i]];
                    }
                }
                $csv .= "\"";
                if ($i == ($numFields - 1)) {
                    $csv .= "\n";
                } else {
                    $csv .= ",";
                }
            }
        }

        return $csv;
    }
}

?>
