<?php

/**
*
* @package simpleMembership
* @copyright Andrey Kvasnevskiy-OrdaSoft(akbet@mail.ru); Anton Getman(ljanton@mail.ru);
* Homepage: http://www.ordasoft.com
* @version: 1.1 PRO
*
**/


/* Initialize Joomla framework */
define( '_JEXEC', 1 );
define( 'JPATH_BASE', realpath(dirname(__FILE__).'/../../../' ));
define( 'DS', DIRECTORY_SEPARATOR );
/* Required Files */
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
/* To use Joomla's Database Class */
require_once ( JPATH_BASE .DS.'libraries'.DS.'joomla'.DS.'factory.php' );
  
  
/* Create the Application - it need for database */
$mainframe =JFactory::getApplication('site');
//DBQuery
$database =JFactory::getDBO();
$params_for_sync=JRequest::getVar('params_for_sync');
$task=$params_for_sync['task'];
switch($task){
  case "sync":
    sync_user($params_for_sync);
  break;
  case "expire":
    exp_user($params_for_sync);
  break;
  
}

function sync_user($params_for_sync){

  $database = JFactory::getDBO();
  if(empty($user_configuration))
  include(JPATH_SITE.'/administrator/components/com_simplemembership/admin.simplemembership.class.conf.php');
  if(!class_exists('mos_alUser'))
  include(JPATH_SITE.'/components/com_simplemembership/simplemembership.class.php');
  /// DEFAULT GROUP
  $default_group = $user_configuration['default_group'];
  if(empty($default_group) ) $default_group=array('2'=>'2');
  else {
    $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ( ".$default_group." )";
    $database->setQuery($query);
    $default_group_name=$database->loadResultArray();
    $default_group_name=implode(",",$default_group_name);
    //$default_group=array_combine($default_group,$default_group);
    
    $f="";
    $s = explode(',',$user_configuration['default_group'] );
    for($i = 0;$i<count($s);$i++){
        $f[] = JHTML::_('select.option', $s[$i], '', 'value', 'text' );
    }
    $default_group = $f ;
  }
  /// END DEFAULT GROUP
  if($params_for_sync['count_adv_users']!=0) {
    $count_adv_users=$params_for_sync['count_adv_users'];
  }
  else {
    $query = "SELECT COUNT(*) FROM #__simplemembership_users";
    $database->setQuery($query);
    $count_adv_users = $database->loadResult();
  }
  if($params_for_sync['ia']!=0) $ia=$params_for_sync['ia'];
  else $ia=0;
  if($params_for_sync['ia_d']!=0) $ia_d=$params_for_sync['ia_d'];
  else $ia_d=0;
  if( ($ia*100-$ia_d) <= floor($count_adv_users) ) {
  //this hren for correct work because count_adv_users can be differnt, because they can be deleted
      $start_ia=100*$ia-$ia_d;
      $query = "SELECT * FROM #__simplemembership_users ORDER BY id LIMIT ".$start_ia.", 100 ";
      $database->setQuery($query);
      $adv_users = $database->loadObjectList();
      foreach($adv_users as $adv_user){//if there aren't users in user delete from adv_users
        $query = "select name from #__users where id='".$adv_user->joomid ."'";
        $database->setQuery($query);
        $joom_result = $database->loadResult();
        if($joom_result=='')
        {
          $al_user = new mos_alUser($database);
          $al_user->load($adv_user->id);
          $al_user->delete();
          $ia_d=$ia_d+1;
  //         $query = "delete from #__simplemembership_users where id='".$adv_user->id."'";
  //         $database->setQuery($query);
  //         $database->query();
        }
  
  
      }
    $query = "SELECT COUNT(*) FROM #__simplemembership_users";
    $database->setQuery($query);
    $count_adv_users = $database->loadResult();
    $ia=$ia+1;
    $params_for_sync['ia_d']=$ia_d;
    $params_for_sync['ia']=$ia;
    $params_for_sync['count_adv_users']=$count_adv_users;
    $params_for_sync['task']='sync';
    echo json_encode($params_for_sync);exit;
  }



  if($params_for_sync['count_joom_users']!=0) {
    $count_joom_users=$params_for_sync['count_joom_users'];
  }
  else {
    $query = "SELECT COUNT(*) FROM #__users";
    $database->setQuery($query);
    $count_joom_users = $database->loadResult();
  }
  if($params_for_sync['ij']!=0) $ij=$params_for_sync['ij'];
  else $ij=0;
  if($ij <= floor($count_joom_users/100)){

    $query = "SELECT * FROM #__users WHERE block=0 AND activation='' OR  activation='0' LIMIT ".$ij*100 .", 100";
    $database->setQuery($query);
    $joom_users = $database->loadObjectList();
    foreach($joom_users as $user){
      $query = "SELECT group_id FROM #__user_usergroup_map WHERE user_id='".$user->id."'";
      $database->setQuery($query);
      $user->group_id = $database->loadResultArray();
      if(isset($user->group_id) && count($user->group_id) >1){
        $user->group_id=array_combine($user->group_id,$user->group_id);
      }
      if(isset($user->group_id) && count($user->group_id) <2 && count($user->group_id)>0){
        $user->group_id=array($user->group_id[0] => $user->group_id[0]);
      }
      $user->group_id=array_combine($user->group_id, $user->group_id);
      $query = "SELECT * FROM #__simplemembership_users WHERE joomid='".$user->id."'";
      $database->setQuery($query);
      $adv_result = $database->loadObject();
  //    var_dump($adv_result );
      if($adv_result){
        $query = "SELECT jgroup_id FROM #__simplemembership_group_joomgroup WHERE mgroup_id='".$adv_result->advgroup_id."'";
        $database->setQuery($query);
        $adv_result->gid=$database->loadResultArray();
        if(isset($adv_result->gid) && count($adv_result->gid) >1){
          $adv_result->gid=array_combine($adv_result->gid,$adv_result->gid);
        }
        if(isset($adv_result->gid) && count($adv_result->gid) <2 && count($adv_result->gid) >0){
          $adv_result->gid=array($adv_result->gid[0] => $adv_result->gid[0]);
        }
      }
      if(!$adv_result)
      {
        $al_user = new mos_alUser($database);
        $al_user->name = $user->name;
        $al_user->username = $user->username;
        $al_user->email = $user->email;
        $al_user->joomid = $user->id;
        $al_user->gid = $user->group_id;
        $al_user->want_gid = $user->group_id;
        $al_user->want_group = $user->usertype;
        $al_user->usertype = $user->usertype;
        $al_user->block = $user->block;
        $al_user->approved = $user->block;
        $al_user->days_last = 0;
        $al_user->advgroup_id = 0;
        $al_user->store();
      }
      else
      {
          $al_user = new mos_alUser($database);
          $al_user->load($adv_result->id);
          $al_user->name = $user->name;
          $al_user->username=$user->username;
          $al_user->email=$user->email;
          $al_user->block=$user->block;
//         $set[] ="name='".$user->name ."'";
//         $set[] ="username='".$user->username ."'";
//         
//         $set[] ="email='".$user->email ."'";
//         
//         $set[] ="block='".$user->block ."'";
  
        if($adv_result->advgroup_id==0)
        {
  /*        $adv_result->want_gid = $user->group_id;
          $adv_result->want_group = $user->usertype;*/
        }
  
  //      if(!($adv_result->gid==$user->group_id || $adv_result->gid == $default_group /*|| $adv_result->want_gid==$user->group_id*/))
  //      {//disapprove ???
  //    echo"sdghfjsdgfjk";
  //        $set[] ="gid='".$user->group_id ."',usertype='".$user->usertype ."', user_type='invalid::dug', approved='1'";
  //      }
    /*
        $set[] ="gid='".$user->group_id ."'";
        $set[] ="usertype='".$user->usertype ."'";*/
  $al_user->store();
//         $id = $adv_result->id;
//         $query = "update #__simplemembership_users SET ". implode(',', $set)." where id='$id' AND advgroup_id<>0";
//         $database->setQuery($query);
//         $database->query();
      }
    }
    $ij++;
    $params_for_sync['ij']=$ij;
    $params_for_sync['count_joom_users']=$count_joom_users;
    $params_for_sync['task']='sync';
    echo json_encode($params_for_sync);exit;
  }

  $params_for_sync['status']='sync_user_ok';
  $params_for_sync['task']='expire';
  echo json_encode($params_for_sync);exit;

}

