<?php 
/**
 * All forms for this site
 * 
 * Change Language      : Line    35 -   52
 * Register a New User  : Line    55 -  196
 * User login           : Line   198 -  297
 * Reset Password       : Line   198 -  297
 * User logout          : Line   299 -  314
 * Check Username       : Line   316 -  329
 * Change Username      : Line   331 -  216
 * User Account Update  : Line   218 -  359
 * Change Password      : Line   361 -  411
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 */

// Change Language if active
if(isset($_POST['changelang'])){
    include(BASE);
    $langID = $_POST['langID'];
    $qchangelang = $dbc->query("SELECT * FROM `languages` WHERE `lang_id`='$langID' LIMIT 1") or die($dbc->error);
    $rchlngto = $qchangelang->fetch_assoc();
    $dbc->close();
    if($qchangelang->num_rows > 0){
        
        $_SESSION['lang'] = $rchlngto['lang_code'];
        
        $url = $_SERVER["REQUEST_URI"];
        ob_end_clean();
        header("Location: $url");
        exit();
    }
 }
// END Change Language if active

// Register a New User
if(isset($_POST['submitforapproval']) == true){
    include(BASE);
    $trimmed = array_map('trim', $_POST);
    
     if (!empty($trimmed['first_name'])){
        $fn = $dbc->real_escape_string($trimmed['first_name']);
        }else{
            $fn_err = $lng['form_register_err_fn'];
        }
        
     if (!empty($trimmed['last_name'])){
        $ln = $dbc->real_escape_string($trimmed['last_name']);
        }else{
            $ln_err = $lng['form_register_err_ln'];
        }
    
    if (filter_var($trimmed['email'], FILTER_VALIDATE_EMAIL)) {
        $e = $dbc->real_escape_string($trimmed['email']);
        }else{
            $e_err = $lng['form_register_err_e'];
        }
     
     $mob    = $_POST['mobile'];
     $url    = $_POST['url'];
     
     if(!empty($_POST['county_location'])){
        $county = $_POST['county_location'];
     }else{
        $county = $_POST['cnty_id'];
     }
     
     $commta = $_POST['comment'];
     
     //$page    = (isset($_POST['page'])) ? 1 : 0;
     $privacy = (isset($_POST['privacy'])) ? 1 : 0;
     //$terms   = (isset($_POST['terms'])) ? 1 : 0;
     $terms   = '1';
     $news    = (isset($_POST['news'])) ? 1 : 0;
     
     if($fn && $ln && $e){
        
$checkife = $dbc->query("SELECT `email` FROM `users` WHERE `email`='".$e."'") or die($dbc->error);
        
        if($checkife->num_rows == 0){
            
            //$a  = md5(uniqid(rand(), true));
            $a  = $_POST['activate'];                            
            $ge = explode("@", $e);
            $dt = date('wjnyGis');
            
            $resolveuser = $dbc->query("SELECT * FROM `users` 
                                                WHERE `user_name` = '".$ge[0]."'                                                  
                                                ORDER BY `user_name` DESC 
                                                LIMIT 1") or die($dbc->error);
            $rwsusr = $resolveuser->fetch_assoc();
            
            if($resolveuser->num_rows > 0){                
                $gue = explode("-", $rwsusr['user_name']);
                if(!empty($gue[1])){
                    $ngue = $gue[0];
                    $sgue = $gue[1];
                    $ague = $gue[1] + 1;
                }                
                $ue = $rwsusr['user_name'].'-'.$ague;
            }else{
                $ue = $ge[0];
            }
            
            //$ue = $ge[0].'-'.$dt;
            
if(!empty($_POST['county_location'])){
    $selcity  = $dbc->query("SELECT * FROM `counties` WHERE `county_name`='".$county."' LIMIT 1") or die($dbc->error);
 }else{
    $selcity  = $dbc->query("SELECT * FROM `counties` WHERE `cnty_id`='".$county."' LIMIT 1") or die($dbc->error);
 }

$rwgcity  = $selcity->fetch_assoc();

$cityID    = $rwgcity['cnty_id'];
$countryID = $rwgcity['country_id'];
$ip        = $_SERVER["REMOTE_ADDR"];
            
            $addtodb = $dbc->query("INSERT INTO `users`(`uid`, `lid`, `loc_id`, `city_id`, `country_id`, `about_id`, `hobby_id`, `sex`, `confirmed`, `approved`, `rejected`, `r_reason`, `blocked`, `b_reason`, `book`, `first_name`, `last_name`, `email`, `user_name`, `password`, `phone`, `fax`, `mobile`, `terms`, `privacy`, `news`, `commta`, `a_street`, `a_number`, `avatar`, `birthday`, `ip`, `register_date`, `last_updated`) VALUES ('0', '0', '0', '".$cityID."', '".$countryID."', '0', '0', '0', '".$a."', '1', '0', '', '0', '', '0',  '".$fn."', '".$ln."', '".$e."', '".$ue."', '', '', '', '".$mob."', '".$terms."', '".$privacy."', '".$news."', '".$commta."', '', '', '', '0000-00-00', '".$ip."', NOW(), NOW() )") or die($dbc->error);
            
if($dbc->affected_rows == 1){

$getSE = $dbc->query("SELECT `title`, `content_ro`, `content_en` FROM `email_template` WHERE `title`='confirm_reg_email_template' LIMIT 1") or die($dbc->error);
      $rSE = $getSE->fetch_assoc();
      $content = $rSE['content_'.$lang];
      
function BuildContent($content){ 
    
$content = str_replace('{{ first_name }}', ''.$_POST['first_name'].'', $content);

$content = str_replace('{{ confirm_code }}', '<a href="'.BASE_URL.PATH.'activate.html?p=activate&e='.$_POST['email'].'&a='.$_POST['activate'].'" target="_blank">Confirmă adresa de e-mail</a>', $content);

$content = str_replace('{{ site_name }}', ''.BASE_NAME.'', $content);

$content = str_replace('{{ link_site }}', '<a href="'. BASE_URL . '" style="text-decoration:none;">', $content);

$content = str_replace('{{ end_link_site }}', '</a>', $content);

return $content;

 }
 
$build_content = BuildContent($content);

// Send E-mail confirmation
require_once(SML.'mail.php');
$to = $trimmed['email'];
$subject = BASE_NAME." :: ".$lng[$rSE['title']]."!";                    
$body = "<!DOCTYPE HTML>
      <head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">      
      <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
      <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">
      <title>".$lng[$rSE['title']]."!</title>      
       </head>
       <body>
        <div style=\"margin:16px;width:800px;max-width:100%;\">      
          <div style=\"margin:16px;padding:16px;\">
            ".$build_content."
            </div>
          </div>
        </body>
      </html>";
                    
Send_Mail($to,$subject,$body);            
            
        $completed = $lng['form_register_succes'];
        }else{
            $err_exist = $lng['form_register_err_exist'];
        }
       }else{
         $err_exist = $lng['form_register_err_email_exist'];
       }
        
     }
     
     $dbc->close();
 }
// END Register a New User

// User login
if(isset($_POST['userlogin']) == true){ // Login form for users
    include(BASE);   
    
  if (!empty($_POST['email'])) {	 
      $e = $dbc->real_escape_string($_POST['email']);      
	}else{
      $err_e = $lng['form_login_err_e'];
	  $e = FALSE;
	     }
  if (!empty($_POST['pass'])) {	  
      $p = $dbc->real_escape_string($_POST['pass']);      
	}else{
	  $p = FALSE;
      $err_p = $lng['form_login_err_pass'];
	     }
         
   if($e && $p){
    
    $chkemail = $dbc->query("SELECT `email` FROM `users` WHERE `email`='$e' LIMIT 1") or die($dbc->error);
    if($chkemail->num_rows == 0){ // Check if email exist
        $noexist = $lng['form_login_err_noexist'];
        $errrst = '1';
    }else{ // if exist
      $checks = $dbc->query("SELECT * FROM `users` WHERE email='$e' LIMIT 1") or die($dbc->error);  
      $rschks = $checks->fetch_assoc();
      if(!empty($rschks['confirmed']) == NULL){
        if(!empty($rschks['approved']) == '0'){
          $notverifyed = $lng['form_login_err_unapproved'];
          $errrst = '1';          
           }else{
             if(!empty($rschks['rejected']) == '1'){
                 $rejected = $lng['form_login_err_rejected'];
                 $r_reason = $lng['form_login_err_rejected_reason'];
                 $errrst = '1';
              }else{
               if(!empty($rblk['blocked']) == '1'){
                  $blocked = $lng['form_login_err_blocked'];
                  $b_reason = $lng['form_login_err_blocked_reason'];
                  $errrst = '1';
                }else{ // if all ok
                  $reslogin = $dbc->query("SELECT uid, lid, first_name, email, user_name FROM users WHERE (email='$e' AND password=SHA('$p')) AND confirmed IS NULL") or die($dbc->error);  
                  if($reslogin->num_rows == 1) {                    
                    
 function getRealIpAddr(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
 }
 $addip = getRealIpAddr();
    
                 $row = $reslogin->fetch_array(MYSQLI_NUM);                 
                 $getinfuo = $dbc->query("SELECT * FROM `user_online` 
                                                  WHERE `uid`='".$row[0]."'") 
                                                  or die($dbc->error);                 
                 if($getinfuo->num_rows == 1){
                   $ron = $dbc->query("UPDATE `user_online` 
                                          SET `online`='1', `ip`='".$addip."' 
                                        WHERE `uid`='".$row[0]."'") or die($dbc->error);
                 }else{
                   $iron = $dbc->query("INSERT INTO `user_online`(`uoid`, `uid`, `online`, `ip`, `date_flogin`, `date_update`) VALUES ('0', '".$row[0]."', '1', '".$addip."', NOW(), NOW())") or die($dbc->error);                    
                 }
                 $reslogin->free();
                 $dbc->close();
                 
                    $_SESSION['uid']        = $row[0];
                    $_SESSION['lid']        = $row[1];
                    $_SESSION['first_name'] = $row[2];
                    $_SESSION['email']      = $row[3];
                    $_SESSION['user_name']  = $row[4];                    
     
                //$url = $_SERVER["REQUEST_URI"];
                $url = BASE_URL.PATH.$row[4].'.html';
                ob_end_clean();
                header("Location: $url");
                exit();
                    
                  }else{
                    $wrongpass = $lng['form_login_err_wrong_pass'];
                    $errrst = '1';
                  }  
                }
             }
           }
         }else{
            $notconfirmed = $lng['form_login_err_email_not_confirm'];
            $errrst = '1';
         }    
      }
    }else{
        $tryagain = $lng['form_login_try_again'];
        $errrst = '1';
    }   
  }
// END User login

// Password Reset
if(isset($_POST['userpassforgotandreset']) == true){ // Reset Password Form for users
    include(BASE);   
    
  if (!empty($_POST['email'])) {	 
      $e = $dbc->real_escape_string($_POST['email']);      
	}else{
      $err_e = $lng['form_login_err_e'];
	  $e = FALSE;
	     }  
         
   if($e){
    
    $chkemail = $dbc->query("SELECT `email` FROM `users` WHERE `email`='$e' LIMIT 1") or die($dbc->error);
    if($chkemail->num_rows == 0){ // Check if email exist
        $noexist = $lng['form_login_err_noexist'];
        $errrst = '1';
    }else{ // if exist
      $checks = $dbc->query("SELECT * FROM `users` WHERE email='$e' LIMIT 1") or die($dbc->error);  
      $rschks = $checks->fetch_assoc();
      if(!empty($rschks['confirmed']) == NULL){
        if(!empty($rschks['approved']) == '0'){
          $notverifyed = $lng['form_login_err_unapproved'];
          $errrst = '1';          
           }else{
             if(!empty($rschks['rejected']) == '1'){
                 $rejected = $lng['form_login_err_rejected'];
                 $r_reason = $lng['form_login_err_rejected_reason'];
                 $errrst = '1';
              }else{
               if(!empty($rblk['blocked']) == '1'){
                  $blocked = $lng['form_login_err_blocked'];
                  $b_reason = $lng['form_login_err_blocked_reason'];
                  $errrst = '1';
                }else{ // if all ok
                  
                  $a = $_POST['forgotcode'];                  
                  $reset = $dbc->query("UPDATE users SET confirmed='$a', last_updated=NOW() WHERE email='$e' AND confirmed IS NULL") or die($dbc->error);  
                  if($dbc->affected_rows == 1) {                    
// SEND E-mail
$getSE = $dbc->query("SELECT `title`, `content_ro`, `content_en` FROM `email_template` WHERE `title`='confirm_forgot_pass_email_template' LIMIT 1") or die($dbc->error);
      $rSE = $getSE->fetch_assoc();
      $content = $rSE['content_'.$lang];
      
function BuildContent($content){ 
    
$content = str_replace('{{ first_name }}', ''.$rschks['first_name'].'', $content);

$content = str_replace('{{ confirm_code }}', '<a href="'.BASE_URL.PATH.'activate.html?p=activate&e='.$_POST['email'].'&a='.$_POST['forgotcode'].'" target="_blank">Confirmă actiunea de resetare a parolei</a>', $content);

$content = str_replace('{{ site_name }}', ''.BASE_NAME.'', $content);

$content = str_replace('{{ link_site }}', '<a href="'. BASE_URL . '" style="text-decoration:none;">', $content);

$content = str_replace('{{ end_link_site }}', '</a>', $content);

return $content;

 }
 
$build_content = BuildContent($content);

// Send E-mail confirmation
require_once(SML.'mail.php');
$to = $_POST['email'];
$subject = BASE_NAME." :: ".$lng[$rSE['title']]."!";                    
$body = "<!DOCTYPE HTML>
      <head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">      
      <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
      <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">
      <title>".$lng[$rSE['title']]."!</title>      
       </head>
       <body>
        <div style=\"margin:16px;width:800px;max-width:100%;\">      
          <div style=\"margin:16px;padding:16px;\">
            ".$build_content."
            </div>
          </div>
        </body>
      </html>";
                    
Send_Mail($to,$subject,$body);            
            
        $completed = $lng['form_result_content_reset_password'];

// END SEND E-mail

$dbc->close();
                    
                  }  
                }
             }
           }
         }else{
            $notconfirmed = $lng['form_login_err_email_not_confirm'];
            $errrst = '1';
         }    
      }
    }else{
        $tryagain = $lng['form_login_try_again'];
        $errrst = '1';
    }   
  }
// END Password Reset

// User logout
if(isset($_POST['userlogout'])){    

    $roff = $dbc->query("UPDATE `user_online` SET `online`='0' WHERE `uid`='".$_SESSION['uid']."'") or die($dbc->error);       
    
	$_SESSION = array(); // Destroy the variables.
	session_destroy(); // Destroy the session itself.
	setcookie (session_name(), '', time()-300, '/', '', 0); // Destroy the cookie.    
    // Add the page.
	$url = BASE_URL.PATH.'index.html';	
	ob_end_clean(); // Delete the buffer.
	header("Location: $url");
	exit(); // Quit the script.    
   
 }
// END User logout

// Check Username
if(isset($_POST['chechun']) == 'true'){
    include(BASE);
    $un = $_POST['user_name'];
    
    $verun = $dbc->query("SELECT `user_name` FROM `users` WHERE `user_name`='{$un}' LIMIT 1") or die($dbc->error);
    if($verun->num_rows == 1){
        $unexist = '1';
    }else{
        $available = '1';
    }
    $dbc->close();
 }
// END Check Username

// Change Username
if(isset($_POST['chgusrnm']) == 'true'){
    include(BASE);
    $user   = $_POST['user_name'];
    $passch = $_POST['passch'];
    $uid    = $_SESSION['uid'];
    $ssun   = $_POST['sesun'];
    
    $verun = $dbc->query("UPDATE users SET user_name='$user', last_updated=NOW() WHERE (uid='$uid' AND password=sha('$passch')) LIMIT 1") or die($dbc->error);
    if($dbc->affected_rows == 1){
        
        $checkifudt = $dbc->query("SELECT * FROM `user_details` WHERE `uid`='$uid'") or die($dbc->error);
        if($checkifudt->num_rows == 1){
        
        $verundt = $dbc->query("UPDATE `user_details` SET seo='$user', `last_update`=NOW() WHERE (uid='$uid') LIMIT 1") or die($dbc->error);
        }else{
            $adduserdt = $dbc->query("INSERT INTO `user_details`(`usdet_id`, `uid`, `url`, `seo`, `pictures`, `facebook`, `twitter`, `instagram`, `linkedin`, `last_update`) VALUES ('0', '$uid', '', '$user', '', '', '', '', '', NOW())") or die($dbc->error);
        }
        
        $unupdate = '1';
        $userlog = $dbc->query("INSERT INTO `user_log`(`ulid`, `uid`, `title`, `description`, `date`) VALUES ('0', '$uid', 'change_username', 'Username $ssun, is changed to $user.', NOW() )") or die($dbc->error);
             if($dbc->affected_rows == 1){
                $_SESSION['user_name']  = $user;        
                  }
    }else{
        $err_update = '1';
    }
    $dbc->close();
 }
// END Change Username

// User Account Update
if(isset($_POST['usraccountupdate'])){
    include(BASE);
    
    $ssun = $_SESSION['user_name'];
    $uid  = $_POST['uid'];
    
    $resloadusr = $dbc->query("SELECT * FROM `users` WHERE `uid`='$uid' LIMIT 1") or die($dbc->error);
    $ru = $resloadusr->fetch_assoc();
    $resloadusr->close();
    
    if(!empty($_POST['first_name'])){
        $fn    = $_POST['first_name'];
        if($ru['first_name'] == $fn){$logfn = '';}else{
        $logfn = ' - first_name: '.$ru['first_name'].' to '.$fn.'<br/>';
        $statusupd = '1';
          }
        }else{
            $fn    = '';
            $logfn = '';
            }
    if(!empty($_POST['last_name'])){
        $ln    = $_POST['last_name'];
        if($ru['last_name'] == $ln){$logln = '';}else{
        $logln = ' - last_name: '.$ru['last_name'].' to '.$ln.'<br/>';
        $statusupd = '1';
           }
        }else{
            $ln    = '';
            $logln = '';
            }
    if(!empty($_POST['gender'])){
        $sex    = $_POST['gender'];
        if($ru['gender'] == $sex){$logsex = '';}else{
        $logsex = ' - sex: '.$ru['gender'].' to '.$sex.'<br/>';
        $statusupd = '1';
          }
        }else{
            $sex    = '';
            $logsex = '';
            }
    if(!empty($_POST['year'])){
        $yr    = $_POST['year'];
        if(date('Y', strtotime($ru['birthday'])) == $yr){$logyr = '';}else{
        $logyr = ' - year: '.date('Y', strtotime($ru['birthday'])).' to '.$yr.'<br/>';
        $statusupd = '1';
          }
        }else{
            $yr    = date('Y', strtotime($ru['birthday']));
            $logyr = '';
            }
    if(!empty($_POST['month'])){
        $mh    = date('m', mktime(0, 0, 0, date($_POST['month'])));
        if(date('m', strtotime($ru['birthday'])) == $mh){$logmh = '';}else{
        $logmh = ' - month: '.date('m', strtotime($ru['birthday'])).' to '.$mh.'<br/>';
        $statusupd = '1';
          }
        }else{
            $mh    = date('m', strtotime($ru['birthday']));
            $logmh = '';
            }
    if(!empty($_POST['day'])){
        $dy    = date('d', mktime(0, 0, 0, 0, $_POST['day']));
        if(date('d', strtotime($ru['birthday'])) == $dy){$logdy = '';}else{
        $logdy = ' - day: '.date('d', strtotime($ru['birthday'])).' to '.$dy.'<br/>';
        $statusupd = '1';
           }
        }else{
            $dy    = date('d', strtotime($ru['birthday']));
            $logdy = '';
            }
    if(!empty($_POST['phone'])){
        $ph    = $_POST['phone'];
        if($ru['phone'] == $ph){$logph = '';}else{
        $logph = ' - phone: '.$ru['phone'].' to '.$ph.'<br/>';
        $statusupd = '1';
          }
        }else{
            $ph    = '';
            $logph = '';
            }
    if(!empty($_POST['fax'])){
        $fx    = $_POST['fax'];
        if($ru['fax'] == $fx){$logfx = '';}else{
        $logfx = ' - fax: '.$ru['fax'].' to '.$fx.'<br/>';
        $statusupd = '1';
          }
        }else{
            $fx    = '';
            $logfx = '';
            }
    if(!empty($_POST['mobile'])){
        $mb    = $_POST['mobile'];
        if($ru['mobile'] == $mb){$logmb = '';}else{
        $logmb = ' - mobile: '.$ru['mobile'].' to '.$mb.'<br/>';
        $statusupd = '1';
           }
        }else{
            $mb    = '';
            $logmb = '';
            }       
    
    $datachconstruct = '<p>'.$logsex.$logfn.$logln.$logyr.$logmh.$logdy.$logph.$logfx.$logmb.'</p>';
    
    if(!empty($statusupd)){        
    $resupdate = $dbc->query("UPDATE `users` SET `sex`='$sex', `first_name`='$fn', `last_name`='$ln', `phone`='$ph', `fax`='$fx', `mobile`='$mb', `birthday`='$yr-$mh-$dy', `last_updated`=NOW() WHERE `uid`='$uid'") or die($dbc->error);
    }
    
    if($dbc->affected_rows == 1){        
        
        if(!empty($statusupd)){
        $userlog = $dbc->query("INSERT INTO `user_log`(`ulid`, `uid`, `title`, `description`, `date`) VALUES ('0', '$uid', 'account_updated', '$datachconstruct', NOW() )") or die($dbc->error);                     
                if(!empty($fn)){
                    if($dbc->affected_rows == 1){
                       $_SESSION['first_name']  = $fn;
                    }
                  }        
                }
                
                $selifusr = $dbc->query("SELECT * 
                           FROM `user_details` 
                           WHERE `uid`='{$uid}' 
                           LIMIT 1") or die($dbc->error);    
    if($selifusr->num_rows == 0){       
       $addusrdetails = $dbc->query("INSERT INTO `user_details`(`usdet_id`, `uid`, `url`, `seo`, `pictures`, `facebook`, `twitter`, `instagram`, `linkedin`, `last_update`) 
                                      VALUES ('0', '{$uid}', '{$_POST['user_website']}', '', '', '', '', '', '', NOW())") or die($dbc->error);        
    }else{    
    $udpusrdet = $dbc->query("UPDATE `user_details`
                                       SET `url`='{$_POST['user_website']}', 
                                           `last_update`=NOW() 
                                       WHERE `uid`='{$uid}'") or die($dbc->error);
    }
    
                
                
       $accupdate = '1';
    }else{
        $err_accupdate = '1';
    }
    $dbc->close();
 }
// END User Account Update

// Change Password
if(isset($_POST['usrpassupdate']) == true){
    include(BASE);
    
    $uid = $_POST['uid'];    
    
    if (!empty($_POST['c_pass'])) {	  
      $pc = $dbc->real_escape_string($_POST['c_pass']);          
	}else{
	  $pc = FALSE;
      $err_pc = $lng['user_myacc_cps_curr_pass_ph'];
	     }
    
    if (!empty($_POST['n_pass'])) {	  
      $pn = $dbc->real_escape_string($_POST['n_pass']);      
	}else{
	  $pn = FALSE;
      $err_pn = $lng['user_myacc_cps_new_pass_ph'];
	     }
    
    if (!empty($_POST['r_pass'])) {	  
      $pr = $dbc->real_escape_string($_POST['r_pass']);      
	}else{
	  $pr = FALSE;
      $err_pr = $lng['user_myacc_cps_cnp_pass_ph'];
	     }
    
    $datachconstruct = '<p> - change_pass: '.$pc.' to '.$pn.'</p>';    
    
    $chkcps = $dbc->query("SELECT `password` FROM `users` WHERE `uid`='$uid' LIMIT 1") or die($dbc->error);
    $rcps = $chkcps->fetch_assoc();    
    
    if(sha1($pc) == $rcps['password']){
        
        if($pn == $pr){
            $updupass = $dbc->query("UPDATE `users` SET `password`=sha('$pn'), `last_updated`=NOW() WHERE `uid`='$uid'") or die($dbc->error);
            if($dbc->affected_rows == 1){
                $userlog = $dbc->query("INSERT INTO `user_log`(`ulid`, `uid`, `title`, `description`, `date`) VALUES ('0', '$uid', 'change_password', '$datachconstruct', NOW() )") or die($dbc->error);
                
                $pass = $lng['user_myacc_cps_curr_pass_ph'];
           }            
        }else{
            $not = $lng['user_myacc_cps_succes'];
           }        
        
    }else{
        $nopass = $lng['user_myacc_cps_wrong_curr_pass'];
    }
  $dbc->close();    
 }
// END Change Password

if(isset($_POST['activatebook']) == true){
    include(BASE);
    $uid = $_POST['uid'];
    $actbook = $dbc->query("UPDATE `users` SET `book`='1' WHERE `uid`='$uid'") or die($dbc->error);
    
    if($dbc->affected_rows == 1){
        $datachconstruct = '<p> - change_status_book: from 0 to 1</p>'; 
        $userlog = $dbc->query("INSERT INTO `user_log`(`ulid`, `uid`, `title`, `description`, `date`) VALUES ('0', '$uid', 'change_status_book', '$datachconstruct', NOW() )") or die($dbc->error);
    }
    
    $dbc->close();
}

if(isset($_POST['dezactivatebook']) == true){
    include(BASE);
    $uid = $_POST['uid'];
    $actbook = $dbc->query("UPDATE `users` SET `book`='0' WHERE `uid`='$uid'") or die($dbc->error);
    
    if($dbc->affected_rows == 1){
        $datachconstruct = '<p> - change_status_book: from 1 to 0</p>'; 
        $userlog = $dbc->query("INSERT INTO `user_log`(`ulid`, `uid`, `title`, `description`, `date`) VALUES ('0', '$uid', 'change_status_book', '$datachconstruct', NOW() )") or die($dbc->error);
    }
    
    $dbc->close();
}


if(isset($_POST['updsettfromadmin']) == true){
    
include(BASE);
  
$chkifadmin = $dbc->query("SELECT `lid` FROM `users` WHERE `uid`='{$_POST['usrID']}' LIMIT 1") or die($dbc->error);
$rescka = $chkifadmin->fetch_assoc();

if($rescka['lid'] > 0){
    
    $aform_sitename = $_POST['site_name'];
    $aform_domain   = $_POST['domain_name'];
    $aform_prefix   = (isset($_POST['prefix'])) ? 1 : 0;
    $aform_https    = (isset($_POST['ssl'])) ? 1 : 0;    
    
    $aform_mailtype = $_POST['mail_type'];
    $aform_mailfrom = $_POST['mail_from'];
    $aform_mailhost = $_POST['mail_host'];
    $aform_mailuser = $_POST['mail_user'];
    $aform_mailpass = $_POST['mail_pass'];
    $aform_mailport = $_POST['mail_port'];
    
    $aform_wgoogle  = $_POST['w_google'];
    $aform_wbing    = $_POST['w_bing'];
    $aform_wyandex  = $_POST['w_yandex'];
    $aform_wwot     = $_POST['w_wot'];
    $aform_wnorton  = $_POST['w_norton'];
    $aform_robots   = $_POST['robots'];
    $aform_revisit  = $_POST['revisit'];
    
    $aform_mobil    = $_POST['admin_mobile'];
    $aform_email    = $_POST['admin_mail'];
    
    if(!empty($_POST['logo'])){
    $aform_logo     = $_POST['logo'];
      }else{
        $aform_logo     = $set['logo'];
      }  
    
    $aform_theme    = $_POST['theme'];
    $aform_dlang    = $_POST['dlang'];    
    
    $aform_reg      = (isset($_POST['regusr'])) ? 1 : 0;
    $aform_trs      = (isset($_POST['trs'])) ? 1 : 0;
    $aform_trs_g    = (isset($_POST['trs_g'])) ? 1 : 0;
    $aform_cook     = (isset($_POST['cookie'])) ? 1 : 0;
    
    $aform_ganalytics = $_POST['google_analytics'];
    
    $aform_header   = $dbc->real_escape_string($_POST['custom_head']);
    $aform_footer   = $dbc->real_escape_string($_POST['custom_foot']);
    
    $aform_sfacebook  = $dbc->real_escape_string($_POST['s_facebook']);
    $aform_sinstagram = $dbc->real_escape_string($_POST['s_instagram']);
    $aform_stwitter   = $dbc->real_escape_string($_POST['s_twitter']);
    $aform_slinkedin  = $dbc->real_escape_string($_POST['s_linkedin']);
        
    $aform_map     = $_POST['map'];
    
    $aform_terms       = (isset($_POST['terms'])) ? 1 : 0;
    $aform_privacy     = (isset($_POST['privacy'])) ? 1 : 0;
    $aform_cookies     = (isset($_POST['cookies'])) ? 1 : 0;
    
    $aform_terms_url   = $dbc->real_escape_string($_POST['terms_url']);
    $aform_privacy_url = $dbc->real_escape_string($_POST['privacy_url']);
    $aform_cookies_url = $dbc->real_escape_string($_POST['cookies_url']);
    
    $aform_tc_o        = $_POST['open_url_trm_in'];
    $aform_pp_o        = $_POST['open_url_prv_in'];
    $aform_cp_o        = $_POST['open_url_cks_in'];
    
    
$updset = $dbc->query("UPDATE `settings` SET `sitename`='".$aform_sitename."', `domain`='".$aform_domain."', `prefix`='".$aform_prefix."', `https`='".$aform_https."', `mailtype`='".$aform_mailtype."', `mailfrom`='".$aform_mailfrom."', `mailhost`='".$aform_mailhost."', `mailuser`='".$aform_mailuser."', `mailpass`='".$aform_mailpass."', `mailport`='".$aform_mailport."', `wgoogle`='".$aform_wgoogle."', `wbing`='".$aform_wbing."', `wyandex`='".$aform_wyandex."', `wwot`='".$aform_wwot."', `wnorton`='".$aform_wnorton."', `robots`='".$aform_robots."', `revisit`='".$aform_revisit."', `mobil`='".$aform_mobil."', `email`='".$aform_email."', `logo`='".$aform_logo."', `theme`='".$aform_theme."', `dlang`='".$aform_dlang."', `reg`='".$aform_reg."', `trs`='".$aform_trs."', `trs_g`='".$aform_trs_g."', `cook`='".$aform_cook."', `g_analytics`='".$aform_ganalytics."', `c_head`='".$aform_header."', `c_foot`='".$aform_footer."', `s_facebook`='".$aform_sfacebook."', `s_instagram`='".$aform_sinstagram."', `s_twitter`='".$aform_stwitter."', `s_linkedin`='".$aform_slinkedin."', `map`='".$aform_map."', `terms`='".$aform_terms."', `trm_url`='".$aform_terms_url."', `tc_o`='".$aform_tc_o."', `privacy`='".$aform_privacy."', `prv_url`='".$aform_privacy_url."', `pp_o`='".$aform_pp_o."', `cookies`='".$aform_cookies."', `cks_url`='".$aform_cookies_url."', `cp_o`='".$aform_cp_o."', `last_update`= NOW() WHERE 1=1") or die($dbc->error);

if($dbc->affected_rows == 1){
    $ok = $lng['set_update_succes'];
 }    
    
  }else{
    $not = $lng['set_noacces'];
  }
   
    $dbc->close();
    
 }
 
if(isset($_POST['change_logosite'])){
    include(BASE);
 
 $chkifadmin = $dbc->query("SELECT `lid` FROM `users` WHERE `uid`='{$_POST['usrID']}' LIMIT 1") or die($dbc->error);
$rescka = $chkifadmin->fetch_assoc();

if($rescka['lid'] > 0){
    
function resizeImage($resourceType,$image_width,$image_height) {
    
$maxDim = 950;
$file_name = $_FILES['logo']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['logo']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        $resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        //$resizeFileName = time();
        $uploadPath = "themes/".$set['theme'].'/img/';
        $fileExt = pathinfo($_FILES['logo']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."logo_".$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."logo_".$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizeImage($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."logo_".$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }
           
          // if (file_exists($uploadPath."logo_".$resizeFileName.'.'. $fileExt)) {
          //  unlink($uploadPath."logo_".$resizeFileName.'.'. $fileExt);
          //  }
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `settings` 
                               SET `logo`='logo_".$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE 1=1") or die($dbc->error);
	   $fileuploaded = $lng['set_upload_logo_succes'];
       }else{
       $errortouploading = $lng['set_upload_img_invalid'];	
	}

 } 
 
 $dbc->close();
 }


if(isset($_POST['admadduser']) == true){
    include(BASE);
    
    $trimmed = array_map('trim', $_POST);
    
    if (!empty($trimmed['first_name'])) {	  
      $fn = $dbc->real_escape_string($trimmed['first_name']);          
	}else{
	  $fn = FALSE;
      $err_fn = $lng['form_register_err_fn'];
    }
    
    if (filter_var($trimmed['user_email'], FILTER_VALIDATE_EMAIL)) {
        $ue = $dbc->real_escape_string($trimmed['user_email']);
        } else {
            $err_ue = $lng['form_register_err_e'];
        }    
    
    if (!empty($trimmed['role'])) {	  
      $role = $dbc->real_escape_string($trimmed['role']);          
	}else{
	  $role = FALSE;
      $err_role = $lng['admin_form_user_role'];
    }
    
    if($fn && $ue && $role){
    
    if($_POST['alid'] > 0){ 
        
$chkifuser = $dbc->query("SELECT * FROM `users` WHERE `email`='{$ue}' LIMIT 1") or die($dbc->error);
        
if($chkifuser->num_rows == 0){
        
if($role == 1){$lid = 0;}elseif($role == 2){$lid = 1;}elseif($role == 3){$lid = 2;}
        
if($_POST['gender'] == 1){$gen = '1';}elseif($_POST['gender'] == 2){$gen = '2';}else{$gen = '0';}
           
           //$a = md5(uniqid(rand(), true));
           $a = $_POST['activate'];
           
           $phone  = $_POST['phone'];
           $fax    = $_POST['fax'];
           $mobile = $_POST['mobile'];
           
           $ln     = $_POST['last_name'];
           
           $gue = explode("@", $ue);
           $dat = date('wjnyGis');
           $unm = $gue[0].'-'.$dat;           


$genpass = $dbc->real_escape_string($trimmed['pass']);
         
        if(!empty($_POST['birthday'])){
        $birthday = $_POST['birthday'];
           }else{
            $birthday = '0000-00-00';
           } 

function getRealIpAddr(){
    if (!empty($_SERVER['HTTP_CLIENT_IP'])){
      $ip=$_SERVER['HTTP_CLIENT_IP'];
    }elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
      $ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
    }else{
      $ip=$_SERVER['REMOTE_ADDR'];
    }
    return $ip;
 }
 $addip = getRealIpAddr();

$afadduser = $dbc->query("INSERT INTO `users`(`uid`, `lid`, `loc_id`, `city_id`, `country_id`, `about_id`, `hobby_id`, `sex`, `confirmed`, `approved`, `rejected`, `r_reason`, `blocked`, `b_reason`, `book`, `first_name`, `last_name`, `email`, `user_name`, `password`, `phone`, `fax`, `mobile`, `terms`, `privacy`, `news`, `commta`, `a_street`, `a_number`, `avatar`, `birthday`, `ip`, `register_date`, `last_updated`) VALUES ('0', '0', '0', '0', '0', '0', '0', '$gen', '$a', '0', '0', '', '0', '', '0', '$fn', '$ln', '$ue', '$unm', SHA('$genpass'), '$phone', '$fax', '$mobile', '0', '0', '0', 'by admin', '', '', '', '$birthday', '$addip', NOW(), NOW())") or die($dbc->error);

$newuid = $dbc->insert_id;
  
if($dbc->affected_rows == 1){
      
      $getSE = $dbc->query("SELECT `title`, `content_ro`, `content_en` FROM `email_template` WHERE `title`='confirm_reg_email_template' LIMIT 1") or die($dbc->error);
      $rSE = $getSE->fetch_assoc();
      $content = $rSE['content_'.$lang];

function BuildContent($content){ 
    
$content = str_replace('{{ first_name }}', ''.$_POST['first_name'].'', $content);

$content = str_replace('{{ confirm_code }}', '<a href="'.BASE_URL.PATH.'activate.html?p=activate&e='.$_POST['user_email'].'&a='.$_POST['activate'].'" target="_blank">Confirmă</a>', $content);

$content = str_replace('{{ site_name }}', ''.BASE_NAME.'', $content);

$content = str_replace('{{ link_site }}', '<a href="'. BASE_URL . '" style="text-decoration:none;">', $content);

$content = str_replace('{{ end_link_site }}', '</a>', $content);

return $content;

 }
 
$build_content = BuildContent($content);
    
require_once(SML.'mail.php');
$to = $trimmed['user_email'];
$subject = BASE_NAME." :: ".$lng[$rSE['title']]."!";                    
$body = "<!DOCTYPE HTML>
         <head>      
         <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">
         <title>".$lng[$rSE['title']]."!</title>
         </head>
         <body>
         <div style=\"margin:16px;width:800px;max-width:100%;\">      
           <div style=\"margin:16px;padding:16px;\">      
             ".$build_content."      
           </div>
         </div>
         </body>
         </html>";
                    
Send_Mail($to,$subject,$body);
            
            $afuadded = $lng['admin_user_form_succes'];
            
            //if(!empty($_POST['user_website'])){                
                $adduserweb = $dbc->query("INSERT INTO `user_details`(`usdet_id`, `uid`, `url`, `seo`, `pictures`, `facebook`, `twitter`, `instagram`, `linkedin`, `last_update`) VALUES ('0', '$newuid', '{$_POST['user_website']}', '$unm', '', '', '', '', '', NOW())") or die($dbc->error);
            //}
         }else{
            $afuNotadded = $lng['admin_user_form_err_notadd'];
        }    
    
       }else{ // if exist user, code bellow
         $userexist = $lng['admin_user_form_err_email_exist'];
       }
    }else{
        $afnot = $lng['admin_user_form_err_level'];
    }         

  }
$dbc->close();   
 }
 
if(isset($_POST['aproveusrfa'])){
include(BASE);
$updaprovusraf = $dbc->query("UPDATE `users` 
                              SET `approved`='1' 
                              WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
if($dbc->affected_rows == 1){
       $approvedafok = $lng['admin_approve_btn'];
     }    
    $dbc->close();
}

if(isset($_POST['adminupdateusraf']) == true){
    
    include(BASE);
    
    $udpusrfromadmin = $dbc->query("UPDATE `users` 
                                    SET `first_name`='{$_POST['first_name']}',
                                        `last_name`='{$_POST['last_name']}',
                                        `email`='{$_POST['user_email']}',
                                        `sex`='{$_POST['gender']}',
                                        `birthday`='{$_POST['birthday']}',
                                        `lid`='{$_POST['role']}',
                                        `phone`='{$_POST['phone']}',
                                        `fax`='{$_POST['fax']}',
                                        `mobile`='{$_POST['mobile']}',
                                        `last_updated`=NOW()
                                    WHERE `uid`='{$_POST['usrID']}'") 
                                    or die($dbc->error);
    
    $selusr = $dbc->query("SELECT * 
                           FROM `user_details` 
                           WHERE `uid`='{$_POST['usrID']}' 
                           LIMIT 1") or die($dbc->error);
    $selusrbase = $dbc->query("SELECT * 
                                 FROM `users` 
                                WHERE `uid`='{$_POST['usrID']}' 
                                LIMIT 1") or die($dbc->error);
                                   
           $rwusrbase = $selusrbase->fetch_assoc();                
    
    if($selusr->num_rows == 0){       
       $addusrdetails = $dbc->query("INSERT INTO `user_details`(`usdet_id`, `uid`, `url`, `seo`, `pictures`, `facebook`, `twitter`, `instagram`, `linkedin`, `last_update`) 
                                      VALUES ('0', '{$_POST['usrID']}', '{$_POST['user_website']}' '{$rwusrbase['user_name']}', '', '', '', '', '', NOW())") or die($dbc->error);
        
    }else{
    
    $udpusrdetfromadmin = $dbc->query("UPDATE `user_details`
                                       SET `url`='{$_POST['user_website']}'                   
                                       WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    }
    
    $dbc->close();
 }


if(isset($_POST['adminmsgtousraform']) == true){    
    
    $uid = $_POST['usrID'];
    
    include(BASE);
    $loadusre = $dbc->query("SELECT `email` FROM `users` WHERE `uid`='$uid' LIMIT 1") or die($dbc->error);
    $rlu = $loadusre->fetch_assoc();    
    $dbc->close();
    
    if($loadusre->num_rows == 1){
        
$getSE = $dbc->query("SELECT `title`, `content_ro`, `content_en` FROM `email_template` WHERE `title`='new_message_email_template' LIMIT 1") or die($dbc->error);
      $rSE = $getSE->fetch_assoc();
      $content = $rSE['content_'.$lang];

function BuildContent($content){ 
    
$content = str_replace('{{ first_name }}', ''.$_POST['first_name'].'', $content);

$content = str_replace('{{ msgtousr }}', ''.$_POST['msgtousr'].'', $content);

$content = str_replace('{{ site_name }}', ''.BASE_NAME.'', $content);

$content = str_replace('{{ link_site }}', '<a href="'. BASE_URL . '" style="text-decoration:none;">', $content);

$content = str_replace('{{ end_link_site }}', '</a>', $content);

return $content;

 }
 
$build_content = BuildContent($content);


require_once(SML.'mail.php');
$to = $rlu['email'];
$subject = BASE_NAME." :: ".$lng[$rSE['title']]."";                    
$body = "<!DOCTYPE HTML>
         <head>      
         <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">
         <title>".$lng[$rSE['title']]."</title>
         </head>
  <body>
    <div style=\"margin:16px;width:800px;max-width:100%;\">
      <div style=\"margin:16px;padding:16px;white-space: pre-line;\">
        ".$build_content."    
      </div>
    </div>
  </body>
</html>";
                    
Send_Mail($to,$subject,$body);
        
        $url = $_SERVER["REQUEST_URI"].'?status=Sent';	
	    ob_end_clean(); // Delete the buffer.
	    header("Location: $url");
	    exit(); // Quit the script.
    }else{
        $msgtousrnotsent = $lng['admin_form_err_message_not_sent'];
    }
}

if(isset($_POST['adminusrpassreset']) == true){
    
    include(BASE);
    
    $genpass = $dbc->real_escape_string($_POST['pass']);
    
    $resetusrpass = $dbc->query("UPDATE `users` 
                                 SET `password`=SHA('$genpass')
                                 WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
                                 
if($dbc->affected_rows == 1){
    
    $getSE = $dbc->query("SELECT `title`, `content_ro`, `content_en` FROM `email_template` WHERE `title`='new_message_email_template' LIMIT 1") or die($dbc->error);
      $rSE = $getSE->fetch_assoc();
      $content = $rSE['content_'.$lang];

function BuildContent($content){ 
    
$content = str_replace('{{ first_name }}', ''.$_POST['first_name'].'', $content);

$content = str_replace('{{ passreset }}', 'p style=\"white-space: pre-line;padding:10px;width:150px;border:dotted 2px #008000;text-align:center;\">'.$genpass.'</p>', $content);

$content = str_replace('{{ site_name }}', ''.BASE_NAME.'', $content);

$content = str_replace('{{ link_site }}', '<a href="'. BASE_URL . '" style="text-decoration:none;">', $content);

$content = str_replace('{{ end_link_site }}', '</a>', $content);

return $content;

 }
 
$build_content = BuildContent($content);

$getusrmail = $dbc->query("SELECT * FROM `users` WHERE `uid`='{$_POST['usrID']}' LIMIT 1") or die($dbc->error);
$resusr = $getusrmail->fetch_assoc();
        
require_once(SML.'mail.php');
$to = $resusr['email'];
$subject = BASE_NAME." :: ".$lng[$rSE['title']]."!";                    
$body = "<!DOCTYPE HTML>
         <head>      
      <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
      <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">
      <title>".$lng[$rSE['title']]."!</title>
      </head>
  <body>
    <div style=\"margin:16px;width:800px;max-width:100%;\">      
      <div style=\"margin:16px;padding:16px;\">      
        ".$build_content."      
      </div>
    </div>
  </body>
</html>";
                    
Send_Mail($to,$subject,$body);

        $respassdone = $lng['admin_form_succes_respass'].' ('.$genpass.')';
    }else{
        $respassfail = $lng['admin_form_err_pass_noress'].' ('.$genpass.')';
    }
    
}

if(isset($_POST['adminusrblock']) == true){
    
    include(BASE);
    
    $blkusr = $dbc->query("UPDATE `users` 
                           SET `blocked`='1',
                               `b_reason`='Pentru detalii trimiteți-ne un mesaj.' 
                           WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
  $dbc->close();
  }

if(isset($_POST['adminusrunblock']) == true){
    
    include(BASE);
    
    $blkusr = $dbc->query("UPDATE `users` 
                           SET `blocked`='0',
                               `b_reason`='' 
                           WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
  $dbc->close();
  }
  
  
  if(isset($_POST['adminusrdelete']) == true){
    
    include(BASE);
    $chkifisphotopairs = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    if($chkifisphotopairs->num_rows > 0){
        while($r = $chkifisphotopairs->fetch_assoc()){
            if(!empty($r['photo1'])){
                if(file_exists("galleries/".$r['photo1'])) {
                        unlink("galleries/".$r['photo1']);           
                  }
            }
            
            if(!empty($r['photo2'])){
                if(file_exists("galleries/".$r['photo2'])) {
                        unlink("galleries/".$r['photo2']);           
                  }
            }
            
            if(!empty($r['photo3'])){
                if(file_exists("galleries/".$r['photo3'])) {
                        unlink("galleries/".$r['photo3']);           
                  }
            }
            
            if(!empty($r['photo4'])){
                if(file_exists("galleries/".$r['photo4'])) {
                        unlink("galleries/".$r['photo4']);           
                  }
            }
        }
        
        $stergeperechi = $dbc->query("DELETE FROM `pairs` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    }
    
    $chkifisphotochamps = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    if($chkifisphotochamps->num_rows > 0){
        while($r2 = $chkifisphotochamps->fetch_assoc()){
            if(!empty($r2['photo1'])){
                if(file_exists("galleries/".$r2['photo1'])) {
                        unlink("galleries/".$r2['photo1']);           
                  }
            }
            
            if(!empty($r2['photo2'])){
                if(file_exists("galleries/".$r2['photo2'])) {
                        unlink("galleries/".$r2['photo2']);           
                  }
            }
            
        }
        
        $stergechamps = $dbc->query("DELETE FROM `champions` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    }
    
    $chkifisphotouserdt = $dbc->query("SELECT * FROM `user_details` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    if($chkifisphotouserdt->num_rows > 0){
        while($r3 = $chkifisphotouserdt->fetch_assoc()){
            if(!empty($r3['pictures'])){
                if(file_exists("images/".$r3['pictures'])) {
                        unlink("images/".$r3['pictures']);           
                  }
            }            
            
        }
        
        $stergeuserdt = $dbc->query("DELETE FROM `user_details` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    }
    
    $chkifisuserlog = $dbc->query("SELECT * FROM `user_log` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    if($chkifisuserlog->num_rows > 0){        
        $stergeuserlog = $dbc->query("DELETE FROM `user_log` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    }
    
    
    
    $adeleteusrcomplete = $dbc->query("DELETE FROM `users` WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
    
  $dbc->close();
  }
  
  
if(isset($_POST['changephotoavatar'])){
include(BASE);
 
$chkifuser = $dbc->query("SELECT * FROM `user_details` WHERE `uid`='{$_POST['usrID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifuser->fetch_assoc();

 if(file_exists("images/".$rescku['pictures'])) {
            unlink("images/".$rescku['pictures']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizeAvatarImageU($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['userphoto']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['userphoto']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'images/';
        $fileExt = pathinfo($_FILES['userphoto']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizeAvatarImageU($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."userphoto_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizeAvatarImageU($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."userphoto_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizeAvatarImageU($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."userphoto_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `user_details` 
                               SET `pictures`='userphoto_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'") or die($dbc->error);
	   $photouploaded = $lng['set_upload_logo_succes'];
       }else{
       $errortouploading = $lng['set_upload_img_invalid'];	
	}
    
  }
 
 $dbc->close();
    
    
 } 
 
if(isset($_POST['sendnewsformadmin']) == true){
    
    $subjectnews = $_POST['subjectnews'];
    $bodynews    = $_POST['bodynewscontent'];
    $onlysubscr  = (isset($_POST['check_subscriber']))? 1 : 0;
    $sessionID   = $_POST['uid'];
    
    include(BASE);
       
    $chkifa = $dbc->query("SELECT * FROM `users` WHERE `uid`='{$sessionID}' LIMIT 1") or die($dbc->error);
    $rca = $chkifa->fetch_assoc();
    
    if($rca['lid'] > 0){

if($onlysubscr == 1){      
     $selectusers = $dbc->query("SELECT * FROM `users` WHERE `news`='1'") or die($dbc->error);
  }elseif($onlysubscr == 0){
     $selectusers = $dbc->query("SELECT * FROM `users`") or die($dbc->error);
  }
        
        require_once(SML.'mail.php');
        
if($selectusers->num_rows == 1){
    
    $rusr    = $selectusers->fetch_assoc();
    $usrmail = $rusr['email'];
    $to      = $usrmail;
$subject = BASE_NAME." :: ".$subjectnews;                    
$body = "<!DOCTYPE HTML>
         <head>      
      <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
      <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">
      <title>{$subjectnews}</title>
      </head>
  <body>
    <div style=\"margin:16px;width:800px;max-width:100%;\">      
      <div style=\"margin:16px;padding:16px;\">      
        <p>".$bodynews."</p>      
      </div>
    </div>
  </body>
</html>";
                    
Send_Mail($to,$subject,$body);
   
   }elseif($selectusers->num_rows > 1){      
      
      while($rusr = $selectusers->fetch_array()){
              $to = $rusr['email'];              
   
$subject = BASE_NAME." :: ".$subjectnews;                    
$body = "<!DOCTYPE HTML>
         <head>      
      <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
      <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\">
      <title>{$subjectnews}</title>
      </head>
  <body>
    <div style=\"margin:16px;width:800px;max-width:100%;\">      
      <div style=\"margin:16px;padding:16px;\">      
        <p>".$bodynews."</p>
      </div>
    </div>
  </body>
</html>";
                    
Send_Mail($to,$subject,$body);
   }
 }
$sentok = $lng['newleter__message_sent'];
    }else{
        $sentNot = $lng['newleter__message_notsent'];
    }
}

if(isset($_POST['add_champ_form']) == true){
    include(BASE);
    
    $uid  = $_POST['uid'];
    $name = $_POST['pigeon_champ'];
    $pos  = $_POST['champ_pos'];
    
    $checknos = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$uid}'") or die($dbc->error);
    if($checknos->num_rows < 5){
        
      if($pos == '1'){
        
        $checknospos1 = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$uid}' AND `champ_pos`='{$pos}'") or die($dbc->error);
        
        if($checknospos1->num_rows < 1){
            
            $addcpdb = $dbc->query("INSERT INTO `champions`(`champ_id`, `uid`, `champ_name`, `champ_pos`, `photo1`, `photo2`, `champ_date`, `last_update`) VALUES ('0', '{$uid}', '{$name}', '{$pos}', '', '', NOW(), NOW())") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
            $added_champ = $lng['form_resp_pigeon_added'];
        }else{
            $not_added_champ = $lng['form_resp_pigeon_not_added'];
         }
         
        }else{
          $limitout = $lng['form_resp_limit'];  
        }
        
      }elseif($pos == '2'){
        
        $checknospos2 = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$uid}' AND `champ_pos`='{$pos}'") or die($dbc->error);
        
        if($checknospos2->num_rows < 4){
            
            $addcpdb = $dbc->query("INSERT INTO `champions`(`champ_id`, `uid`, `champ_name`, `champ_pos`, `photo1`, `photo2`, `champ_date`, `last_update`) VALUES ('0', '{$uid}', '{$name}', '{$pos}', '', '', NOW(), NOW())") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
            $added_champ = $lng['form_resp_pigeon_added'];
        }else{
            $not_added_champ = $lng['form_resp_pigeon_not_added'];
         }
         
        }else{
          $limitout = $lng['form_resp_limit'];  
        }
        
        
      }
       
    }else{
        $limitout = $lng['form_resp_limit'];
    }
    
    
}


if(isset($_POST['addchangephoto1']) == true){
   include(BASE);
 
$chkifph1 = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifph1->fetch_assoc();

 if(is_file("galleries/".$rescku['photo1'])) {
            unlink("galleries/".$rescku['photo1']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo1']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo1']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo1']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `champions` 
                               SET `photo1`='photo1_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `champ_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes_first'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
}


if(isset($_POST['addchangephoto2']) == true){
   include(BASE);
 
$chkifph1 = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifph1->fetch_assoc();

 if(is_file("galleries/".$rescku['photo2'])) {
            unlink("galleries/".$rescku['photo2']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo2']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo2']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo2']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `champions` 
                               SET `photo2`='photo2_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `champ_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes_second'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
}


if(isset($_POST['addchangepcb1']) == true){
   include(BASE);
 
$chkifpcb = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifpcb->fetch_assoc();

 if(is_file("galleries/".$rescku['photo1'])) {
            unlink("galleries/".$rescku['photo1']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo1']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo1']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo1']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `champions` 
                               SET `photo1`='photo1_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `champ_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
 }

if(isset($_POST['addchangepcb2']) == true){
   include(BASE);
 
$chkifpcb = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifpcb->fetch_assoc();

 if(is_file("galleries/".$rescku['photo2'])) {
            unlink("galleries/".$rescku['photo2']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo2']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo2']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo2']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `champions` 
                               SET `photo2`='photo2_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `champ_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
 }


if(isset($_POST['delphotog1']) == true){
  
    include(BASE);
    
 $selphotog1 = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['chmID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphotog1->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo1'])) {
            unlink("galleries/".$rescku['photo1']);
              $photodelservok = "Fotografia a fost ștearsă de pe server.";
             }

$delphotog1 = $dbc->query("UPDATE `champions` 
                               SET `photo1`='' 
                             WHERE `uid`='{$_POST['usrID']}' 
                               AND `champ_id`='{$_POST['chmID']}' 
                             LIMIT 1") or die($dbc->error);

    }
    $dbc->close(); 
    
 }
 
 if(isset($_POST['delphotog2']) == true){
  
    include(BASE);
    
 $selphotog2 = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['chmID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphotog2->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo2'])) {
            unlink("galleries/".$rescku['photo2']);
              $photodelservok = "Fotografia a fost ștearsă de pe server.";
             }

$delphotog2 = $dbc->query("UPDATE `champions` 
                               SET `photo2`='' 
                             WHERE `uid`='{$_POST['usrID']}' 
                               AND `champ_id`='{$_POST['chmID']}' 
                             LIMIT 1") or die($dbc->error);

    }
    $dbc->close(); 
    
 }
 
 
 if(isset($_POST['stergereporumbel']) == true){
  
    include(BASE);
    
 $selphoto = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['chmID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphoto->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo1'])) {
            unlink("galleries/".$rescku['photo1']);
              $deletephoto = "ok";
             }
             
 if(is_file("galleries/".$rescku['photo2'])) {
            unlink("galleries/".$rescku['photo2']);
              $deletephoto = "ok";
             }

$delphoto = $dbc->query("DELETE FROM `champions`                                 
                               WHERE `uid`='{$_POST['usrID']}' 
                                 AND `champ_id`='{$_POST['chmID']}'") or die($dbc->error);
                               
if($dbc->affected_rows == 1){
    $deletefromdatab = 'ok';
    }
    
    if((!empty($deletephoto)) || (!empty($deletefromdatab))){
        $msgresponsedel = $lng['pigeon_photo_deleted'];
    }    

    }
    $dbc->close(); 
    
 } 
 
 if(isset($_POST['modificaporumbel']) == true){
  
 include(BASE); 
    
$selphotom = $dbc->query("SELECT * FROM `champions` WHERE `uid`='{$_POST['usrID']}' AND `champ_id`='{$_POST['chmID']}' LIMIT 1") or die($dbc->error);
$resckum = $selphotom->fetch_assoc();

if($resckum['uid'] == $_POST['usrID']){
    
    $modifyporumbel = $dbc->query("UPDATE `champions` SET `champ_name`='{$_POST['newchampname']}' WHERE `champ_id`='{$_POST['chmID']}'") or die($dbc->error);
    
    if($dbc->affected_rows == 1){
        $oknewnamechanged = $lng['pigeon_name_updated'];
    }else{
        $newnameNOTchange = $lng['pigeon_name_not_updated'];
    }

      }
    
    $dbc->close(); 
    
 }
 
 
 if(isset($_POST['add_pair_form']) == true){
    include(BASE);
    
    $uid  = $_POST['uid'];
    $name = $_POST['pigeon_pair'];    
    
    $checknos = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$uid}'") or die($dbc->error);
    
    if($checknos->num_rows < 10){
            
            $addpair = $dbc->query("INSERT INTO `pairs`(`pair_id`, `uid`, `pair_name`, `photo1`, `photo2`, `photo3`, `photo4`, `pair_date`, `last_update`) VALUES ('0', '{$uid}', '{$name}', '', '', '', '', NOW(), NOW())") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
            $added_champ = $lng['pigeon_pairs_added'];
        }else{
            $not_added_champ = $lng['pigeon_pairs_not_added'];
         }
       
    }else{
        $limitout = $lng['form_resp_limit'];
    }
    
    
}
 
 
 if(isset($_POST['stergereperche']) == true){
  
    include(BASE);
    
 $selphoto = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['prkID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphoto->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo1'])) {
            unlink("galleries/".$rescku['photo1']);
              $deletephoto = "ok";
             }
             
 if(is_file("galleries/".$rescku['photo2'])) {
            unlink("galleries/".$rescku['photo2']);
              $deletephoto = "ok";
             }
 
 if(is_file("galleries/".$rescku['photo3'])) {
            unlink("galleries/".$rescku['photo3']);
              $deletephoto = "ok";
             }

 if(is_file("galleries/".$rescku['photo4'])) {
            unlink("galleries/".$rescku['photo4']);
              $deletephoto = "ok";
             }

$delphoto = $dbc->query("DELETE FROM `pairs`                                 
                               WHERE `uid`='{$_POST['usrID']}' 
                                 AND `pair_id`='{$_POST['prkID']}'") or die($dbc->error);
                               
if($dbc->affected_rows == 1){
    $msgresponsedeldb = $lng['pigeon_pairs_deleted'];
    }
    
    }
    $dbc->close(); 
    
 } 
 
 if(isset($_POST['modificapereche']) == true){
  
 include(BASE); 
    
$selphotom = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['pairID']}' LIMIT 1") or die($dbc->error);
$resckum = $selphotom->fetch_assoc();

if($resckum['uid'] == $_POST['usrID']){
    
    $modifypair = $dbc->query("UPDATE `pairs` SET `pair_name`='{$_POST['newpairname']}' WHERE `pair_id`='{$_POST['pairID']}'") or die($dbc->error);
    
    if($dbc->affected_rows == 1){
        $oknewnamechanged = $lng['pigeon_pairs_updated'];
    }else{
        $newnameNOTchange = $lng['pigeon_pairs_not_updated'];
    }

      }
    
    $dbc->close(); 
    
 } 
 
 
if(isset($_POST['addchangepr1']) == true){
   include(BASE);
 
$chkifpcb = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifpcb->fetch_assoc();

 if(is_file("galleries/".$rescku['photo1'])) {
            unlink("galleries/".$rescku['photo1']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo1']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo1']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo1']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo1_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `pairs` 
                               SET `photo1`='photo1_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `pair_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
 }
 
 
 if(isset($_POST['addchangepr2']) == true){
   include(BASE);
 
$chkifpcb = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifpcb->fetch_assoc();

 if(is_file("galleries/".$rescku['photo2'])) {
            unlink("galleries/".$rescku['photo2']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo2']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo2']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo2']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo2_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `pairs` 
                               SET `photo2`='photo2_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `pair_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
 }
 
 
 if(isset($_POST['addchangepr3']) == true){
   include(BASE);
 
$chkifpcb = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifpcb->fetch_assoc();

 if(is_file("galleries/".$rescku['photo3'])) {
            unlink("galleries/".$rescku['photo3']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo3']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo3']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo3']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo3_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo3_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo3_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `pairs` 
                               SET `photo3`='photo3_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `pair_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
 }
 
 if(isset($_POST['addchangepr4']) == true){
   include(BASE);
 
$chkifpcb = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['picID']}' LIMIT 1") or die($dbc->error);
$rescku = $chkifpcb->fetch_assoc();

 if(is_file("galleries/".$rescku['photo4'])) {
            unlink("galleries/".$rescku['photo4']);           
           }

if($rescku['uid'] == $_POST['usrID']){
    
function resizePhoto($resourceType,$image_width,$image_height) {
    
$maxDim = 600;
$file_name = $_FILES['photo4']['tmp_name'];
list($width, $height) = getimagesize( $file_name );
$ratio = $width/$height;
if( $ratio > 1) {
        $resizeWidth = $maxDim*$ratio;
        $resizeHeight = $maxDim;
    } else {
        $resizeWidth = $maxDim;
        $resizeHeight = $maxDim/$ratio;
    }    

$imageLayer = imagecreatetruecolor($resizeWidth,$resizeHeight);

    imagecolorallocate($imageLayer, 0, 0, 0);
    imagecolorallocatealpha($imageLayer, 255, 255, 255, 127);
    imagecolortransparent($imageLayer);
    imagealphablending($imageLayer, false);        
    imagesavealpha($imageLayer, true);
    
    imagecopyresampled($imageLayer,$resourceType,0,0,0,0,$resizeWidth,$resizeHeight, $image_width,$image_height);    
    
    return $imageLayer;
  } 

$imageProcess = 0;
if(is_array($_FILES)) {
        $fileName = $_FILES['photo4']['tmp_name']; 
        $sourceProperties = getimagesize($fileName);
        //$resizeFileName = str_replace(' ','-',strtolower(BASE_NAME));
        $resizeFileName = time();
        $uploadPath = 'galleries/';
        $fileExt = pathinfo($_FILES['photo4']['name'], PATHINFO_EXTENSION);
        $uploadImageType = $sourceProperties[2];
        $sourceImageWidth = $sourceProperties[0];
        $sourceImageHeight = $sourceProperties[1];
        switch ($uploadImageType) {
            case IMAGETYPE_JPEG:
                $resourceType = imagecreatefromjpeg($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagejpeg($imageLayer,$uploadPath."photo4_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_GIF:
                $resourceType = imagecreatefromgif($fileName); 
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagegif($imageLayer,$uploadPath."photo4_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            case IMAGETYPE_PNG:                 
                $resourceType = imagecreatefrompng($fileName);
                $imageLayer = resizePhoto($resourceType,$sourceImageWidth,$sourceImageHeight);
                imagepng($imageLayer,$uploadPath."photo4_".$rescku['uid'].'-'.$resizeFileName.'.'. $fileExt);
                break;
 
            default:
                $imageProcess = 0;
                break;
           }       
          
           
        if(isset($imageProcess) == 1){
        if(move_uploaded_file($file, $uploadPath. $resizeFileName. ".". $fileExt)){       
           $imageProcess = 1;                   
            }
           }
    }  
 
	if(isset($imageProcess) == 1){
	    $sql = $dbc->query("UPDATE `pairs` 
                               SET `photo4`='photo4_".$rescku['uid'].'-'.$resizeFileName.".".$fileExt."', 
                                   `last_update`=NOW() 
                             WHERE `uid`='{$_POST['usrID']}'
                             AND `pair_id`='{$_POST['picID']}'") or die($dbc->error);
	   $photo1uploaded = $lng['image_succes'];
       }else{
       $errortouploading = $lng['image_invalid'];	
	}
    
  }
 
 $dbc->close(); 
 }
 
 
 if(isset($_POST['delphotopr1']) == true){
  
    include(BASE);
    
 $selphoto = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['prID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphoto->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo1'])) {
            unlink("galleries/".$rescku['photo1']);
              $photodelservok = $lng['image_selete_db_succes'];
             }

$delphoto = $dbc->query("UPDATE `pairs` 
                               SET `photo1`='' 
                             WHERE `uid`='{$_POST['usrID']}' 
                               AND `pair_id`='{$_POST['prID']}' 
                             LIMIT 1") or die($dbc->error);

    }
    $dbc->close(); 
    
 }
 
 if(isset($_POST['delphotopr2']) == true){
  
    include(BASE);
    
 $selphoto = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['prID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphoto->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo2'])) {
            unlink("galleries/".$rescku['photo2']);
              $photodelservok = $lng['image_selete_db_succes'];
             }

$delphoto = $dbc->query("UPDATE `pairs` 
                               SET `photo2`='' 
                             WHERE `uid`='{$_POST['usrID']}' 
                               AND `pair_id`='{$_POST['prID']}' 
                             LIMIT 1") or die($dbc->error);

    }
    $dbc->close(); 
    
 }
 
 if(isset($_POST['delphotopr3']) == true){
  
    include(BASE);
    
 $selphoto = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['prID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphoto->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo3'])) {
            unlink("galleries/".$rescku['photo3']);
              $photodelservok = $lng['image_selete_db_succes'];
             }

$delphoto = $dbc->query("UPDATE `pairs` 
                               SET `photo3`='' 
                             WHERE `uid`='{$_POST['usrID']}' 
                               AND `pair_id`='{$_POST['prID']}' 
                             LIMIT 1") or die($dbc->error);

    }
    $dbc->close(); 
    
 }
 
 if(isset($_POST['delphotopr4']) == true){
  
    include(BASE);
    
 $selphoto = $dbc->query("SELECT * FROM `pairs` WHERE `uid`='{$_POST['usrID']}' AND `pair_id`='{$_POST['prID']}' LIMIT 1") or die($dbc->error);
$rescku = $selphoto->fetch_assoc();

if($rescku['uid'] == $_POST['usrID']){ 


 if(is_file("galleries/".$rescku['photo4'])) {
            unlink("galleries/".$rescku['photo4']);
              $photodelservok = $lng['image_selete_db_succes'];
             }

$delphoto = $dbc->query("UPDATE `pairs` 
                               SET `photo4`='' 
                             WHERE `uid`='{$_POST['usrID']}' 
                               AND `pair_id`='{$_POST['prID']}' 
                             LIMIT 1") or die($dbc->error);

    }
    $dbc->close(); 
    
 }


if(isset($_POST['addcateglinkscompetitii']) == true){
  include(BASE);
    
    if($_SESSION['lid'] > 0){
        
        $catx_usid = $_POST['usrID'];
        $catx_name = $_POST['catext_name'];
        $catx_desc = $_POST['catext_description'];
        
        
   function curatareSEO($catx_name){
    // Inlocuire spatiu cu minus.
    $catx_name = str_replace(' ', '-', $catx_name);    
    
    // inlocuire litere sau trascrieri precum -
    $catx_name = preg_replace('~[^\pL\d]+~u', '-', $catx_name);
    
    // transliterate
    setlocale(LC_CTYPE, 'ro_RO');
    $catx_name = iconv('UTF-8', 'ASCII//TRANSLIT', $catx_name);

    // Stergere caractere speciale.
    $catx_name = preg_replace('/[^A-Za-z0-9\-]/', '', $catx_name);
    
    // Inlocuire multiple minusuri cu unul singur.
    $catx_name = preg_replace('/-+/', '-', $catx_name);
    
    // Caractere mici
    $catx_name = strtolower($catx_name);
    
    return $catx_name;
 }
   
        $catx_seo = curatareSEO($catx_name);
        
                
        $catx_loc = $_POST['location'];
        $catx_srt = $_POST['sort'];        
        
        $addtobasecatext = $dbc->query("INSERT INTO `categlinks`(`catext_id`, `catext_uid`, `catext_name`, `catext_description`, `catext_seo`, `catext_loc`, `sort`, `catext_rdate`, `catext_update`) VALUES ('0', '{$catx_usid}', '{$catx_name}', '{$catx_desc}', '{$catx_seo}', '{$catx_loc}', '{$catx_srt}', NOW(), NOW())") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
            $addedok = $lng['link_form_add_cat_succes'];
        }else{
           $add_error = $lng['link_form_add_cat_fail']; 
        }
        
        
        
    }else{
        $add_error = $lng['link_form_level_error'];
    }
 
$dbc->close();
 }
 
 
if(isset($_POST['updatecateglinkscompetitii']) == true){
  include(BASE);
    
    if($_SESSION['lid'] > 0){
        
        $catx_usid = $_POST['usrID'];
        $catx_ceid = $_POST['catID'];
        $catx_name = $_POST['catext_name'];
        $catx_desc = $_POST['catext_description'];
        
        
   function curatareSEO($catx_name){
    // Inlocuire spatiu cu minus.
    $catx_name = str_replace(' ', '-', $catx_name);    
    
    // inlocuire litere sau trascrieri precum -
    $catx_name = preg_replace('~[^\pL\d]+~u', '-', $catx_name);
    
    // transliterate
    setlocale(LC_CTYPE, 'ro_RO');
    $catx_name = iconv('UTF-8', 'ASCII//TRANSLIT', $catx_name);

    // Stergere caractere speciale.
    $catx_name = preg_replace('/[^A-Za-z0-9\-]/', '', $catx_name);
    
    // Inlocuire multiple minusuri cu unul singur.
    $catx_name = preg_replace('/-+/', '-', $catx_name);
    
    // Caractere mici
    $catx_name = strtolower($catx_name);
    
    return $catx_name;
 }
   
        $catx_seo = curatareSEO($catx_name);
        
                
        $catx_loc = $_POST['location'];
        $catx_srt = $_POST['sort'];        
        
        $addtobasecatext = $dbc->query("UPDATE `categlinks` SET `catext_uid`='{$catx_usid}', `catext_name`='{$catx_name}', `catext_description`='{$catx_desc}', `catext_seo`='{$catx_seo}', `catext_loc`='{$catx_loc}', `sort`='{$catx_srt}', `catext_update`=NOW() WHERE `catext_id`='{$catx_ceid}'") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
            $addedok = $lng['link_form_update_cat_succes'];
        }else{
           $add_error = $lng['link_form_update_cat_fail']; 
        }        
        
    }else{
        $add_error = $lng['link_form_level_error_edit'];
    }
 
$dbc->close();
 }



if(isset($_POST['removecatextlink']) == true){
  
  if($_SESSION['lid'] > 0){
        
        include(BASE);        
        $cteID = $_POST['cteID'];        
        $removecatext = $dbc->query("DELETE FROM `categlinks` WHERE `catext_id`='{$cteID}'") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
    $lnkremovefromdb = $lng['link_form_delete_cat_succes'];
    }
        
       $dbc->close(); 
    }
    
  }

 
 if(isset($_POST['addlinkstomainframes']) == true){
  include(BASE);
    
    if($_SESSION['lid']> 0){
        
        $extl_ctid = $_POST['cteID'];
        $extl_usid = $_POST['usrID'];        
        $extl_name = $_POST['extl_name'];
        $extl_turl = $_POST['extl_url'];
        $extl_sort = $_POST['sort'];
        
   function curatareSEO($extl_name){
    // Inlocuire spatiu cu minus.
    $extl_name = str_replace(' ', '-', $extl_name);    
    
    // inlocuire litere sau trascrieri precum -
    $extl_name = preg_replace('~[^\pL\d]+~u', '-', $extl_name);
    
    // transliterate
    setlocale(LC_CTYPE, 'ro_RO');
    $extl_name = iconv('UTF-8', 'ASCII//TRANSLIT', $extl_name);

    // Stergere caractere speciale.
    $extl_name = preg_replace('/[^A-Za-z0-9\-]/', '', $extl_name);
    
    // Inlocuire multiple minusuri cu unul singur.
    $extl_name = preg_replace('/-+/', '-', $extl_name);
    
    // Caractere mici
    $extl_name = strtolower($extl_name);
    
    return $extl_name;
 }
   
        $extl_seo = curatareSEO($extl_name);
        
                
        $extl_tgt = $_POST['target'];
        $extl_dfl = (isset($_POST['setopen'])) ? 1 : 0; 
        
              
        
        $addtobasecatext = $dbc->query("INSERT INTO `extlinks`(`extl_id`, `catext_id`, `extl_uid`, `extl_name`, `extl_url`, `sort`, `extl_seo`, `extl_target`, `extl_default`, `extl_dateadd`, `extl_last_update`) VALUES ('0', '{$extl_ctid}', '{$extl_usid}', '{$extl_name}', '{$extl_turl}', '{$extl_sort}', '{$extl_seo}', '{$extl_tgt}', '{$extl_dfl}', NOW(), NOW())") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
            $addedok = $lng['link_form_add_succes'];
        }else{
           $add_error = $lng['link_form_add_fail']; 
        }
        
    }else{
        $add_error = $lng['link_form_level_error_link'];
    }
 
   $dbc->close();
 }
 
 
 if(isset($_POST['updatelinkstomainframes']) == true){
  include(BASE);
    
    if($_SESSION['lid'] > 0){
        
        $extl_ctid = $_POST['cteID'];
        $extl_lkid = $_POST['lnkID'];
        $extl_usid = $_POST['usrID'];        
        $extl_name = $_POST['extl_name'];
        $extl_turl = $_POST['extl_url'];
        $extl_sort = $_POST['sort'];
        
   function curatareSEO($extl_name){
    // Inlocuire spatiu cu minus.
    $extl_name = str_replace(' ', '-', $extl_name);    
    
    // inlocuire litere sau trascrieri precum -
    $extl_name = preg_replace('~[^\pL\d]+~u', '-', $extl_name);
    
    // transliterate
    setlocale(LC_CTYPE, 'ro_RO');
    $extl_name = iconv('UTF-8', 'ASCII//TRANSLIT', $extl_name);

    // Stergere caractere speciale.
    $extl_name = preg_replace('/[^A-Za-z0-9\-]/', '', $extl_name);
    
    // Inlocuire multiple minusuri cu unul singur.
    $extl_name = preg_replace('/-+/', '-', $extl_name);
    
    // Caractere mici
    $extl_name = strtolower($extl_name);
    
    return $extl_name;
 }
   
        $extl_seo = curatareSEO($extl_name);
        
                
        $extl_tgt = $_POST['target'];
        $extl_dfl = (isset($_POST['setopen'])) ? 1 : 0;       
        
        $addtobasecatext = $dbc->query("UPDATE `extlinks` SET `catext_id`='{$extl_ctid}', `extl_uid`='{$extl_usid}', `extl_name`='{$extl_name}', `extl_url`='{$extl_turl}', `sort`='{$extl_sort}', `extl_seo`='{$extl_seo}', `extl_target`='{$extl_tgt}', `extl_default`='{$extl_dfl}', `extl_last_update`=NOW() WHERE `extl_id`='$extl_lkid'") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
            $addedok = $lng['link_form_update_succes'];
        }else{
           $add_error = $lng['link_form_update_fail']; 
        }
        
    }else{
        $add_error = $lng['link_form_level_error_update'];
    }
 
   $dbc->close();
 }
 
 
 if(isset($_POST['removeXtlink']) == true){
    
    if($_SESSION['lid'] > 0){
        
        include(BASE);        
        $lnkID = $_POST['lnkID'];        
        $removelinks = $dbc->query("DELETE FROM `extlinks` WHERE `extl_id`='{$lnkID}'") or die($dbc->error);
        
        if($dbc->affected_rows == 1){
    $lnkremovefromdb = $lng['link_form_delete_link'];
    }
        
       $dbc->close(); 
    }
 }
 
if(isset($_POST['templatemodedir']) == true){
    
    include(BASE);
    
    $chkAdm = $dbc->query("SELECT `lid`,`uid` FROM `users` LIMIT 1") or die($dbc->error);
    $resAdm = $chkAdm->fetch_assoc();    
    
    if($resAdm['lid'] > 0){
        
        $content_id = $_POST['etID'];
        $nameSE     = $_POST['et_name'];
        $content_ro = $dbc->real_escape_string($_POST['et_content_ro']);
        $content_en = $dbc->real_escape_string($_POST['et_content_en']);
        
        $chkSE = $dbc->query("SELECT * FROM `email_template` WHERE `et_id`='".$content_id."' LIMIT 1") or die($dbc->error);
        $resSE = $chkSE->fetch_assoc();
        
        if(!empty($resSE['et_id'])){
            $updSE = $dbc->query("UPDATE `email_template` SET `uid`='".$resAdm['uid'] ."', `content_ro`='".$content_ro ."', `content_en`='".$content_en ."', `last_update`=NOW() WHERE `et_id`='".$content_id ."'") or die($dbc->error);
            
            if($dbc->affected_rows == 1){
                $updated_et = $lng['email_template_updated'];
            }else{
                $not_updated = $lng['email_template_not_updated'];
            }
            
        }else{
            $insSE = $dbc->query("INSERT INTO `email_template`(`et_id`, `uid`, `title`, `content_ro`, `content_en`, `date_created`, `last_update`) VALUES ('0', '".$resAdm['uid'] ."', '".$nameSE."', '".$content_ro."', '".$content_en."', NOW(), NOW())") or die($dbc->error);
          if($dbc->affected_rows == 1){
                $updated_et = $lng['email_template_added'];
            }else{
                $not_updated = $lng['email_template_not_added'];
            }    
        }        
    }else{
        $notAuth = $lng['email_template_level_edit'];
    }
    
    $dbc->close();

 }

if(isset($_POST['changelangcontent']) == true){
    
    include(BASE);
    
    $trimmed = array_map('trim', $_POST);
    
    if (!empty($trimmed['valContent'])) {	  
      $vC = $dbc->real_escape_string($trimmed['valContent']);          
	}else{
	  $vC = FALSE;
      $err_vC = $lng['form_register_err_fn'].'Continutul traducerii nu poate fi gol.';
    }
    
    $idC = $trimmed['languageID'];
    $LID = $trimmed['LID'];
    
    if($LID > 0){// This is Admin
       if($vC){
        $updatelangcontent = $dbc->query("UPDATE lang_content SET value='$vC' WHERE langc_id='$idC'") or die($dbc->error);
        if($dbc->affected_rows == 1){// Tisi is updated
           $updatelangsucces = 'Traducere actualizata cu succes';
        }
       }
    }else{// This is NOT Admin - Acces Denied
      $err_NA = 'NOT Admin';
    }
    
    
    $dbc->close();
  }
 
?>