<?php

class FrontEndUserListing extends CMSModule
{

    function GetName()
    {
	return 'FrontEndUserListing';
    }

    function GetFriendlyName()
    {
	return $this->Lang('friendlyname');
    }


    function GetVersion()
    {
	return '0.1';
    }

    function GetHelp()
    {
	return $this->Lang('help');
    }

    function GetAuthor()
    {
	return 'Katon';
    }

    function GetAuthorEmail()
    {
	return 'katonchik@gmail.com';
    }

    function GetChangeLog()
    {
	return $this->Lang('changelog');
    }

    function IsPluginModule()
    {
	return true;
    }

    function HasAdmin()
    {
	return true;
    }

    function GetAdminSection()
    {
	return 'usersgroups';
    }


    function GetAdminDescription()
    {
	return $this->Lang('moddescription');
    }


    function VisibleToAdminUser()
    {
	return $this->CheckPermission('Use FrontEndUserListing');
    }

    function GetDependencies()
    {
	return array( 'FrontEndUsers' => '0.1.3' );
    }


    function Install()
    {
	$this->CreatePermission('Use FrontEndUserListing', 'Use FrontEndUserListing');
	$this->SetTemplate('displaysummary', $this->GetSummaryHtmlTemplate());
	$this->Audit( 0, $this->Lang('friendlyname'), $this->Lang('installed',$this->GetVersion()));
    }

    function InstallPostMessage()
    {
	return $this->Lang('postinstall');
    }

    function UninstallPostMessage()
    {
	return $this->Lang('postuninstall');
    }


    function Uninstall()
    {
	$this->RemovePermission('Use FrontEndUserListing');
	$this->Audit( 0, $this->Lang('friendlyname'), $this->Lang('uninstalled'));
    }


    function DoAction($action, $id, $params, $return_id=-1)
    {
	switch ($action)
	{
	    case 'default':
	    {
		$this->DisplayUsersInGroup( $id, $params, $returnid );
		break;
	    }
	    case 'defaultadmin':
	    {
		// only let people access module preferences if they have permission
		if ($this->CheckPermission('Use FrontEndUserListing'))
		{
		    $this->DisplayAdminPanel($id, $params, $return_id);
		} else {
		    $this->DisplayErrorPage($id, $params, $return_id,
			    $this->Lang('accessdenied'));
		}
		break;
	    }
	    case "updatesummarytemplate":
		$this->SetTemplate('displaysummary', $params['templatecontent']);
		$this->Redirect($id, 'defaultadmin');
		break;
	}
    }



    /*---------------------------------------------------------
    DisplayUsersInGroup($id, $params, $return_id, $message)
    NOT PART OF THE MODULE API
    ---------------------------------------------------------*/
    function DisplayUsersInGroup( $id, &$params, $returnid )
    {

	$feusers = $this->GetModuleInstance('FrontEndUsers');
	if( !$feusers )
	{
	    // this is ugly for the user to see
	    // but at least the admin will be able to figure it out
	    $this->_DisplayErrorPage( $id, $params, $returnid,
				      $this->Lang('error_nofeusersmodule'));
	    return;
	}

	$cmsmailer = $this->GetModuleInstance('CMSMailer');
	if( !$cmsmailer )
	{
	    // this is ugly for the user to see
	    // but at least the admin will be able to figure it out
	    $this->_DisplayErrorPage( $id, $params, $returnid,
				      $this->Lang('error_nofeusersmodule'));
	    return;
	}

	// yep, all the modules are here, now we
	// have to convert the groupname into an id
	$grpid = $feusers->GetGroupID($params['group']);
	if( $grpid == false )
	{
	    // this is ugly for the user to see
	    // but at least the admin will be able to figure it out
	    $this->_DisplayErrorPage( $id, $params, $returnid,
				      $this->Lang('error_nosuchgroup'));
	    return;
	}

	// now we have an id... have to get a list of the groups properties
	$relations = $feusers->GetGroupPropertyRelations( $grpid );
	if( $relations[0] == false )
	{
	    // this is ugly for the user to see
	    // but at least the admin will be able to figure it out
	    $this->_DisplayErrorPage( $id, '', $returnid, $relations[1] );
	    return;
	}
	uasort( $relations, 'compare_elements_by_sortorder_key' );

	// now we have the properties, gotta show something to the user
	// dammit.
	if( isset( $params['error'] ) )
	{
	    $this->smarty->assign('error', $params['error']);
	}
	if( isset( $params['message'] ) )
	{
	    $this->smarty->assign('message', $params['message']);
	}

	// now we're ready to populate the template
	// first we put in stuff that is required (username, password, etc, etc)
	$listheader = array();

	foreach( $relations as $reln )
	{
	    // don't process hidden fields here
	    if( $reln['required'] == 3 ) continue;

	    // get the property definition
	    // Is $defn a string or an array?
	    $name = $reln['name'];
	    $defn = $feusers->GetPropertyDefn( $name );
	    $onerow = new StdClass();

	    $listheader[$name] = $defn['prompt'];
	}

	$db = $this->GetDb();
	$entryarray = array();
	$query = "SELECT p.*, b.groupid FROM "
		.cms_db_prefix()."module_feusers_properties p, "
		.cms_db_prefix()."module_feusers_belongs b, "
		.cms_db_prefix()."module_feusers_groups g "
		."WHERE b.userid = p.userid "
		."AND b.groupid = g.id";
	if (isset($grpid)){
	    $query .= " AND g.id=" . $grpid;
	}
	$dbresult=$db->Execute($query);

	//Fixme: the following algorithm is pretty clumsy
	$users = array();
	$userCount = 0;
	$users[$userCount] = array();
	$userid = 0;

	while ($row = $dbresult->FetchRow()){

	    //e.g. users[0]['home_phone']] = 276-2650;
	    $users[$userCount][$row['title']] = $row['data'];

	    if($userid != $row['userid']){ // if new user
		if ($userCount > 0) {
		    $sorteduser = array();
		    $sorteduser = $this->SortAsDefs($users[$userCount], $listheader);
		    array_push($entryarray, $sorteduser);
		}
		$userid = $row['userid'];
		$userCount++;
		$users[$userCount] = array();
	    }
	}
	// add the last element
	$sorteduser = $this->SortAsDefs($users[$userCount], $listheader);
	array_push($entryarray, $sorteduser);

	$this->smarty->assign_by_ref ('listheader', $listheader);
	$this->smarty->assign_by_ref('items', $entryarray);
	echo "<!-- Displaying FEUserListing Module -->\n";
	if (isset($params['summarytemplate']))
	{
	    echo $this->ProcessTemplate($params['summarytemplate']);
	}
	else
	{
	    #$log->debug($this->ProcessTemplateFromDatabase('displaysummary'));
	    echo $this->ProcessTemplateFromDatabase('displaysummary');
	}

    }


