<?php
class Temoignage extends BaseModel {
    public static $tableName='temoignage';
    public function __construct(){
        
    }


    public static function ajouter()
    {
        global $BD;        
        
		
        $getid = $BD->query("SELECT max(id) as idcat FROM temoignage");
        if ($getid->rowCount() == 0) {
            $id=1;
        }
        else{
            $getiid = $getid->fetch();
            $id=$getiid["idcat"]+1;
        }

		if (isset($_FILES["fichier"]) AND strlen($_FILES["fichier"]["name"])>0) {
			$folder = '../media/';
			$tmp_name = $_FILES["fichier"]["tmp_name"];

			$name = $_FILES["fichier"]["name"];

			$img = pathinfo($_FILES["fichier"]['name']);
			$cv = "temoignage".$id.'.'.$img["extension"];
            move_uploaded_file($tmp_name, $folder.$cv);
        }
        else{
            $cv = '';            
        }

        $insert = $BD->prepare("INSERT INTO `temoignage`(`id`, `nom`, `profession`, `message`, `image`) VALUES (?,?,?,?,?)");
        $insert->execute(array($id,$_REQUEST['nom'],$_REQUEST['profession'],$_REQUEST['message'],$cv));
        header("Location: ../temoignage");
    }
    
    public static function modifier()
    {
        global $BD;
        $id = $_REQUEST['id'];         
        
        if (isset($_FILES["fichier"]) AND strlen($_FILES["fichier"]["name"])>0) {
            $folder = '../media/';
            $tmp_name = $_FILES["fichier"]["tmp_name"];

            $name = $_FILES["fichier"]["name"];

            $img = pathinfo($_FILES["fichier"]['name']);
            $cv = "temoignage".$id.'.'.$img["extension"];
            move_uploaded_file($tmp_name, $folder.$cv);

            $insert = $BD->prepare("UPDATE `temoignage` SET `image`=? WHERE id=?");
            $insert->execute(array($cv,$id));
        }
      
        
        $insert = $BD->prepare("UPDATE `temoignage` SET `nom`=?, `profession`=?, `message`=? WHERE id=?");
        $insert->execute(array($_REQUEST['nom'],$_REQUEST['profession'],$_REQUEST['message'],$id));
        header("Location: ../temoignage");
        
    }

    public static function supprimer()
    {
        global $BD;

        $BD->query("DELETE FROM temoignage WHERE id IN (".$_REQUEST["id"].")");

		header("Location: ../temoignage");
    }

}