<?php
  namespace App;
  use Illuminate\Support\Facades\DB;
  use PDO;
  class  MyUser {
      private $_login;
      private $_password;
      private const USER_TABLE = "Users";

      function getLogin() : string {
          return $this->_login;
      }

      function getPassword() : string {
         return $this->_password;
      }

      function setLogin(string $login) : void {
          $this->_login = $login;
      }

      function setPassword(string $password) : void {
          $this->_password = $password;
      }

      function __construct(string $login, string $password = null) {
          $this->_login = $login;
          $this->_password = $password;
      }

      function __destruct() {

      }

      function exists() : bool {
          $pdo = DB::connection()->getPdo();
          $req = $pdo->prepare('SELECT passwd FROM ' . self::USER_TABLE . ' WHERE login = :login');
          $req->bindValue(':login', $this->getLogin(), PDO::PARAM_STR);
          if (!$req->execute()) {
            throw new Exception('Problème requête');
          }
          if ($req->rowCount() == 0) {
            return false;
          }
          $res = $req->fetch();
          if (!password_verify($this->getPassword(), $res['passwd'])) {
            return false;
          }

          return true;

      }

      function create() : void {
          $pdo = DB::connection()->getPdo();
          $req = $pdo->prepare('INSERT INTO ' . self::USER_TABLE . ' (login, passwd) VALUES (:login, :passwd)');
          $req->bindValue(':login', $this->getLogin(), PDO::PARAM_STR);
          $req->bindValue(':passwd', password_hash($this->getPassword(), PASSWORD_DEFAULT), PDO::PARAM_STR);
          if (!$req->execute()) {
              throw new Exception('Problème requête');
          }
      }

      function changePassword() : void {
          $pdo = DB::connection()->getPdo();
          $req = $pdo->prepare('UPDATE ' . self::USER_TABLE . ' SET passwd = :passwd WHERE login = :login');
          $req->bindValue(':passwd', password_hash($this->getPassword(), PASSWORD_DEFAULT));
          $req->bindValue(':login', $this->getLogin());
          if (!$req->execute()) {
            throw new Exception('Problème requête');
          }

      }

      function delete() : void {
        $pdo = DB::connection()->getPdo();
        $req = $pdo->prepare('DELETE FROM Users WHERE login = :login');
        $req->bindValue(':login', $this->getLogin());
        if (!$req->execute()) {
          throw new Exception('Problème requête');
        }
      }

    }
