<?php

session_start();
include ('includes/database.php');
include ('includes/functions.php');

$conn = new Functions();

if(!empty($_POST['old_password']) AND !empty($_POST['new_password'])) {
    $old_password = $_POST['old_password'];
    $new_password = $_POST['new_password'];
    $username = $_POST['username'];
    

     //check for password strength or validity
     if(!$conn->Checkpassword($new_password)){
        echo "<script>
        $(function () { //ready
                  toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                  toastr.error('Password must include one uppercase letter, one lowercase letter, one number, one special character such as $ or % and length should be between 6 and 16');
              });
        </script>";
        return false;
    }


    //check if old password matches the one in database
    $sql = "SELECT * FROM admin WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":username", $username);
    $result = $conn->fetchSingle();
    $db_password = $result->password;
    

    $existing_password = $conn->password_check($old_password, $db_password);
    $crypt_new_password = $conn->password_check($new_password, $db_password);

    if(!$existing_password){
        echo "<script>
        $(function () { //ready
                  toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                  toastr.error('Old Password Does Not Match With The One We Have In Our Record');
              });
        </script>";
        return false;
    }

    if($crypt_new_password == $new_password){
        echo "<script>
        $(function () { //ready
                  toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                  toastr.error('You Cannot Use Thesame Password For Old And New');
              });
        </script>";
        return false;
    }


    //all checks passed, update password in database
    $sql = "UPDATE admin SET password =:password WHERE username =:username";
    $conn->query($sql);
    $conn->bind(":password", $conn->Password_Encryption($new_password));
    $conn->bind(":username", $username);

    if($conn->execute()){
        echo "<script>
    $(function () { //ready
              toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
              toastr.success('Password Updated Successfully');
          });
    </script> <meta http-equiv='refresh' content='5; index'>";
    }else{
        echo "<script>
        $(function () { //ready
                  toastr.options.progressBar = true, toastr.options.preventDuplicates = true,
                  toastr.error('An Error ocurred While Updating Password');
              });
        </script>";
    }

}
?>