<?php
class Document extends BaseModel
{
    public static $tableName = 'document';
    public function __construct()
    {

    }

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

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

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

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

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

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

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

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

    public static function supprimer()
    {
        global $BD;

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

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

}