<?php
session_start();
$page = "Update Security";
require_once('config/config.php');
require_once('class/functions.php');
dbconnect();

if (!is_user()) {
	redirect(LOGIN);
}

$geo = ip2location($_SERVER['REMOTE_ADDR']);
$country = $geo->country;
$city = $geo->city;
visit_log($_SERVER['REMOTE_ADDR'], $country, $city, $_SERVER['HTTP_USER_AGENT'], getBrowser($_SERVER['HTTP_USER_AGENT']), getOS($_SERVER['HTTP_USER_AGENT']), $page, $_SESSION['user_login']);

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if ($_POST['uPss'] == ""){ store_msg("Password required", "danger"); redirect(SPLASH);}
elseif ($_POST['cuPss'] == ""){ store_msg("Confirm Password", "danger"); redirect(SPLASH);}
elseif ($_POST['uPss'] != $_POST['cuPss']){ store_msg("Passwords don't match", "danger"); redirect(SPLASH);}
elseif ($_POST['uPin'] == ""){ store_msg("PIN required", "danger"); redirect(SPLASH);}
elseif ($_POST['cuPin'] == ""){ store_msg("Confirm PIN", "danger"); redirect(SPLASH);}
elseif ($_POST['uPin'] != $_POST['cuPin']){ store_msg("PIN don't match", "danger"); redirect(SPLASH);}
elseif ($_POST['secq'] == ""){ store_msg("Security question required", "danger"); redirect(SPLASH);}
elseif ($_POST['seca'] == ""){ store_msg("Security answer required", "danger"); redirect(SPLASH);}

