<?php

require_once 'classes/ImportPlugin.php';

/**
* @package Plugins
*/
class PluginClients_csv extends ImportPlugin
{
    var $name = /*T*/'Simple Importer of Customer Personal Data From a .csv File'/*/T*/;

    var $userGateway;
    var $customFields;

    function getForm()
    {
        $this->tpl->define(array('PluginClientdata' => '../../plugins/import/clients_csv/PluginClientcsv.tpl'));

        $this->getCustomFields();
        foreach($this->customFields AS $t_id => $t_values){
            $this->tpl->assign("NAME", $this->user->varLang($t_values['name']));
            $this->tpl->assign("IMPUTNAME", "CT_$t_id");
            $this->tpl->assign("IMPUTREQUIRED", "CTR_$t_id");
            if($t_values['isRequired']){
                $this->tpl->assign("CHECKED", 'checked');
            }else{
                $this->tpl->assign("CHECKED", '');
            }
            $this->tpl->parse('customFields_out', '.customFields');
        }
        return $this->tpl->subst('PluginClientdata_out', 'PluginClientdata');
    }

    function process($post)
    {
        require_once 'newedge/classes/NE_Upload.php';
        require_once 'classes/UserGateway.php';

        $this->userGateway = new UserGateway();

        if (@$_FILES['file']['name'] == '') {
            NE_Lib::redirectPage('index.php?fuse=admin&view=ViewImportPlugins', $this->user->lang('You didn\'t upload any files'));
        }

        $filename = $_FILES['file']['name'];
        $file = new NE_Upload('file');

        if (!$file->isValid()) {
            NE_Lib::redirectPage('index.php?fuse=admin&view=ViewImportPlugins', $this->user->lang("File %s upload failed", $filename).". ".$this->user->lang("Please ensure that the file is not empty and try uploading again"));
        }

        $fp = fopen($_FILES['file']['tmp_name'], 'r');
        $firstLine = true;
        while(!feof($fp)) {
            $line = fgetcsv($fp, 4096, $_POST['fieldDelimiter'], $_POST['fieldEnclosure']);
            if (!$line || $firstLine && isset($_POST['skipFirstRow'])) {
                $firstLine = false;
                continue;
            }
            $line[-1] = '';
            
            if (!$this->_createUser($line)) {
                NE_Lib::addMessage($this->user->lang('User %s couldn\'t be added because you have reached your user number limit', "{$line[0]} {$lastName[1]}"));
                break;
            }
        }
        fclose($fp);

        NE_Lib::redirectPage('index.php?fuse=admin&view=ViewImportPlugins');

    }

    function _createUser($line)
    {
        $missed_fields = array();
        $firstName = '';
        $lastName = '';
        $email = '';
        $organization = '';
        
        $this->getCustomFields();

        foreach($this->customFields AS $t_id => $t_values){
            switch($t_values['name']){
                case 'First Name':
                    $firstName = $line[$_POST["CT_$t_id"]-1];
                    break;
                case 'Last Name':
                    $lastName = $line[$_POST["CT_$t_id"]-1];
                    break;
                case 'Email':
                    $email = $line[$_POST["CT_$t_id"]-1];
                    break;
                case 'Organization':
                    $organization = $line[$_POST["CT_$t_id"]-1];
                    break;
            }

            if(isset($_POST["CTR_$t_id"]) && ($line[$_POST["CT_$t_id"]-1] == '')){
                $missed_fields[] = $t_values['name'];
            }
        }
        
        if(count($missed_fields)){
            $missed_fields_list = implode(', ', $missed_fields);
            NE_Lib::addMessage($this->user->lang('User %s couldn\'t be added because he has no these required fields: %s ', "$firstName $lastName", $missed_fields_list));
            return true;
        }

        if ($this->userGateway->checkEmailDuplicate($email)) {
            NE_Lib::addMessage($this->user->lang('User %s couldn\'t be added because there is already a customer with that E-mail', "$firstName $lastName"));
            return true;
        }

        $user = new User();
        $user->setDirty(true);
        if (!$user->add()) {
            return false;
        }
        $user->setFirstName($firstName);
        $user->setLastName($lastName);
        $user->setDateCreated(date('Y-m-d'));
        $user->setEmail($email);

        foreach($this->customFields AS $t_id => $t_values){
            $user->setCustomFieldById($t_id, $line[$_POST["CT_$t_id"]-1]);
        }

        NE_Lib::addMessage($this->user->lang('User %s was successfully added', "$firstName $lastName"));
    
        $user->activate();
        $user->save();

        return true;
    }
    
    function getCustomFields(){
        if(!isset($this->customFields)){
            $query = "SELECT id, name, isRequired FROM customuserfields WHERE showCustomer=1 ORDER BY myOrder";
            $result = $this->db->query($query);
            while (list($tID,$tName,$tisRequired) = $result->fetch()) {
                $this->customFields[$tID] = array('name'       => $tName,
                                                  'isRequired' => $tisRequired);
            }
        }
    }
}
?>