<?php
/**
 * Clubdata List Modules
 *
 * Contains classes to generate and display serveral lists
 *
 * @package List
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 * @author Franz Domes <franz.domes@gmx.de>
 * @version $Revision: 1.4 $
 * @version 2.0
 * @copyright Copyright (c) 2009, Franz Domes
 */

/**
 *
 */
if (defined('MEMBERLIST_CLASS')) {
    return 0;
} else {
    define('MEMBERLIST_CLASS', TRUE);
}

require_once('include/membertype_dep.php');
require_once('include/dblist.class.php');
require_once('include/addresses.class.php');
require_once('include/createPDF.class.php');
require_once('include/search.class.php');

/**
 * This class generates memberlist for various purposes
 *
 * @author Franz Domes <franz.domes@gmx.de>
 * @version $Revision: 1.3 $
 * @package List
 */
class vMemberlist
{
    /** @var string name of command type to display*/
    var $command;

    /** @var object current list object*/
    var $mlist;

    var $db;

    /** @var integer set to 1 if new view has to be initialized*/
    var $initView;

    /** @var string holds SQL statement as generated by setSqlAndColumns()*/
    var $sql;

    /** @var strings holds columns to show, as generated by setSqlAndColumns()*/
    var $cols;

    /**
     * @var object
     */
    var $smarty;

    /**
     * @var object
     */
    var $formsgeneration;

    /**
    * Constructor of class List
    * @return integer Always OK
    */
    function vMemberlist($db, $command, $initView, &$smarty, &$formsgeneration)
    {
        $this->db = $db;
        $this->command = $command;
        $this->initView = $initView;
        $this->smarty = &$smarty;
        $this->formsgeneration = &$formsgeneration;

        $quicksearch = getGlobVar('quicksearch');
        if ( !empty($quicksearch) )
        {
            // Force initView if quicksearch is set !!
            $this->initView = 1;
        }

        $this->pageNr = getGlobVar('PageNr','::number::');
        if (empty($this->pageNr) )
        {
            $this->pageNr = 1;
        }

        $cols = getGlobVar('DisplayCols');
        if ( empty($cols) )
        {
            $cols = getConfigEntry($this->db, 'DefaultCols');
        }


        // Make sure, the first column is MemberID.
        // Use array_unique to eliminate other MemberIDs.
        // Join afterwards to have comma-delimited list of columns
        if ( is_array($cols) )
        {
            $cols = join(',', array_unique(array_merge(array('`###_Members`.MemberID'),array_keys($cols))));
        }
        else
        {
        	$tmpArr = preg_split("/[\s,]+/",$cols);
            $cols = join(',', array_unique(array_merge(array('`###_Members`.MemberID'),preg_split("/[\s,]+/",$cols))));
        }
//           echo "COLS: $cols<BR>";
        $this->cols = $this->setColumnAlias($cols);
//         echo "COLS: $this->cols<BR>";

        // Set up SQL, cols
        $this->sql = $this->generateSql();
        if ( $this->initView != 1 )
        {
            $this->mlist = new DbList($this->db, 'memberlist');
        }
        else
        {
            if ( !empty($quicksearch) )
            {
                $cond = "`Addresses_1`.Lastname LIKE '%$quicksearch%' OR Addresses_1.Firstname LIKE '%$quicksearch%' OR Addresses_2.FirmName_ml LIKE '%$quicksearch%'";
            }
            else
            {
                $searchObj = new Search($this->db, $this->formsgeneration, 'Advanced', 'Search');
                $cond = $searchObj->generateSelectCMD();
            }
            $this->mlist = new DbList($this->db, 'memberlist',
                              array('changeFlg' => FALSE,
                                    'sql' => $this->sql,
                                    'cols' => $this->cols,
                                    'cond' => $cond,
                                    'selectRowsFlg' => true,
                                    // geändert 20090822, ohne ###_ bei MemberID wegen Member Search
                                    'idFieldName' => clubdata_mysqli::replaceDBprefix('MemberID', DB_TABLEPREFIX),
                                    'selectedRows' => (getConfigEntry($this->db, 'CheckedCheckboxes') ? 'ALL' : 'NONE'),
                                    'listLinks' => array ( 'Detail' => INDEX_PHP . '?mod=members&view=Overview'),
                                    'linkParams' => "&Command={$this->command}&mod=list&view=Memberlist"
                                    ));
            debug_r('M_LIST', $this->mlist, "[vMemberlist, vMemberlist] MLIST (COND: $cond)");

            if ( getGlobVar('resetList','[01]','PG') == 1 )
            {
                $this->mlist->resetAll();
            }

            // Jump directly to detailed member info, if command is search and
            // the list contains only one member
            if ((empty($command) || $command == 'Search') &&
                $this->mlist->recordCount() == 1 )
            {
                $this->mlist->setConfig('cols',"`###_Members`.MemberID AS MemberID");    // We need just the member ID, so reset list to just this column
                $sql = $this->mlist->prepareSQL();

                $rs = $this->db->Execute($sql);
                if ( $rs === false )
                {
                    $APerr->setFatal(__FILE__,__LINE__,$this->db->errormsg(),"SQL: $sql");
                }
                else
                {
//                     $memberID = $rs->fields['`###_Members%MemberID`'];
                    $memberID = $rs->fields['MemberID'];
                    echo '<SCRIPT LANGUAGE="JavaScript">';
                    echo "location = (\"" . INDEX_PHP . "?mod=members&view=Overview&MemberID=$memberID\");";
                    echo '</SCRIPT>';
                }
            }
        }
   		$tmpSort = getGlobVar('sort', '^[\#\`_A-Za-z0-9\.]*$');

  		if ( !empty($tmpSort) )
	    {
  		  $this->mlist->setConfig('sort', $tmpSort);
		}
        elseif ( $this->mlist->getConfig('sort') == '' )
        {
            $this->mlist->setConfig('sort', '`###_Members`.`MemberID`');
        }

    }

