<?php

include 'auth-validate.php';
include '../../db.php';

@session_start();


//pull auth parameters
$password_old = isset($_REQUEST['password_old']) ? $_REQUEST['password_old'] : null;
$password_new = isset($_REQUEST['password_new']) ? $_REQUEST['password_new'] : null;


//make sure parameters are present
if(!$password_old || !$password_new)
{
	http_response_code(400);
	echo 'password missing';
	return;
}

//pull info on user from database
$stmt_file = $dbh->prepare("SELECT password FROM user WHERE id_user=:id_user");
$stmt_file->bindValue(':id_user', $_SESSION['id_user']);
$stmt_file->execute();
$rows = $stmt_file->fetchAll(PDO::FETCH_ASSOC);

//check if user missing
if(!count($rows))
{
	http_response_code(404);
	echo 'user not found';
	return;
}

//validate password entered
if(!password_verify($password_old, $rows[0]['password']))
{
	http_response_code(403);
	echo 'invalid old password';
	return;
}


$stmt_file = $dbh->prepare("UPDATE user SET password = :password WHERE id_user = :id_user");
$stmt_file->bindValue(':id_user', $_SESSION['id_user']);
$stmt_file->bindValue(':password', password_hash($password_new));
$stmt_file->execute();
$rows = $stmt_file->fetchAll(PDO::FETCH_ASSOC);


echo 'OK';

?>