<?php
session_start();
require_once('../config/config.php');
require_once('../class/functions.php');
dbconnect();

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

$page = "Edit";
$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['admin_login']);


if (isset($_POST['updtUsr']) && $_POST['updtUsr'] == 'updtUsr')
{
if ($_POST['firstname'] == "") { store_msg("Firstname required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['usrPs'] == "") { store_msg("Password required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['pin'] == "") { store_msg("PIN required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['surname'] == "") { store_msg("Surname required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['gender'] == "") { store_msg("Select Gender", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['dob'] == "") { store_msg("Select date of birth", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['email'] == "") { store_msg("Email required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['phone'] == "") { store_msg("Mobile number required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['address'] == "") { store_msg("Address required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['city'] == "") { store_msg("City required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['state'] == "") { store_msg("State required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['zip'] == "") { store_msg("Zip or Postal code required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['country'] == "") { store_msg("Country required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['identification'] == "") { store_msg("Select ID type", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['idno'] == "") { store_msg("ID number required", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['expiry'] == "") { store_msg("Select ID expiry date", "danger"); redirect(ACCOUNTS);}
elseif ($_POST['status'] == "") { store_msg("Select account holder's Status", "danger"); redirect(ACCOUNTS);}
//elseif (!empty($_FILES['photo']['name']) && !valid_photo($_FILES['photo']['name'])) { store_msg("Invalid photo file format", "danger"); redirect(ACCOUNTS);}
//elseif (!empty($_FILES['photo']['size']) && !valid_size($_FILES['photo']['size'])) { store_msg("Photo image size exceeded 2 MB", "danger"); redirect(ACCOUNTS);}

else{
$usernumber = clean_data($_POST['userNumber']);
$userID = clean_data($_POST['userID']);
$pass = md5(clean_data($_POST['usrPs']));
$pin = clean_data($_POST['pin']);
$word = clean_data($_POST['usrPs']);
$sname = clean_data($_POST['surname']);
$fname = clean_data($_POST['firstname']);
$names = $fname.' '.$sname;
$gender = clean_data($_POST['gender']);
$dob = clean_data($_POST['dob']);
$email = clean_data($_POST['email']);
$phone = clean_data($_POST['phone']);
$address = clean_data($_POST['address']);
$city = clean_data($_POST['city']);
$state = clean_data($_POST['state']);
$zip = clean_data($_POST['zip']);
$country = clean_data($_POST['country']);
$idtype = clean_data($_POST['identification']);
$idno = clean_data($_POST['idno']);
$expiry = clean_data($_POST['expiry']);
$status = clean_data($_POST['status']);

$stmt = $pdo->prepare('UPDATE '.USERS_TABLE_NAME.' SET user_pwd = :pass, user_pin = :pin, user_word = :word, first_name = :fname, last_name = :lname, user_names = :names, user_email = :email, user_phone = :phone, user_gender = :gender, dob = :dob, user_add = :address, user_city = :city, user_state = :state, postcode = :postcode, country = :country, id_type = :idtype, id_number = :idno, id_expiry = :expiry, user_suspended = :status WHERE user_number = :usernumber');

if ($stmt->execute(array(':pass' => $pass, ':pin' => $pin, ':word' => $word, ':fname' => $fname, ':lname' => $sname, ':names' => $names, ':email' => $email, ':phone' => $phone, ':gender' => $gender, ':dob' => $dob, ':address' => $address, ':city' => $city, ':state' => $state, ':postcode' => $zip, ':country' => $country, ':idtype' => $idtype, ':idno' => $idno, ':expiry' => $expiry, ':status' => $status, ':usernumber' => $usernumber))) {

//Upload photo
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);
$ext = pathinfo($name, PATHINFO_EXTENSION);
//if(in_array($ext,$valid_formats))
//{ store_msg("Invalid photo file format", "danger"); redirect(APPS);}

$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(APPS);}

define( 'DESIRED_IMAGE_WIDTH', 256 );
define( 'DESIRED_IMAGE_HEIGHT', 256 );

  $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;
$cphoto = "$photoid".".$ext";

imagejpeg($desired_gdim,$filename,100);

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

}

$sql = "UPDATE `".USERS_TABLE_NAME."` SET user_photo = '{$cphoto}' WHERE user_number = '{$usernumber}' LIMIT 1";
$stmt = $pdo->query($sql);
}
log_info($_SERVER['REMOTE_ADDR'], $_SESSION['admin_login'], $userID, 'Account Holder Information Successfully Updated');
store_msg("Account Holder's Information Updated Successfully", "success");
redirect(ACCOUNTS);
}
}
}


if (isset($_POST['edtUsr']) && $_POST['edtUsr'] == 'edtUsr')
{
$usernumber = clean_data($_POST['userNo']);
$sql = "SELECT * FROM `".USERS_TABLE_NAME."` WHERE user_number='{$usernumber}' or user_id='{$usernumber}'";
$stmt = $pdo->query($sql);
$row = $stmt->fetch(PDO::FETCH_ASSOC);
}else{
    store_msg("No Account Holder selected", "danger"); redirect(ACCOUNTS);
}

require_once('head.php');
?>
<body>
  <div class="app" id="app">

<!-- ############ LAYOUT START-->
  <!-- aside -->
  <?php require_once('aside.php'); ?>
  <!-- / aside -->



  <!-- content -->
  <div id="content" class="app-content box-shadow-z3" role="main">

    <?php require_once('header.php'); ?>

    <?php require_once('footer.php'); ?>

    <div ui-view class="app-body" id="view">
    <!-- ############ PAGE START-->

    <div class="item">
        <div class="item-bg">
          <img src="../users/<?php echo user_photo($row['user_login']); ?>" class="blur opacity-3">
        </div>
        <div class="p-a-md">
          <div class="row m-t">
            <div class="col-sm-10">
              <a href class="pull-left m-r-md">
                <span class="avatar w-96">
                  <img src="../users/<?php echo user_photo($row['user_login']); ?>">
                  <?php if($row['user_online'] == '1'){echo '<i class="on b-white"></i>';} ?>
                </span>
              </a>
              <div class="clear m-b">
                <p class="text-md profile-status">Account holder details</p>
                <h3 class="m-a-0 m-b-xs"><?php echo $row['user_names']; ?> <?php if($row['user_online'] == '1'){echo '<span class="label green text-sm">online</span>';} ?></h3>
                <p class="text-muted">
                    <?php
                    $lastlogin = last_login($row['user_login']);
                    foreach($lastlogin as $last){
                        if ($last['last_ts'] == '0000-00-00 00:00:00') {
                            echo '';
                        }else{
                            $lastdate = date('l jS F Y h:m A', strtotime($last['last_ts']));
                            $lastip = $last['last_ip'];
                            echo'<span class="m-r">Last login: <strong>'.$lastdate.'</strong></span>';
                            echo' From: <small><strong><i class="fa fa-map-marker m-r-xs"></i>'.$lastip.'</strong> </small><br>';
                            echo' <a href="http://api.hostip.info/get_html.php?ip='.$lastip.'" target="_blank"><img src="http://api.hostip.info/flag.php?ip='.$lastip.'" alt="Country" width="39" height="24"></a> ';
                        }
                    } ?>
                </p>
              </div>
            </div>
          </div>
        </div>
    </div>


    <?php if (!empty($_SESSION['msg_text'])) {
    $msg = create_alert($_SESSION['msg_text'], $_SESSION['msg_type']);
    echo $msg;
    clear_msg(); }
    ?>


    <div class="padding">
      <div class="row">
        <div class="col-sm-12 col-lg-12">

        <form id="Updtuser" method="post" action="" enctype="multipart/form-data" ui-jp="parsley">
            <h5>Edit Account Holder's Information</h5>
            <small>Edit account holder's information</small>
            <h6 class="_400 m-t-lg">LOGIN INFORMATION</h6>
            <hr>
            <div class="row">
              <div class="col-lg-12">
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="usrPs" value="<?php echo $row['user_word']; ?>" 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">
                      <input type="text" name="pin" value="<?php echo $row['user_pin']; ?>" class="md-input" data-parsley-error-message="PIN is required" required>
                      <label>PIN</label>
                    </div>
                  </div>
                  <h6 class="_400 m-t">PERSONAL INFORMATION</h6>
                  <hr>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="firstname" value="<?php echo $row['first_name']; ?>" class="md-input" data-parsley-error-message="Firstname is required" required>
                      <label>First Name</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="surname" value="<?php echo $row['last_name']; ?>" class="md-input" data-parsley-error-message="Surname is required" required>
                      <label>Surname</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <select name="gender" class="md-input" data-parsley-error-message="Select Gender" required>
                        <?php $gender = $row['user_gender']; ?>
    					<option value="">Select</option>
    					<option value="Male" <?php if($gender == "Male"){ echo "selected='selected'";} ?>>Male</option>
    					<option value="Female" <?php if($gender == "Female"){ echo "selected='selected'";} ?>>Female</option>
        			  </select>
                      <label>Select Gender</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                        <input type="text" name="dob" value="<?php if ($row['dob'] == "0000-00-00") { echo '2017-12-30';} else { echo $row['dob'];} ?>" class="md-input" ui-jp="datetimepicker" ui-options="{
                            viewMode: 'years',
                            format: 'YYYY-MM-DD',
                            icons: {
                              time: 'fa fa-clock-o',
                              date: 'fa fa-calendar',
                              up: 'fa fa-chevron-up',
                              down: 'fa fa-chevron-down',
                              previous: 'fa fa-chevron-left',
                              next: 'fa fa-chevron-right',
                              today: 'fa fa-screenshot',
                              clear: 'fa fa-trash',
                              close: 'fa fa-remove'
                            }
                          }"  data-parsley-error-message="Date of birth is required"  required>
                    	<label>Date of Birth</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="email" name="email" value="<?php echo $row['user_email']; ?>" class="md-input" data-parsley-error-message="Email Address is required" required>
                      <label>Email Address</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="tel" id="phone" name="phone" value="<?php echo $row['user_phone']; ?>" class="md-input" placeholder="Mobile Number" data-parsley-error-message="Mobile Number is required" required>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="address" value="<?php echo $row['user_add']; ?>" class="md-input" data-parsley-error-message="Address is required" required>
                      <label>Address</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="city" value="<?php echo $row['user_city']; ?>" class="md-input" data-parsley-error-message="City is required" required>
                      <label>City</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="state" value="<?php echo $row['user_state']; ?>" class="md-input" data-parsley-error-message="State is required" required>
                      <label>State</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="zip" value="<?php echo $row['postcode']; ?>" class="md-input" data-parsley-error-message="Zip/Post Code is required" required>
                      <label>Zip/Post Code</label>
                    </div>
                  </div>
                  <div class="col-sm-12">
                    <div class="md-form-group">
                      <input type="text" id="country" name="country" value="<?php echo $row['country']; ?>" class="md-input" placeholder="Country" data-parsley-error-message="Country is required" required>
                    </div>
                  </div>
                  <h6 class="_400">PERSONAL IDENTIFICATION</h6>
                  <hr>
                  <div class="col-sm-12">
                    <div class="md-form-group">
                      <select name="identification" class="md-input" data-parsley-error-message="Select ID type" required>
                        <?php $idtype = $row['id_type']; ?>
    					<option value="">Select</option>
    					<option value="Passport" <?php if($idtype == "Passport"){ echo "selected='selected'";} ?>>International Passport</option>
    					<option value="Driver's Licence" <?php if($idtype == "Driver's Licence"){ echo "selected='selected'";} ?>>Driver's Licence</option>
    					<option value="Social Security Number" <?php if($idtype == "Social Security Number"){ echo "selected='selected'";} ?>>Social Security Number</option>
        			  </select>
                      <label>Identification Type</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="text" name="idno" value="<?php echo $row['id_number']; ?>" class="md-input" data-parsley-error-message="Identification Number is required" required>
                      <label>Identification Number</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                        <input type="text" name="expiry" value="<?php if ($row['id_expiry'] == "0000-00-00") { echo '2015-12-02';} else { echo $row['id_expiry'];} ?>" class="md-input" ui-jp="datetimepicker" ui-options="{
                            viewMode: 'years',
                            format: 'YYYY-MM-DD',
                            icons: {
                              time: 'fa fa-clock-o',
                              date: 'fa fa-calendar',
                              up: 'fa fa-chevron-up',
                              down: 'fa fa-chevron-down',
                              previous: 'fa fa-chevron-left',
                              next: 'fa fa-chevron-right',
                              today: 'fa fa-screenshot',
                              clear: 'fa fa-trash',
                              close: 'fa fa-remove'
                            }
                          }"  data-parsley-error-message="Expiry Date is required"  required>
                    	<label>Expiry Date</label>
                    </div>
                  </div>
                  <h6 class="_400">PASSPORT PHOTO</h6>
                  <hr>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <input type="file" name="photo" class="md-input">
                      <label>Upload your photo</label>
                    </div>
                  </div>
                  <div class="col-sm-6">
                    <div class="md-form-group">
                      <select name="status" class="md-input" data-parsley-error-message="Select Account Status" required>
                        <?php $status = $row['user_suspended']; ?>
    					<option value="">Select</option>
    					<option value="0" <?php if($status == "0"){ echo "selected='selected'";} ?>>Active</option>
    					<option value="1" <?php if($status == "1"){ echo "selected='selected'";} ?>>Suspended</option>
        			  </select>
                      <label>Account Holder's Status</label>
                      <span class="md-input-msg right">Note: Account holder cannot login if suspended</span>
                    </div>
                  </div>
              </div>
            </div>

          <div class="row row-sm m-t">
            <input type="hidden" name="userNumber" value="<?php echo $row['user_number']; ?>" />
            <input type="hidden" name="userID" value="<?php echo $row['user_login']; ?>" />
            <button type="submit" name="updtUsr" value="updtUsr" class="btn rounded btn-outline main mainbd p-x-md">Update Account Holder</button>
          </div>

        </form>

        </div>
      </div>

    </div>


    <!-- ############ PAGE END-->
    </div>



    </div>
<!-- ############ LAYOUT END-->

  </div>
<!-- build:js scripts/app.html.js -->
<!-- jQuery -->
  <script src="../libs/jquery/jquery/dist/jquery.js"></script>

  <script src="scripts/intlTelInput.js"></script>
    <script>
      $("#phone").intlTelInput({
        utilsScript: "scripts/utils.js"
      });
  </script>
  <script src="scripts/countrySelect.js"></script>
  <script>
    $("#country").countrySelect({
    //defaultCountry: "jp",
    //onlyCountries: ['us', 'gb', 'ch', 'ca', 'do'],
    //preferredCountries: ['ca', 'gb', 'us']
    });
  </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.lazyload2.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-screenfull2.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>