    function getSmartyTemplate()
    {
        return 'list/v_Memberlist.inc.tpl';
    }

    function setSmartyValues()
    {
        $this->mlist->prepareRecordList($this->pageNr);
//         debug_r('SMARTY', $this->mlist, "[V_Memberlist, setSmartyValues]: mlist");
        $this->smarty->assign_by_ref('MemberList', $this->mlist);
    }

    /**
    * generates SQL command
    * All addresses are added dynamically.
    * @return boolean true : save ok, false: error
    */
    function generateSql()
    {

        $adrObj = new Addresses($this->db, $this->formsgeneration);

        $from = $adrObj->generateAdrTableList('`###_Members` LEFT JOIN `###_Members_Attributes` ON `###_Members`.MemberID = `###_Members_Attributes`.MemberID',
                                              '`###_Members`.`MemberID`');

        $sql = "SELECT DISTINCT * FROM $from";
        debug('M_LIST', "[vMemberlist, generateSql] MLIST (SQL: $sql)");
        return $sql;
    }

    /**
    * generates appropriate columns aliases for address columns
    * Address_{addresstype_id}.{fieldname} will be converted to
    *   Address_{addresstype_id}.{fieldname} as {addresstype_description}_{fieldname}
    * @return string new columns definition
    */
    function setColumnAlias($cols)
    {
//         echo "COLS: $cols<BR>";
        $adrObj = new Addresses($this->db, $this->formsgeneration);
        $addresstypes = $adrObj->getAddresstypes();

        for ( $i=0; $i < count($addresstypes) ; $i++ )
        {
            $adrID = $addresstypes[$i]['id'];
            $adrInfo[$adrID]['id'] = $adrID;
            $adrInfo[$adrID]['description'] = getDescriptionTxt($addresstypes[$i]);
        }

        $cols1 = preg_replace(array('/Addresses_([0-9]+)\.([^ ,]+)/e',              // process lines starting with Addresses_
                                    '/([, ]*)((?<!Addresses_)[^.`]+)\.([^ ,]+)/e'), // do not process columns which starts by 'Addresses_' anymore
                              array("\"`Addresses_\$1`.`\$2` AS `\" . lang(\$adrInfo[\\1]['description']) . '_' . lang('\$2') . '`'",
                                    "\"$1`$2`.`$3` AS `$2%$3`\""),
                             $cols);

//         echo "COLS1: $cols1<BR>";
        return $cols1;
    }

    /**
    * saves values passed via POST
    * @return boolean true : save ok, false: error
    */
    function doAction($action)
    {

        switch ( $action )
        {
            case 'SETCHECKED':
                $id = getGlobVar('id', '::number::');
                $newState = getGlobVar('newState', 'false|true');

                $this->mlist->setSelectedRows($id, ($newState == 'false' ? 0 : 1));

			      // Exit if ajax call is used
		          if ( getGlobVar('byAjax', 'true|false') == true )
		          {
			      	exit;
		          }
                break;

            case 'SELECTALL':
                $this->mlist->setAllSelectedRows(1);
                break;

            case 'DESELECTALL':
                $this->mlist->setAllSelectedRows(0);
                break;

            case 'EXCEL':
                $this->mlist->exportExcel();
                break;

            case 'PDF':
                $pdf = new createPDF($this->db, $formsgeneration, true);
                $pdf->createPDFbyMlist($this->mlist);
                break;

//             case 'INFOLETTER':
//                 include('modules/list/exportInfoLetter.php');
//                 break;

            case 'INVOICE':
                $this->mlist->exportExcel();
                break;
        }
        return true;
    }

}