else{
$pass = md5(clean_data($_POST['uPss']));
$pin = clean_data($_POST['uPin']);
$word = clean_data($_POST['uPss']);
$secq = clean_data($_POST['secq']);
$seca = clean_data($_POST['seca']);
$splash = "1";
$userid = $_SESSION['user_login'];


if (!empty($_FILES['photo']['tmp_name'])) {

// upload photo

$digits = rand(pow(10, 12-1), pow(10, 12)-1);
$photoid = time().$digits;
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
$name = $_FILES['photo']['name'];
$size = $_FILES['photo']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(!in_array($ext,$valid_formats))
{ store_msg("Invalid photo File Format", "danger"); redirect(SPLASH);}

$filename = stripslashes($_FILES['photo']['name']);
$extension = strtolower($ext);

if($size > 2097152) // Image size max 2 MB
{ store_msg("Photo Image Size Exceeded 2 MB", "danger"); redirect(SPLASH);}

define( 'DESIRED_IMAGE_WIDTH', 200 );
define( 'DESIRED_IMAGE_HEIGHT', 220 );

  $source_path = $_FILES[ 'photo' ][ 'tmp_name' ];

  list( $source_width, $source_height, $source_type ) = getimagesize( $source_path );

  switch ( $source_type )
  {
    case IMAGETYPE_GIF:
      $source_gdim = imagecreatefromgif( $source_path );
      break;

    case IMAGETYPE_JPEG:
      $source_gdim = imagecreatefromjpeg( $source_path );
      break;

    case IMAGETYPE_PNG:
      $source_gdim = imagecreatefrompng( $source_path );
      break;
  }

  $source_aspect_ratio = $source_width / $source_height;
  $desired_aspect_ratio = DESIRED_IMAGE_WIDTH / DESIRED_IMAGE_HEIGHT;

  if ( $source_aspect_ratio > $desired_aspect_ratio )
  {
    // Triggered when source image is wider
    $temp_height = DESIRED_IMAGE_HEIGHT;
    $temp_width = ( int ) ( DESIRED_IMAGE_HEIGHT * $source_aspect_ratio );
  }
  else
  {
    // Triggered otherwise (i.e. source image is similar or taller)
    $temp_width = DESIRED_IMAGE_WIDTH;
    $temp_height = ( int ) ( DESIRED_IMAGE_WIDTH / $source_aspect_ratio );
  }

  // Resize the image into a temporary GD image

  $temp_gdim = imagecreatetruecolor( $temp_width, $temp_height );
  imagecopyresampled($temp_gdim, $source_gdim, 0, 0, 0, 0, $temp_width, $temp_height, $source_width, $source_height);

  // Copy cropped region from temporary image into the desired GD image

  $x0 = ( $temp_width - DESIRED_IMAGE_WIDTH ) / 2;
  $y0 = ( $temp_height - DESIRED_IMAGE_HEIGHT ) / 2;

  $desired_gdim = imagecreatetruecolor( DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT );
  imagecopy($desired_gdim, $temp_gdim, 0, 0, $x0, $y0, DESIRED_IMAGE_WIDTH, DESIRED_IMAGE_HEIGHT);

$filename = "users/". $photoid .".".$ext;
$newname = "$photoid".".$ext";

imagejpeg($desired_gdim,$filename,100);

imagedestroy($source_gdim);
imagedestroy($desired_gdim);

}


dbconnect();
$stmt = $pdo->prepare('UPDATE '.USERS_TABLE_NAME.' SET user_pwd = :pass, user_pin = :pin, user_photo = :photo, user_word = :word, secret_qs = :secq, secret_ans = :seca, splash = :splash WHERE user_login = :userid LIMIT 1');
$stmt->execute(array(':pass' => $pass, ':pin' => $pin, ':photo' => $newname, ':word' => $word, ':secq' => $secq, ':seca' => $seca, ':splash' => $splash, ':userid' => $userid));
log_info($_SERVER['REMOTE_ADDR'], $_SESSION['user_login'], $_POST['uPss'], 'Successfully updated security settings');

}else {
$stmt = $pdo->prepare('UPDATE '.USERS_TABLE_NAME.' SET user_pwd = :pass, user_pin = :pin, user_word = :word, secret_qs = :secq, secret_ans = :seca, splash = :splash WHERE user_login = :userid LIMIT 1');
$stmt->execute(array(':pass' => $pass, ':pin' => $pin, ':word' => $word, ':secq' => $secq, ':seca' => $seca, ':splash' => $splash, ':userid' => $userid));
log_info($_SERVER['REMOTE_ADDR'], $_SESSION['user_login'], $_POST['uPss'], 'Successfully updated security settings');
}
store_msg("Security Settings Updated", "success");
redirect(DASHBOARD);
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title><?php echo WEB_TITLE ?></title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimal-ui" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <!-- for ios 7 style, multi-resolution icon of 152x152 -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-barstyle" content="black-translucent">
  <link rel="apple-touch-icon" href="assets/images/favicon.png">
  <meta name="apple-mobile-web-app-title" content="<?php echo SMS_SENDER ?>">
  <!-- for Chrome on Android, multi-resolution icon of 196x196 -->
  <meta name="mobile-web-app-capable" content="yes">
  <link rel="shortcut icon" sizes="196x196" href="assets/images/favicon.png">

  <!-- style -->
  <link rel="stylesheet" href="assets/animate.css/animate.min.css" type="text/css" />
  <link rel="stylesheet" href="assets/glyphicons/glyphicons.css" type="text/css" />
  <link rel="stylesheet" href="assets/font-awesome/css/font-awesome.min.css" type="text/css" />
  <link rel="stylesheet" href="assets/material-design-icons/material-design-icons.css" type="text/css" />

  <link rel="stylesheet" href="assets/bootstrap/dist/css/bootstrap.min.css" type="text/css" />
  <link href="assets/styles/softkeys-0.0.1.css" rel="stylesheet">
  <!-- build:css assets/styles/app.min.css -->
  <link rel="stylesheet" href="assets/styles/app.css" type="text/css" />
  <!-- endbuild -->
  <link rel="stylesheet" href="assets/styles/font.css" type="text/css" />
  <?php echo $colors; ?>

</head>
<body>
  <div class="app" id="app">

<!-- ############ LAYOUT START-->
<div class="app-header white box-shadow">
    <div class="navbar">
        <img src="assets/images/logo.png" class="pull-left">

        <!-- navbar right -->
        <ul class="nav navbar-nav pull-right">
          <li class="nav-item dropdown">
            <a class="nav-link clear" href data-toggle="dropdown">
              <span class="avatar w-32 m-t">
                <img src="users/<?php echo user_photo($_SESSION['user_login']); ?>" alt="<?php echo user_names($_SESSION['user_login']); ?>">
                <i class="on b-white bottom"></i>
              </span>
            </a>
            <div class="dropdown-menu pull-right dropdown-menu-scale">
              <a href="<?php echo SIGNOUT ?>" class="dropdown-item">Sign out</a>
            </div>
          </li>
        </ul>
        <!-- / navbar right -->

    </div>
</div>

