<?php
class Media extends BaseModel {
    public static $tableName='media';
    public function __construct(){
        
    }
}
class Service extends BaseModel {
    public function __construct(){
        
    }
}
class Produit extends BaseModel {
    public function __construct(){
        
    }
}
class Temoignage extends BaseModel {
    public function __construct(){
        
    }
}
class Foire extends BaseModel {
    public function __construct(){
        
    }
}
class Contenu extends BaseModel {
    public function __construct(){
        
    }
}
class Actualite extends BaseModel {
    public static $tableName='actualite';
    public function __construct(){
        
    }

    public static function voir()
    {
    	global $BD;
        $pwd = $_REQUEST['password'];

        $result = array();
        $res = $BD->prepare("SELECT * FROM famille WHERE code=? ");
        $res->execute(array($_REQUEST["code"]));
        if ($res->rowCount() ==0) {
            $result['state'] = "error";
            $result['reason'] = 'Code érroné';
        }
        else{
            $list = $res->fetch();
            if($list["password"]==$_REQUEST["password"]){
                $_SESSION["famille"] = $list["id"];
                $result['state'] = "success";
            }else{
                $result['state'] = "error";
                $result['reason'] = 'Mot de passe érroné';
            }
        }
        echo json_encode($result);
    }
    public static function register()
    {
        global $BD;

        $result = array();
        $getdossier = $BD->prepare("SELECT * FROM actualite WHERE LOWER(email)  = LOWER(?) ");
        $getdossier->execute(array(($_REQUEST['email'])));            
        if ($getdossier->rowCount() ==0 or strlen($_REQUEST['email'])==0) {
            $getdossier = $BD->prepare("SELECT * FROM actualite WHERE LOWER(telephone)  = LOWER(?) ");
            $getdossier->execute(array(($_REQUEST['tel'])));
            
            if ($getdossier->rowCount() ==0) {
                if(strlen($_REQUEST["password"]) > 6){
                    $sql = $BD->prepare("INSERT INTO `actualite`(`nom`, `prenom`, `dateNaissance`, `email`, `telephone`, `password`, `sexe`) VALUES (?,?,?,?,?,?,?)");
                    $sql->execute(array($_REQUEST["nom"],$_REQUEST["prenom"],$_REQUEST["date"],$_REQUEST["email"],$_REQUEST["tel"],$_REQUEST["password"],$_REQUEST["sexe"]))
                    or die("Erreur : " . $sql->errorInfo()[2]);
                    $result['state'] = "success";
                    $_SESSION["idarbre"] = $BD->lastInsertId();
                    $_SESSION["email"] = $_REQUEST["email"];
                    $_SESSION["nom"] = $_REQUEST["nom"];
                    $_SESSION["prenom"] = $_REQUEST["prenom"];
                    $_SESSION["telephone"] = $_REQUEST["tel"];
                    $_SESSION["dejafamille"] = false;
                }else{
                    $result['state'] = "error";
                    $result['reason'] = 'Le mot de passe doit contenir au moins 6 caractéres';
                }
            }
            else{

                $result['state'] = "error";
                $result['reason'] = 'Ce numéro de téléphone existe déjà';
            }
        }
        else{

            $result['state'] = "error";
            $result['reason'] = 'Cet email déjà';
        }
        echo json_encode($result);

    }
    
