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


    public static function ajouter()
    {
        global $BD;        
        
		
        $getid = $BD->query("SELECT max(id) as idcat FROM service");
        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/service/';
			$tmp_name = $_FILES["fichier"]["tmp_name"];

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

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

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

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

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

            $insert = $BD->prepare("UPDATE `service` SET `icone`=? WHERE id=?");
            $insert->execute(array($icone,$id));
        }

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

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

            $insert = $BD->prepare("UPDATE `service` SET `image`=? WHERE id=?");
            $insert->execute(array($couverture,$id));
        }

        $insert = $BD->prepare("UPDATE `service` SET `intitule`=?,`description`=? WHERE id=?");
        $insert->execute(array($_REQUEST['titre'],$_REQUEST['description'],$id));
        header("Location: ../service");
        
    }

    public static function supprimer()
    {
        global $BD;

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

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

}