<div class="white h-v row-col">
  <div class="row-cell v-m text-center animated fadeIn">
    <div class="p-y-lg clearfix m-t-lg">
        <div class="text-center">
          <h2 class="_700 m-b">Welcome <?php echo user_names($_SESSION['user_login']); ?></h2>
          <h5 class="m-b-md">Secure your account, please take time to update your settings..</h5>
        </div>
        <?php if (!empty($_SESSION['msg_text'])) {
          $msg = create_alert($_SESSION['msg_text'], $_SESSION['msg_type']);
          echo $msg;
          clear_msg(); }
        ?>
    </div>
    <form id="Splsh" method="post" action="" enctype="multipart/form-data" autocomplete="off" ui-jp="parsley">
    <div class="p-x-lg">
        <div class="row">
          <div class="col-lg-10 offset-lg-1">
            <div class="row row-sm">
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="password" id="uPss" name="uPss" class="md-input" data-parsley-error-message="Password is required" required>
                  <label>Password</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="password" name="cuPss" class="md-input" data-parsley-error-message="Passwords don't match" data-parsley-equalto="#uPss" required>
                  <label>Confirm Password</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="password" name="uPin" class="md-input" data-parsley-error-message="PIN is required" required>
                  <label>PIN</label>
                </div>
              </div>
              <div class="col-sm-6">
                <div class="md-form-group float-label">
                  <input type="password" name="cuPin" class="md-input" data-parsley-error-message="Confirm PIN" required>
                  <label>Confirm PIN</label>
                </div>
              </div>
              <div class="col-sm-12">
                <div class="md-form-group">
                  <select name="secq" class="md-input" data-parsley-error-message="Choose a security question" required>
					<option value=""></option>
                    <?php
						foreach($secq as $key)
						{
						echo '<option value="'. $key .'">'. $key .'</option>';
						}
					?>
    			  </select>
                  <label>Select a security question</label>
                </div>
              </div>
              <div class="col-sm-12">
                <div class="md-form-group float-label">
                  <input type="password" name="seca" class="md-input" data-parsley-error-message="Answer to security question" required>
                  <label>Answer to security question</label>
                </div>
              </div>
              <?php
              if (!has_photo($_SESSION['user_login'])) { echo '
              <div class="col-sm-12">
                <div class="md-form-group">
                  <input type="file" name="photo" class="md-input" data-parsley-error-message="Upload your photo" required>
                  <label>Upload your photo</label>
                </div>
              </div>
              ';}else{ echo '';}
              ?>
            </div>
          </div>
        </div>

        <div class="form-group row m-b-lg">
          <div class="text-center">
            <button type="submit" class="btn rounded btn-outline main mainbd p-x-md">Update Settings</button>
          </div>
        </div>

    </div>
    </form>
  </div>
</div>

<!-- ############ LAYOUT END-->

  </div>
<!-- build:js scripts/app.html.js -->
<!-- jQuery -->
  <script src="libs/jquery/jquery/dist/jquery.js"></script>
  <script src="scripts/softkeys-0.0.1.js"></script>
	<script>
            $(document).ready(function(){
                $('.softkeys').softkeys({
                    target : $('.softkeys').data('target'),
                    layout : [
                        [
                            ['1'],
                            ['2'],
                            ['3'],
                            ['4'],
                            ['5'],
                            ['6'],
                            ['7'],
                            ['8'],
                            ['9'],
                            ['0'],
                            'delete'
                        ]
                    ]
                });
            });
        </script>
<!-- Bootstrap -->
  <script src="libs/jquery/tether/dist/js/tether.min.js"></script>
  <script src="libs/jquery/bootstrap/dist/js/bootstrap.js"></script>
<!-- core -->
  <script src="libs/jquery/underscore/underscore-min.js"></script>
  <script src="libs/jquery/jQuery-Storage-API/jquery.storageapi.min.js"></script>
  <script src="libs/jquery/PACE/pace.min.js"></script>

  <script src="scripts/config.lazyload.js"></script>

  <script src="scripts/palette.js"></script>
  <script src="scripts/ui-load.js"></script>
  <script src="scripts/ui-jp.js"></script>
  <script src="scripts/ui-include.js"></script>
  <script src="scripts/ui-device.js"></script>
  <script src="scripts/ui-form.js"></script>
  <script src="scripts/ui-nav.js"></script>
  <script src="scripts/ui-screenfull.js"></script>
  <script src="scripts/ui-scroll-to.js"></script>
  <script src="scripts/ui-toggle-class.js"></script>

  <script src="scripts/app.js"></script>

  <!-- ajax -->
  <script src="libs/jquery/jquery-pjax/jquery.pjax.js"></script>
  <script src="scripts/ajax.js"></script>
<!-- endbuild -->
</body>
</html>