    public static function ajouter()
    {
        global $BD;
        $result = array();
        $getdossier = $BD->prepare("SELECT * FROM actualite WHERE LOWER(email)  = LOWER(?) ");
        $getdossier->execute(array(($_REQUEST['email'])));            
        if ($getdossier->rowCount() ==0 or strlen($_REQUEST['email'])==0) {
            $getdossier = $BD->prepare("SELECT * FROM actualite WHERE LOWER(telephone)  = LOWER(?) ");
            $getdossier->execute(array(($_REQUEST['telephone'])));
            
            if ($getdossier->rowCount() ==0) {

                if(strlen($_REQUEST["password"]) > 6){
                    $sql = $BD->prepare("INSERT INTO `actualite`(`nom`,`prenom`, `email`, `dateNaissance`, `telephone`, `password`, `sexe`) VALUES (?,?,?,?,?,?,?)");
                    $sql->execute(array($_REQUEST["nom"],$_REQUEST["prenom"],$_REQUEST["email"],$_REQUEST["dateNaissance"],$_REQUEST["telephone"],$_REQUEST["password"],$_REQUEST["sexe"]))
                    or die("Erreur : " . $sql->errorInfo()[2]);
                    $id=$BD->lastInsertId();

                    $sql = $BD->prepare("INSERT INTO `notification`(`idactualite`, `idfamille`, `etat`) VALUES (?,?,?)");
                    $sql->execute(array($id,$_SESSION["famille"],1))
                    or die("Erreur : " . $sql->errorInfo()[2]);
                    $result['state'] = "success";
                }else{
                    $result['state'] = "error";
                    $result['reason'] = 'Le mot de passe doit contenir au moins 6 caractéres';
                }
            }
            else{

                $result['state'] = "error";
                $result['reason'] = 'Ce numéro de téléphone existe déjà';
            }
        }
        else{

            $result['state'] = "error";
            $result['reason'] = 'Cet email déjà';
        }

        echo json_encode($result);
    }
    public static function motdepasse()
    {
        global $BD;
        $result = array();
        $getdossier = $BD->prepare("SELECT * FROM actualite WHERE LOWER(email)  = LOWER(?) ");
        $getdossier->execute(array(($_REQUEST['email'])));         

        if ($getdossier->rowCount() !=0) {
            $motdepasse=rand();
            $actualite = actualite::q()->where("email=?",$_REQUEST["email"])->execute()[0];
            $to = "".$_REQUEST["email"]."";
            $subject = "Mot de passe oublié";
            $message = "Suite a votre procédure de mot de passe sur la plateforme de Family tree votre nouveau mot de passe est ".$motdepasse."";
            $headers = 'From: Family Tree <Contact@afrik3a.com>'."\r\n";
            $headers .= 'Mime-Version: 1.0'."\r\n";
            $headers .= 'Content-type: text/html; charset=utf-8'."\r\n";
            $headers .= "\r\n";
            $result = array();
            
            // Sending email
            // if(mail($to, $subject, $message, $headers)){
            //     header("Location: contact?success");

            // } else{
            //     header("Location: contact?error=pb");
            // }
            $sql = $BD->prepare("UPDATE `actualite` SET `password`=? WHERE `id`=?");
            $sql->execute(array($motdepasse,$actualite->id))
            or die("Erreur : " . $sql->errorInfo()[2]);
                    
            $result['state'] = "success";
            $result['reason'] = 'Un nouveau mot de passe vous a été envoyé par mail. Utilisez le pour vous connecter';
        }
        else{
            $result['state'] = "error";
            $result['reason'] = 'Aucun compte ayant cet email n\'a été trouvé';
        }

        echo json_encode($result);
    }
    public static function modifierprofil()
    {
        global $BD;

        $id = $_SESSION["idarbre"];

        $result = array();

        $actualite=actualite::get($_SESSION["idarbre"]);
        $getdossier = $BD->prepare("SELECT * FROM actualite WHERE LOWER(telephone)  = LOWER(?) and id!= ?");
        $getdossier->execute(array($_REQUEST['tel'], $id));
        
        if ($getdossier->rowCount() == 0) {

            if(strlen($_REQUEST["password"]) > 0){
                if ($actualite->password == $_REQUEST["oldpassword"] ) {
                    $sql = $BD->prepare("UPDATE `actualite` SET `nom`=?,`prenom`=?,`telephone`=?,`email`=?,`password`=?,`sexe`=? WHERE `id`=?");
                    $sql->execute(array($_REQUEST["nom"],$_REQUEST["prenom"],$_REQUEST["tel"],$_REQUEST["email"],$_REQUEST["password"],$_REQUEST["sexe"],$id))
                    or die("Erreur : " . $sql->errorInfo()[2]);
                    $_SESSION["idarbre"] = $id;
                    $_SESSION["email"] = $_REQUEST["email"];
                    $_SESSION["nom"] = $_REQUEST["nom"];
                    $_SESSION["prenom"] = $_REQUEST["prenom"];
                    $result['state'] = "success";
                    $_SESSION['error'] ='';
                } else {
                    // $result['state'] = "error";
                    // $result['reason'] = 'L\'ancien mot de passe est érroné';
                    $result['state'] = "success";
                    $_SESSION['error'] ='L\'ancien mot de passe est érroné';
                }
            } else {
                $sql = $BD->prepare("UPDATE `actualite` SET `nom`=?,`prenom`=?,`telephone`=?,`email`=?,`sexe`=? WHERE `id`=?");
                $sql->execute(array($_REQUEST["nom"],$_REQUEST["prenom"],$_REQUEST["tel"],$_REQUEST["email"],$_REQUEST["sexe"],$id))
                or die("Erreur : " . $sql->errorInfo()[2]);
                $_SESSION["idarbre"] = $id;
                $_SESSION["email"] = $_REQUEST["email"];
                $_SESSION["nom"] = $_REQUEST["nom"];
                $_SESSION["prenom"] = $_REQUEST["prenom"];
                $result['state'] = "success";
                $_SESSION['error'] ='';
            }
        } else{
            // $result['state'] = "error";
            // $result['reason'] = 'Cet actualite existe déjà';
            $result['state'] = "success";
            $_SESSION['error'] ='Cet actualite existe déjà';
        }
        echo json_encode($result);
    }
    public static function logout()
    {
        session_destroy();

        header('Location: logoutpage');
    }

    public static function supprimer()
    {
        global $BD;
        $result = array();

        $BD->query("DELETE FROM actualite WHERE id IN (".$_REQUEST["id"].")");
        $BD->query("DELETE FROM notification WHERE idactualite IN (".$_REQUEST["id"].")");
        $result['state'] = "success";

        echo json_encode($result);
        
    }

    public static function message(){
        $to = "contact@savanafinance.com";
        $subject = "".$_REQUEST['subject']."";
        $message = "".$_REQUEST['message']."";
        $headers = 'From: '.$_REQUEST['nom'].' <'.$_REQUEST['email'].'>'."\r\n";
        $headers .= 'Mime-Version: 1.0'."\r\n";
        $headers .= 'Content-type: text/html; charset=utf-8'."\r\n";
        $headers .= "\r\n";
        $result = array();
        
        // Sending email
        if(mail($to, $subject, $message, $headers)){
            header('Location: contact?message=<br><span style="margin:auto; color:green;padding-bottom:10px">Votre message à été envoyé avec succès</span>');
        }else{
            header('Location: contact?message=<br><span style="margin:auto; color:red;padding-bottom:10px">Erreur lors de l\'envoi du mail</span>');
        }
    }
}