function exp_user($params_for_sync){
  global $mosConfig_mailfrom;
  $database = JFactory::getDBO();

  if(!class_exists('mos_alUser'))
  include(JPATH_SITE.'/components/com_simplemembership/simplemembership.class.php');

  if(empty($user_configuration))
  include(JPATH_SITE.'/administrator/components/com_simplemembership/admin.simplemembership.class.conf.php');

  /// DEFAULT GROUP
  $default_group = $user_configuration['default_group'];
  if(empty($default_group) ) $default_group=array('2'=>'2');
  else {
    $query ="SELECT ug.title FROM #__usergroups AS ug WHERE ug.id IN ( ".$default_group." )";
    $database->setQuery($query);
    $default_group_name=$database->loadResultArray();
    $default_group_name=implode(",",$default_group_name);
    //$default_group=array_combine($default_group,$default_group);
    
    $f="";
    $s = explode(',',$user_configuration['default_group'] );
    for($i = 0;$i<count($s);$i++){
        $f[] = JHTML::_('select.option', $s[$i], '', 'value', 'text' );
    }
    $default_group = $f ;
  }
  /// END DEFAULT GROUP
  
  if($params_for_sync['count_exp_users']!=0) {
    $count_exp_users=$params_for_sync['count_exp_users'];
  }
  else {
    $query = "SELECT COUNT(*) FROM #__simplemembership_users WHERE advgroup_id<>'0' AND DATE_SUB(CURDATE(),INTERVAL `days_last` DAY) >= `last_approved` AND approved='0' AND `days_last`<>'0'";
    $database->setQuery($query);
    $count_exp_users = $database->loadResult();
  }
  
  if($params_for_sync['ie']!=0) $ie=$params_for_sync['ie'];
  else $ie=0;
  if($params_for_sync['ie_d']!=0) $ie_d=$params_for_sync['ie_d'];
  else $ie_d=0;

  if(($ie*100-$ie_d)<= floor($count_exp_users/100)){
    $start_ie=100*$ie-$ie_d;
    $query = "SELECT id,joomid FROM #__simplemembership_users WHERE advgroup_id<>'0' AND DATE_SUB(CURDATE(),INTERVAL `days_last` DAY) >= `last_approved` AND approved='0' AND `days_last`<>'0' ORDER BY id LIMIT ".$start_ie .", 100";
    $database->setQuery($query);
    $list_joom_id = $database->loadObjectList();
    $user = new JUser();
    foreach($list_joom_id as $item){
      $user->load($item->joomid);
      $user->groups = $default_group;
      $user->usertype = $default_group_name;
      $user->save();
      
      $al_user = new mos_alUser($database);
      $al_user->load($item->id);
      $al_user->user_type='invalid::texp';
      $al_user->approved='1';
      $notification_email=$al_user->email;
      $al_user->store();
      $ie_d=$ie_d+1;
//       $query = "update #__simplemembership_users SET user_type='invalid::texp',gid='$default_group', usertype='$default_group_name',approved='1' where joomid='".$item->joomid."'";
//       $database->setQuery($query);
//       $database->query();

      JUTility::sendMail($mosConfig_mailfrom,'simplemembership joomla sencexpire',$notification_email, 'account disapproved',stripslashes($user_configuration['user_disapprove_msg']),1);
    }
    $ie++;
    $params_for_sync['ie']=$ie;
    $params_for_sync['ie_d']=$ie_d;
    $params_for_sync['count_exp_users']=$count_exp_users;
    $params_for_sync['task']='expire';
    echo json_encode($params_for_sync);exit;
  }

  $params_for_sync['status']='exp_user_ok';
  echo json_encode($params_for_sync);exit;


}







?>
