<?php
include 'pagename.php';
include $session;
Session::checkSession_app();
include '../config.php';

$evp_options_sql = "SELECT option_name, option_value FROM evp_options";
$evp_options_read = $db->select($evp_options_sql);
if ($evp_options_read) {
    $evp_options_check = mysqli_num_rows($evp_options_read);
    if ($evp_options_check > 0) {
		 while($row = $evp_options_read->fetch_assoc()) {
			$option_name[$row['option_name']] = $row['option_value'];
    }
	$evp_options_read->free();
        $s_url =  $option_name['site_url'];		
        $a_url =  $option_name['app_url'];		
		$s_path =  $option_name['script_path'];
		$site_title =  $option_name['site_title'];
		$user_image_url =  $option_name['image'];	
		$user_name =  $option_name['fname'];	
		$get_current_pass =  $option_name['password'];	
	}
}
	
function mailsend($mail,$resettoken,$action){
  global $s_url, $a_url, $site_title, $mail_token_func;
  $domain = $_SERVER['HTTP_HOST'];
  $from = "no-reply@".$domain;
  // Always set content-type when sending HTML email
  $headers = "MIME-Version: 1.0" . "\r\n";
  $headers.= "Content-type:text/html;charset=UTF-8" . "\r\n";
  // More headers
  $headers.= 'From: <' . $from . '>' . "\r\n";
  $subject = "$site_title - Email Address Change Request";
  $message = '<html><body>';
  $message .= '<div style="width:100%;text-align:center;">';
  $message .= "<h3>Hello!</h3>";
  $message .= "<p>We have received a user email change request to this email address.</p>";
  $message .= "<p>Please, verify your email address change request by clicking following link</p>";
  $link = $s_url."/functions/".$mail_token_func."?verify_token=".$resettoken."&".$action."=".$mail;
  $message .= "<div style='border-radius: 10px;cursor:pointer;background:#F7C9C9; display:inline-block;padding:10px;'>".$link."</div>";
  $message .= "<p><small>If you think this is a mistake then kindly disregard this email request and inform <strong>$site_title - <a href='$s_url' target='_blank'>$s_url</a></strong> immediately!</small></p>";
  $message .= "</div>";
  $message .= "</body></html>";
  if (mail($mail, $subject, $message, $headers)) {
    return true;
  }
  return false;
}
function RandomString($length = 20) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function test_input($data) { //filter value function
    $db = new database();
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    $data = strtolower($data);
    $data = mysqli_real_escape_string($db->link, $data);
    return $data;
}

$error = false;
$message = '';
$action_std = false;
$action_cat = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['profile_img_btn'])) {
          $action_std = true;
          $action_cat = 'profile_img';
          $user_id = test_input($_POST['user_id']);
          // ------------------------------------------------------------
          $img_url= test_input($_FILES['img_url']['name']);
          if(!empty($img_url)){
            // ---img functions---
            // Get Image Dimension
            $fileinfo = @getimagesize($_FILES["img_url"]["tmp_name"]);
            $width = $fileinfo[0];
            $height = $fileinfo[1];
            $allowed_image_extension = array(
                "png",
                "jpg",
                "jpeg"
            );
            // Get image file extension
            $file_extension = pathinfo($_FILES["img_url"]["name"], PATHINFO_EXTENSION);
            $file_extension = strtolower($file_extension);
            // Validate file input to check if is not empty
            if (! file_exists($_FILES["img_url"]["tmp_name"])) {
                  $error = true;
                  $message = "Choose image file to upload.";

            }    // Validate file input to check if is with valid extension
            else if (! in_array($file_extension, $allowed_image_extension)) {
                    $error = true;
                    $message = "Upload valiid images. Only PNG, JPG and JPEG are allowed.";
            }    // Validate image file size
            else if (($_FILES["img_url"]["size"] > 500000)) {

              $error = true;
              $message = "Image size exceeds 500KB";

            }else {
                 $img_url = $user_id.".".$file_extension;


                       $img_url = $user_name.'_'.$img_url;
                       $target = "../uploads/" .$img_url;
                       if(!empty($user_image_url) && $user_image_url != 0){
                         unlink('../uploads/'.$user_image_url);
                       }
                       if (move_uploaded_file($_FILES["img_url"]["tmp_name"], $target)) {
                         $user_update_sql = "UPDATE evp_options	
												SET option_value = CASE option_name	
													WHEN 'image' THEN '$img_url'	
												END	
												WHERE option_name IN ('image')";
                         $user_insert_read = $db -> update($user_update_sql);
                         if ($user_insert_read) {
                           $error = false;
                           $message = "Image uploaded successfully.";
                         }else{
                           $error = true;
                           $message = "Problem in uploading database files.";
                         }

                       } else {

                          $error = true;
                          $message = "Problem in uploading image files.";

                       }
                     
                   
            }
          }else{
            $error = true;
            $message = "No Image found";
          }
          // -------------------------------------------------------------
        }else{
          header("Location: $a_url/".$error_404_page);
        }
        if($action_std && !empty($action_cat)){
          Session::set("action_cat", $action_cat);
          Session::set("action", $error);
          Session::set("action_message", $message);
          header("Location: $a_url/".$profile_page);
        }else{
          header("Location: $a_url/".$error_404_page);
        }
      }else{
        header("Location: $a_url/".$error_404_page);
      }
?>