<?php 

$max_password = 20;

$dir = '../';

require_once $dir.'includes/main.php';

$errors = array();

// check login
if(!isset($user_id)){
   $errors[] = LOG_IN;
}

$oldpassword = clean($_POST['old_password']);
$newpassword = clean($_POST['new_password']);

// check password
if(empty($oldpassword)){
   $errors[] = "Old password is required";
}

if(strlen($oldpassword) > $max_password){
   $errors[] = "Old password cannot be more than $max_password characters";
}

if(empty($newpassword)){
   $errors[] = "New password is required";
}

if(strlen($newpassword) > $max_password){
   $errors[] = "New password cannot be more than $max_password characters";
}

$hashed_oldpassword = sha1($oldpassword);

if($u['password'] != $hashed_oldpassword){
   $errors[] = "Old password is incorrect";
}

//check errors
if(!empty($errors)){

   ex_messages($errors);

}else{

   $hashed_password = sha1($newpassword);

   if(query("UPDATE users SET password = '{$hashed_password}' WHERE id = '{$user_id}' LIMIT 1")){

      setcookie('password', $hashed_password, $t + (60*60*24*30*12), '/');

      ex_messages(['Account password has been updated successfully']);

   }else{

      ex_messages([ERROR_DATABASE]);

   }

}

?>