<?php
#BEGIN_LICENSE
#-------------------------------------------------------------------------
# Module: MAMS (c) 2020-2021 by CMS Made Simple Foundation
#  An add-on module for CMS Made Simple to provide useful functions
#  and commonly used gui capabilities to other modules.
#-------------------------------------------------------------------------
# A fork of:
#
# Module: FrontEndUsers (c) 2008-2014 by Robert Campbell
#         (calguy1000@cmsmadesimple.org)
#
#-------------------------------------------------------------------------
#
# CMSMS - CMS Made Simple is (c) 2006 - 2021 by CMS Made Simple Foundation
# CMSMS - CMS Made Simple is (c) 2005 by Ted Kulp (wishy@cmsmadesimple.org)
# Visit the CMSMS Homepage at: http://www.cmsmadesimple.org
#
#-------------------------------------------------------------------------
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# However, as a special exception to the GPL, this software is distributed
# as an addon module to CMS Made Simple.  You may not use this software
# in any Non GPL version of CMS Made simple, or in any version of CMS
# Made simple that does not indicate clearly and obviously in its admin
# section that the site was built with CMS Made simple.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
# Or read it online: http://www.gnu.org/licenses/licenses.html#GPL
#
#-------------------------------------------------------------------------
#END_LICENSE

namespace MAMS;

if(!defined('CMS_VERSION'))
{
  exit;
}
if(!$this->_HasSufficientPermissions('users'))
{
  return;
}

$user_id = $user = NULL;
try
{
  $this->SetCurrentTab('users');
  if(isset($params['cancel']))
  {
    // clear anything in the session, but don't need the data.
    \MAMS\user_edit_assistant::retrieve();
    $this->SetMessage($this->Lang('msg_cancelled'));
    $this->RedirectToTab();
  }
  
  $user = \MAMS\user_edit_assistant::retrieve();
  
  if(!$user)
  {
    throw new \LogicException('Could not restore user edit info from session');
  }
  
  $user_id = $user->id;
  
  if(isset($params['back']))
  {
    $user->store();
    $this->Redirect($id, 'admin_edituser', $returnid, ['user_id' => $user_id]);
  }
  
  $alldefns   = $this->GetPropertyDefns();
  $fields     = [];
  $properties = \mams_utils::get_properties_for_groups($user->get_groups());
  
  # remove empty props... IDK why there are any but do make this puke... need to revisit (JM)
  $properties = \array_filter($properties);
  
  if(!\count($properties))
  {
    // there are no properties to think of.
    // simulate submission.
    $params['submit'] = 1;
  }
  else
  {
    foreach($properties as $prop)
    {
      $prop_name = $prop['name'];
      
      if(!isset($alldefns[$prop_name]))
      {
        throw new \LogicException('Definition for property ' . $prop_name . ' not found');
      }
      //if( $alldefns[$prop_name]['encrypt'] && $user_id > 0 ) continue;  // cannot edit encrypted properties.
      $fields[$prop_name] = new property_editor_defn($alldefns[$prop_name], $prop, $user);
    }
  }
  
  if(isset($params['submit']))
  {
    /* handle submission */
    try
    {
      // note, we use the set value method on the field... it will actually modify the user
      // and set the data.
      foreach($fields as $prop_name => $field)
      {
        $key  = 'prop_' . $prop_name;
        $key2 = 'propdel_' . $prop_name;
        $val  = \xt_utils::get_param($params, $key);
        if($field->type == 8)
        {
          $val = \xt_param::get_separated_date($params, $key);
        }
        else if($field->type == 6)
        {
          // image
          if(isset($params[$key2]))
          {
            $field->clear_value();
          }
          $val = $id . $key;
        }
        $field->set_value($val);
      }
      
      // pass 2 .. validate the input (required fields, upload types and so-on)
      foreach($fields as $prop_name => $field)
      {
        $field->validate();
      }
      
      // pass 2.1 ... ensure that if must_validate is on, that we have an email address
      // for this user.
      if($user->must_validate && !$user->can_validate())
      {
        throw new \RuntimeException($this->Lang('error_validate_insufficientinfo'));
      }
      
      $is_add = ($user->id < 1) ? TRUE : FALSE;
      $user->save();
      
      // pass 3 .. do post processing.
      foreach($fields as $prop_name => $field)
      {
        $field->postprocess($user);
      }
      
      // all done... just gotta do some notifications and events.
      $evt_parms = ['name' => $user->username, 'id' => $user->id];
      
      if($is_add)
      {
        audit('', $this->GetName(), 'Added user ' . $user->username);
        $this->add_history($user->id, 'admin add user');
        \CMSMS\HookManager::do_hook('MAMS::OnCreateUser', $evt_parms);
        $this->SetMessage($this->Lang('msg_useradded'));
      }
      else
      {
        $this->add_history($user_id, 'admin change settings');
        audit($user->id, $this->GetName(), 'Modified user ' . $user->username);
        
        \CMSMS\HookManager::do_hook('MAMS::OnUpdateUser', $evt_parms);
        $this->SetMessage($this->Lang('msg_usermodified'));
        
        if($user->must_validate)
        {
          // user save resets the temp code.
          $helper = $this->get_verification_assistant();
          $code   = $helper->set_force_verify($user->id);
          $helper->send($user->id, $code);
          audit($user->id, 'MAMS', 'User sent verification email');
        }
      }
      
      $this->RedirectToTab();
    }
    catch(\Exception $e)
    {
      echo $this->ShowErrors($e->GetMessage());
    }
  }
  
  $tpl = $this->CreateSmartyTemplate('admin_edituser2.tpl');
  $tpl->assign('required_field_color', $this->GetPreference('required_field_color', 'blue'));
  $tpl->assign('hidden_field_color', $this->GetPreference('hidden_field_color', 'blue'));
  $tpl->assign('required_field_marker', $this->GetPreference('requried_field_marker', '*'));
  $tpl->assign('hidden_field_marker', $this->GetPreference('hidden_field_marker', '!!'));
  $tpl->assign('fields', $fields);
  $tpl->assign('user', $user);
  $tpl->display();
  $user->store();
}
catch(\Exception $e)
{
  if($user)
  {
    $user->store();
  }
  $this->SetError($e->GetMessage());
  $this->Redirect($id, 'admin_edituser', $returnid, ['user_id' => $user_id]);
}
