<?php require('includes/config.php');
// se effettuato l'accesso reindirizza alla pagina dei membri
if( $user->is_logged_in() ){ header('Location: memberpage.php'); exit(); }
// se il modulo è stato inviato, elaboralo
if(isset($_POST['submit'])){
    if (!isset($_POST['username'])) $error[] = "Please fill out all fields";
    if (!isset($_POST['email'])) $error[] = "Please fill out all fields";
    if (!isset($_POST['password'])) $error[] = "Please fill out all fields";
    $username = $_POST['username'];
// validazione
    if(!$user->isValidUsername($username)){
        $error[] = 'I nomi utente devono contenere almeno 3 caratteri alfanumerici';
    } else {
        $stmt = $db->prepare('SELECT username FROM members WHERE username = :username');
        $stmt->execute(array(':username' => $username));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!empty($row['username'])){
            $error[] = 'Nome inserito già in uso.';
        }
    }
    if(strlen($_POST['password']) < 3){
        $error[] = 'Password troppo corta.';
    }
    if(strlen($_POST['passwordConfirm']) < 3){
        $error[] = 'La password confermata è troppo corta';
    }
    if($_POST['password'] != $_POST['passwordConfirm']){
        $error[] = 'le password non corrispondono';
    }
    //validazione email
    $email = htmlspecialchars_decode($_POST['email'], ENT_QUOTES);
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        $error[] = 'Inserisci un indirizzo email valido.';
    } else {
        $stmt = $db->prepare('SELECT email FROM members WHERE email = :email');
        $stmt->execute(array(':email' => $email));
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!empty($row['email'])){
            $error[] = 'Email inserita già in uso.';
        }
    }
// se non sono stati creati errori, continua
    if(!isset($error)){
        //hash the password
        $hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
        //create the activasion code
        $activasion = md5(uniqid(rand(),true));
        try {
// inserisce nel database con un'istruzione preparata
class UserModel {
 
   protected $table="tabella_utenti";
 
   protected $default_values=
      [
         'username'=>['field'=>'username','default'=>'','not_null'=>true,'filter'=>'sanatize_string','conditions'=>['unique']],
         'password'=>['field'=>'password','default'=>'','not_null'=>true,'filter'=>'hash'],
         'email'=>['field'=>'email','not_null'=>true,'default'=>'','filter'=>'validation_email','conditions'=>['unique']],
         'active'=>['field'=>'','not_null'=>true,'default'=>false,'filter'=>'boolean'],
         'ruolo'=>['field'=>'','not_null'=>true,'default'=>'general_user','filter'=>'string']
      ];
   public $data=[];
   public static function newUser(){
      return (new self);
   }
      public function BindConnQuery($bind,$type){
      $this->stmt=$this->mysqli->prepare($this->query);
      if($this->stmt->param_count != count($bind)){
          //return [];
      }
      $callArgs = array();
      foreach($bind as $index => $arg) {
          $callArgs[$index] = &$bind[$index];
      }
      try {
          array_unshift($callArgs, $type);
          call_user_func_array(array($this->stmt, 'bind_param'), $callArgs);
          $this->stmt->execute();
      }
      catch (Exception $e) {
          print_r($e);
          die;
      }
  }
   private function filters($data,$config){
      //condizioni qui dentro
   }
}
            $stmt->execute(array(
                ':username' => $username,
                ':password' => $hashedpassword,
                ':email' => $email,
                ':active' => $activasion
            ));
            $id = $db->lastInsertId('memberID');
            //invia email
            $to = $_POST['email'];
            $subject = "Registrazione confermata";
            $body = "<p>Registrazione avvenuta con successo.</p>
            <p>Per attivare il tuo account, clicca sul link: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>
            <p>Saluti, Davide Marcellino</p>";
            $mail = new Mail();
            $mail->setFrom(SITEEMAIL);
            $mail->addAddress($to);
            $mail->subject($subject);
            $mail->body($body);
            $mail->send();
            // reindirizza alla pagina dell'indice
            header('Location: index.php?action=joined');
            exit;
        // else cattura l'eccezione e mostra l'errore.
        } catch(PDOException $e) {
            $error[] = $e->getMessage();
        }
    }
}
// definisce il titolo della pagina
$title = 'Demo';
// include modello di intestazione
require('layout/header.php');
?>