<?php 
 
  $root = realpath($_SERVER["DOCUMENT_ROOT"]);
  $db_path = $root."/db/ggdworkshop.db";
  $schema_path = $root."/db/schema.sql";

  class DB{
    private $pdo;

    public function connect(){
      if($this->pdo == null){
        global $db_path;
        $this->pdo = new \PDO('sqlite:'.$db_path);
        $this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
      }
      return $this->pdo;
    }

    public function schema($schema_file){
      $sql = file_get_contents($schema_file);
      $this->pdo->exec($sql);
    }

    public function insert($registro){
      $columns = implode(",", array_keys($registro));
      echo $columns;
      $sql = "INSERT INTO Registro ($columns)"
              .' VALUES (:nombre,:apellido,:titulo,:afiliacion,:ciudad,:pais,:email,:fechaLlegada,'
              .':fechaPartida,:financiacion,:invitado,:cartaInvitacion,:roomingPref,:roommate,:fechaRegistro);';
      echo $sql;
      $stmt = $this->pdo->prepare($sql);  
      $stmt->execute([
        ':nombre' => $registro['nombre'],
        ':apellido' => $registro['apellido'],
        ':titulo' => $registro['titulo'],
        ':afiliacion' => $registro['afiliacion'],
        ':ciudad' => $registro['ciudad'],
        ':pais' => $registro['pais'],
        ':email' => $registro['email'],
        ':fechaLlegada' => $registro['fechaLlegada'],
        ':fechaPartida' => $registro['fechaPartida'],
        ':financiacion' => $registro['financiacion'],
        ':invitado' => $registro['invitado'],
        ':cartaInvitacion' => $registro['cartaInvitacion'],
        ':roomingPref' => $registro['roomingPref'],
        ':roommate' => $registro['roommate'],
        ':fechaRegistro' => $registro['fechaRegistro']
        ]);
      return $this->pdo->lastInsertId();
  
    }
    public function getAll(){
      $stmt = $this->pdo->prepare("SELECT * FROM Registro");
      $stmt -> execute();
      return $stmt->fetchAll(\PDO::FETCH_BOTH);

    }



  } 

  $db = new DB();
  $db->connect();
  $db->schema($schema_path);


    
?>