    function GetSummaryHtmlTemplate()
    {
	    return '<!-- Start FrontEndUserListing Display Template -->

<!-- To access properties, use dots, not arrows.  E.g.: prop.first_name -->

<table width="100%" border="1">

<tr>

{foreach from=$listheader item=hprop}

<th>{$hprop}</th>

{/foreach}

</tr>

{foreach from=$items item=entry}

<tr>

{foreach from=$entry item=prop}

<td>{$prop}</td>

{/foreach}

</tr>

{/foreach}

</table>
		
<!-- End FrontEndUserListing Display Template -->';
	}
		
		
		
/*		
	function GetSummaryHtmlTemplate()
	{
		return '<!-- Start FrontEndUserListing Display Template -->
<table width="100%" border="1">
{foreach from=$items item=entry}
<tr>
<td>
{$entry.first_name} {$entry.last_name}<br>
<a href="mailto:{$entry.Email}">{$entry.last_name}</a><br>
</td>
<td>
{$entry.home_phone}<br> {$entry.cell_phone}
</td>
<td>
{$entry.icq}
</td>
<td>
{$entry.ip}
</td>
</tr>		
{/foreach}
</table>		
		
<!-- End FrontEndUserListing Display Template -->';		
}
*/
/*		
	function GetSummaryHtmlTemplate()
	{
		return '<!-- Start FrontEndUserListing Display Template -->
<table width="100%" border="1">
{foreach from=$items item=entry}
<tr>
<td>
{$entry.first_name} {$entry.last_name}
</td>
<td>
{$entry.email}
</td>
</tr>		
{/foreach}
</table>		
		
<!-- End FrontEndUserListing Display Template -->';		
}
*/
		
		
		
		
		
		
    function DisplayErrorPage($id, &$params, $returnid, $message='')
    {
	$this->smarty->assign('title_error', $this->Lang('error'));
	if ($message != '')
	{
	    $this->smarty->assign_by_ref('message', $message);
	}

        echo $this->ProcessTemplate('error.tpl');
    }

    function DisplayAdminPanel($id, &$params, $returnid, $message='')
    {
	echo $this->StartTabHeaders();
	echo $this->SetTabHeader('summary_template',$this->Lang('summarytemplate'));
	echo $this->EndTabHeaders();
	echo $this->StartTabContent();
	echo $this->StartTab('summary_template');
	echo $this->CreateFormStart($id, 'updatesummarytemplate');
	echo '<p>'.$this->CreateTextArea(false, $id, $this->GetTemplate('displaysummary'), 'templatecontent', '').'</p>';
	echo $this->CreateInputSubmit($id, 'submitbutton', $this->Lang('submit'));
	echo $this->CreateFormEnd();
	echo $this->EndTab();
	echo $this->EndTabContent();
    }

    /*--------------------------------------------------------
    orig_array contains pairs like 'home_phone' => '276-2650'
    sample_array contains pairs like 'home_phone' => 'Home Phone'
    ----------------------------------------------------------*/

    function SortAsDefs($orig_array, $sample_array)
    {
	$sorted_array = array();
	foreach ($sample_array as $key => $value) {
	    if (isset($orig_array[$key])){
		$sorted_array[$key] = $orig_array[$key];
	    } else {
		$sorted_array[$key] = "&nbsp;";
	    }
	}
	return $sorted_array;
    }


}

?>
