1
0
Fork 0
This commit is contained in:
p1907961 2021-01-05 17:53:26 +01:00
parent 303075c495
commit 240492d94f
11 changed files with 325 additions and 36 deletions

View file

@ -1,10 +1,55 @@
<?php <?php
if($_SESSION['USER']->isLoggedIn()) { if($_SESSION['USER']->isLoggedIn()) {
$accomodationType = ['Hôtel', 'Gîte','Camping','Villa en location'];
$alert = '';
if(isset($path[1])) { if(isset($path[1])) {
switch ($path[1]) { switch ($path[1]) {
case 'add': case 'add':
if(!$_SESSION['USER']->getAccomodationId()) if(!$_SESSION['USER']->getAccomodationId())
{ {
/*
* Creating Accomodation
*/
if(isset(
$_POST['accomodationName'],
$_POST['postalCode'],
$_POST['address'],
$_POST['accomodationType']
)){
$availableServices = AccomodationServices::getAll();
$re_name = '/^[a-zA-Z -\'?*éàèôê0-9"()+&]{1,}$/';
$re_cp = '/[0-9]{5}/';
/*
* Checking inputs
*/
if(!preg_match($re_name, $_POST['accomodationName']) || !preg_match($re_cp, $_POST['postalCode']) || ((isset($_POST["accomodationService"]) && gettype($_POST['accomodationService']) === 'array' && array_diff($_POST["accomodationService"], $availableServices))))
{
$alert = alert('danger','Le formulaire est invalide');
}else{
if(Accomodation::insertUser($_SESSION['USER'], array(
"name" => $_POST['accomodationName'],
"address" => $_POST['address'],
"postalCode" => $_POST['postalCode'],
"type" => $_POST['accomodationType'])) != false){
/*
* Update users information
*/
$_SESSION['USER']->update();
/*
* Insert ok
*/
$accomodation = Accomodation::fetchByUser($_SESSION['USER']);
$accomodation->setServices($_POST["accomodationService"]);
$alert = alert('success','Ajout du logement réussi.');
}else{
$alert = alert('danger','Erreur lors de l\'insertion du logement.');
}
}
}
$services = AccomodationServices::fetch(); $services = AccomodationServices::fetch();
require_once(VIEW_PATH.$path[1] . '_' . $path[0].'.php'); require_once(VIEW_PATH.$path[1] . '_' . $path[0].'.php');
}else{ }else{
@ -14,6 +59,8 @@ if($_SESSION['USER']->isLoggedIn()) {
case 'edit': case 'edit':
if($_SESSION['USER']->getAccomodationId()) if($_SESSION['USER']->getAccomodationId())
{ {
$accomodation = Accomodation::fetchByuser($_SESSION['USER']);
$services = AccomodationServices::fetch();
require_once(VIEW_PATH.$path[1] . '_' . $path[0].'.php'); require_once(VIEW_PATH.$path[1] . '_' . $path[0].'.php');
}else{ }else{
redirect(); redirect();

View file

@ -13,7 +13,6 @@ if(!$_SESSION['USER']->isLoggedIn() && !isset($path[1])) {
/* /*
* Successful login * Successful login
*/ */
$_SESSION['USER'] = $userArray[0]; // Pass the returned User type data into Session $_SESSION['USER'] = $userArray[0]; // Pass the returned User type data into Session
redirect(); redirect();
}else{ }else{

View file

@ -20,6 +20,19 @@ class Accomodation extends Model
} }
return $this; return $this;
} }
public static function insertUser(User $user, $data): bool
{
$inserted = Accomodation::insert($data);
if($inserted !== false){
/*
* User foreign key
*/
$query = 'UPDATE User SET AccomodationId=? WHERE email=?;';
$q = Accomodation::$db->prepare($query);
return ($q->execute([Accomodation::$db->lastInsertId(), $user->getEmail()]) == true);
}
return false;
}
public static function fetchByUser(User $user) public static function fetchByUser(User $user)
{ {
@ -31,4 +44,73 @@ class Accomodation extends Model
} }
return false; return false;
} }
public static function fetchById(int $id)
{
$data = Accomodation::fetch(array(['id','=', $id]));
if(count($data) === 1){
return $data[0];
}
return false;
}
public function getName()
{
return $this->data['name'];
}
public function getAddress()
{
return $this->data['address'];
}
public function getPostalCode()
{
return $this->data['postalCode'];
}
public function getType()
{
return $this->data['type'];
}
public function getServices()
{
$out = [];
if(isset($this->data['id'])){
$query = 'SELECT AccomodationServicesName FROM _AccomodationServices WHERE AccomodationId = ?;';
$q = Accomodation::$db->prepare($query);
$q->execute([$this->data['id']]);
forEach($q->fetchAll(PDO::FETCH_ASSOC) as $item){
$out[] = $item['AccomodationServicesName'];
}
return $out;
}
return false;
}
public function setServices(array $names)
{
/*
* Clear & Add
*/
if(isset($this->data['id'])){
$query = 'DELETE FROM _AccomodationServices WHERE AccomodationId = ?;';
$q = Accomodation::$db->prepare($query);
if($q->execute([$this->data['id']])){
/*
* Add
*/
if(!empty($names)){
$args = [];
$insertquery = 'INSERT INTO _AccomodationServices VALUES ';
$s = array_fill(0, count($names), '(?,?)');
$insertquery .= join(',', $s) . ';';
forEach($names as $name){
$args[] = $this->data['id'];
$args[] = $name;
}
$q = Accomodation::$db->prepare($insertquery);
return ($q->execute($args) == true);
}
return true;
}
}
return false;
}
} }

View file

@ -20,6 +20,14 @@ class AccomodationServices extends Model
} }
return $this; return $this;
} }
public static function getAll(): array
{
$out = [];
forEach(AccomodationServices::fetch() as $item){
$out[] = $item->getName();
}
return $out;
}
public function getName(): string public function getName(): string
{ {

View file

@ -1,4 +1,19 @@
<?php <?php
/*
* Getters
*/
function getGet($name, $default = NULL){
if(isset($_GET[$name])){
return $_GET[$name];
}
return $default;
}
function getPost($name, $default = NULL){
if(isset($_POST[$name])){
return $_POST[$name];
}
return $default;
}
/* /*
* URL & Redirection * URL & Redirection
*/ */
@ -15,10 +30,27 @@ function redirect($route = WEBSITE_DEFAULT_PATH){
function assetsPath($path, $level = 0){ function assetsPath($path, $level = 0){
return str_repeat('../', $level) . $path; return str_repeat('../', $level) . $path;
} }
# Alert generator
function alert($status , $msg){
switch($status){
case 'primary':
case 'secondary':
case 'success':
case 'danger':
case 'warning':
case 'info':
case 'light':
case 'dark':
return "<div class='alert alert-" .$status. "' role='alert'>" .htmlspecialchars($msg). "</div>";
break;
default:
throw new \Exception("Status d'alerte invalide");
}
}
# Navbar button render # Navbar button render
function navItem($name, $path){ function navItem($name, $path){
$acc = ''; $acc = '';
if(($_SERVER['REDIRECT_URL'] === WEBSITE_PATH . $path) || ($path === ($_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER["SERVER_NAME"] . $_SERVER["REDIRECT_URL"]))){ if(($_SERVER['REQUEST_URI'] === WEBSITE_PATH . $path) || ($path === ($_SERVER["REQUEST_SCHEME"] . '://' . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"]))){
$acc = 'active'; $acc = 'active';
} }
return '<li class="nav-item"><a class="nav-link ' .$acc. '" aria-current="page" href="' .htmlspecialchars($path). '">' .htmlspecialchars($name). '</a></li>'; return '<li class="nav-item"><a class="nav-link ' .$acc. '" aria-current="page" href="' .htmlspecialchars($path). '">' .htmlspecialchars($name). '</a></li>';

View file

@ -18,12 +18,12 @@ class Model {
Model::$db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD); Model::$db = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USER, DB_PASSWORD);
Model::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); Model::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(Exception $e){ } catch(Exception $e){
var_dump($e); die($e);
} }
} }
} }
/* /*
* GET/SELECT Query * Fetch
*/ */
public static function fetch($filters = []): array public static function fetch($filters = []): array
{ {
@ -55,6 +55,35 @@ class Model {
} }
return $output; return $output;
} }
/*
* Insert
*/
public static function insert($data){
$query = 'INSERT INTO ' . get_called_class() . ' (';
$_col = get_called_class()::getColumns();
$c = 0;
$args = [];
if($data !== null){
forEach($data as $key=>$value){
if(!key_exists($key, $_col)){
throw new Exception('Invalid data entry: ' . $key);
}else{
$args[] = $value;
if($c+1 === sizeof($data)){
$query .= $key . ') VALUES ( ' . join(',',array_fill(0, sizeof($data), '?')) . ' );';
}else{
$query .= $key . ', ';
}
$c++;
}
}
$q = Model::$db->prepare($query);
return ($q->execute($args) == true);
}
return false;
}
protected function getColumns(): array protected function getColumns(): array
{ {
if(!isset(get_called_class()::$column[get_called_class()])) { if(!isset(get_called_class()::$column[get_called_class()])) {

View file

@ -8,31 +8,34 @@ require_once('template/head.php');
<div class="container-fluid section"> <div class="container-fluid section">
<form action="" method="POST"> <form action="" method="POST">
<div class="row justify-content-md-center"> <div class="row justify-content-md-center">
<?=$alert?>
<div class="col col-lg-3"> <div class="col col-lg-3">
<div class="form-group"> <div class="form-group">
<label for="exampleInputEmail1">Donnez un nom à votre hebergement</label> <label for="exampleInputEmail1">Donnez un nom à votre hebergement</label>
<input type="text" class="form-control" name="accomodationName" id="accomodationName" aria-describedby="accomodationName" placeholder="Enter a name"> <input type="text" class="form-control" name="accomodationName" id="accomodationName" aria-describedby="accomodationName" placeholder="Le X" value="<?=htmlspecialchars(getPost('accomodationName'))?>">
<small id="accomodationName" class="form-text text-muted">We'll never share your email with anyone else.</small> <!-- <small id="accomodationName" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div> </div>
<div class="form-group"> <div class="form-group">
<label for="exampleInputPassword1">Password</label> <label for="exampleInputPassword1">Code Postal</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password"> <input type="text" class="form-control" name="postalCode" id="postalCode" placeholder="69100" value="<?=htmlspecialchars(getPost('postalCode'))?>">
</div> </div>
<div class="form-check"> <div class="form-group">
<input type="checkbox" class="form-check-input" id="exampleCheck1"> <label for="exampleInputPassword1">Adresse</label>
<label class="form-check-label" for="exampleCheck1">Check me out</label> <input type="text" class="form-control" name="address" id="address" placeholder="" value="<?=htmlspecialchars(getPost('address'))?>">
</div> </div>
</div> </div>
<div class="col-md-auto"></div> <div class="col-md-auto"></div>
<div class="col col-lg-3"> <div class="col col-lg-3">
<div class="form-group"> <div class="form-group">
<label for="typeSelect">Sélectionnez un type d'hébergement</label> <label for="typeSelect">Sélectionnez un type d'hébergement</label>
<select class="form-control" id="typeSelect"> <select class="form-control" name="accomodationType" id="typeSelect">
<option>Hôtel</option> <?php
<option>2</option> foreach ($accomodationType as $type){
<option>3</option> ?>
<option>4</option> <option><?=$type?></option>
<option>5</option> <?php
}
?>
</select> </select>
</div> </div>
<div class="form-group"> <div class="form-group">
@ -42,13 +45,13 @@ require_once('template/head.php');
foreach ($services as $service){ foreach ($services as $service){
$c++; $c++;
?><div class="form-check form-check-inline"> ?><div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" id="inlineCheckbox<?=$c?>" value="<?=htmlspecialchars($service->getName())?>"> <input class="form-check-input" type="checkbox" name='accomodationService[]' id="inlineCheckbox<?=$c?>" value="<?=htmlspecialchars($service->getName())?>">
<label class="form-check-label" for="inlineCheckbox<?=$c?>"><?=htmlspecialchars($service->getName())?></label> <label class="form-check-label" for="inlineCheckbox<?=$c?>"><?=htmlspecialchars($service->getName())?></label>
</div> </div>
<?php <?php
} }
?> ?>
</div> </div><br>
<button type="submit" class="btn btn-primary">Ajouter</button> <button type="submit" class="btn btn-primary">Ajouter</button>
</div> </div>
</div> </div>

View file

@ -1,7 +1,62 @@
<?php <?php
require_once('template/head.php'); require_once('template/head.php');
?> ?>
<div class="container-fluid section">
<h1>Bienvenue M. <?=htmlspecialchars(strtoupper($_SESSION['USER']->getLastName()))?>,</h1>
<h2>Ici vous pouvez éditer votre hébérgement.</h2>
</div>
<div class="container-fluid section">
<form action="" method="POST">
<div class="row justify-content-md-center">
<?=$alert?>
<div class="col col-lg-3">
<div class="form-group">
<label for="exampleInputEmail1">Donnez un nom à votre hebergement</label>
<input type="text" class="form-control" name="accomodationName" id="accomodationName" aria-describedby="accomodationName" placeholder="Le X" value="<?=htmlspecialchars($accomodation->getName())?>">
<!-- <small id="accomodationName" class="form-text text-muted">We'll never share your email with anyone else.</small> -->
</div>
<div class="form-group">
<label for="exampleInputPassword1">Code Postal</label>
<input type="text" class="form-control" name="postalCode" id="postalCode" placeholder="69100" value="<?=htmlspecialchars($accomodation->getPostalCode())?>">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Adresse</label>
<input type="text" class="form-control" name="address" id="address" placeholder="" value="<?=htmlspecialchars($accomodation->getAddress())?>">
</div>
</div>
<div class="col-md-auto"></div>
<div class="col col-lg-3">
<div class="form-group">
<label for="typeSelect">Sélectionnez un type d'hébergement</label>
<select class="form-control" name="accomodationType" id="typeSelect">
<?php
foreach ($accomodationType as $type){
?>
<option<?php if($type === $accomodation->getType()){ echo ' selected="selected"'; } ?>><?=$type?></option>
<?php
}
?>
</select>
</div>
<div class="form-group">
<label for="typeSelect">Quels services proposez-vous ?</label><br>
<?php
$c = 0;
foreach ($services as $service){
$c++;
?><div class="form-check form-check-inline">
<input class="form-check-input" type="checkbox" name='accomodationService[]' id="inlineCheckbox<?=$c?>" value="<?=htmlspecialchars($service->getName())?>">
<label class="form-check-label" for="inlineCheckbox<?=$c?>"><?=htmlspecialchars($service->getName())?></label>
</div>
<?php
}
?>
</div><br>
<button type="submit" class="btn btn-primary">Ajouter</button>
</div>
</div>
</form>
</div>
<?php <?php
require_once('template/footer.php'); require_once('template/footer.php');
?> ?>

View file

@ -1,5 +1,6 @@
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" <script
integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" type="text/javascript"
crossorigin="anonymous"></script> src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.0.0/mdb.min.js"
></script>
</body> </body>
</html> </html>

View file

@ -6,8 +6,21 @@
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="<?=assetsPath("assets/css/main.css", $assetsLevel);?>"> <link rel="stylesheet" href="<?=assetsPath("assets/css/main.css", $assetsLevel);?>">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" <!-- Font Awesome -->
integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <link
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
rel="stylesheet"
/>
<!-- Google Fonts -->
<link
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
rel="stylesheet"
/>
<!-- MDB -->
<link
href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.0.0/mdb.min.css"
rel="stylesheet"
/>
<title> - <?= WEBSITE_NAME ?></title> <title> - <?= WEBSITE_NAME ?></title>
</head> </head>
<body> <body>

View file

@ -3,7 +3,7 @@
?> ?>
<nav class="navbar navbar-expand-lg navbar-light bg-light"> <nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid"> <div class="container-fluid">
<a class="navbar-brand" href="#"><?= WEBSITE_NAME; ?></a> <a class="navbar-brand" href="<?=genURL('index');?>"><?= WEBSITE_NAME; ?></a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText" <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarText"
aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation"> aria-controls="navbarText" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span> <span class="navbar-toggler-icon"></span>
@ -17,6 +17,7 @@
if(!$_SESSION['USER']->getAccomodationId()){ if(!$_SESSION['USER']->getAccomodationId()){
echo navItem('Ajout Hebergement',genURL('accomodation/add')); echo navItem('Ajout Hebergement',genURL('accomodation/add'));
} else { } else {
echo navItem('Gestion des disponibilités', genURL('accomodation/date'));
echo navItem('Edition de l\'hebergement', genURL('accomodation/edit')); echo navItem('Edition de l\'hebergement', genURL('accomodation/edit'));
} }
break; break;
@ -28,17 +29,36 @@
echo navItem('Login',genURL('login')); echo navItem('Login',genURL('login'));
} }
?> ?>
</ul> </ul>
<span class="navbar-text">
<?php <?php
if($_SESSION['USER']->isLoggedIn()){ if($_SESSION['USER']->isLoggedIn()){
?> ?>
M. <?=htmlspecialchars(strtoupper($_SESSION['USER']->getLastName()))?> <?=htmlspecialchars($_SESSION['USER']->getFirstName())?> <ul class="navbar-nav d-flex flex-row">
<a href="<?=genURL('logout')?>">Déconnexion</a> <li class="nav-item me-3 me-lg-0 dropdown">
<a
class="nav-link dropdown-toggle"
href="#"
id="navbarDropdown"
role="button"
data-mdb-toggle="dropdown"
aria-expanded="false"
>
<i class="fas fa-user"></i>
</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<li><h6 class="dropdown-header"><?=htmlspecialchars(strtoupper($_SESSION['USER']->getLastName()))?> <?=htmlspecialchars($_SESSION['USER']->getFirstName())?></h6></li>
<!-- <li><h6 class="dropdown-header"><?=htmlspecialchars(strtoupper($_SESSION['USER']->getType()))?></h6></li> -->
<li><hr class="dropdown-divider" /></li>
<li>
<a class="dropdown-item" href="<?=genURL('logout')?>">Déconnexion</a>
</li>
</ul>
</li>
</ul>
<?php <?php
} }
?> ?>
</span>
</div> </div>
</div> </div>
</nav> </nav>