<?php

namespace Bases;

use PDO;

class Model
{
    private static $bdd = null;
    protected $table = null;

    protected function bdd()
    {
        if (self::$bdd === null) {
            require("config/db.php");

            $options = [
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8mb4'",
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ
            ];

            self::$bdd = new PDO(
                "mysql:host=$host;dbname=$dbname",
                $username,
                $password,
                $options
            );
        }
        return self::$bdd;
    }

    public function all()
    {
        $sql = "SELECT * FROM $this->table";
        $requete = $this->bdd()->prepare($sql);
        $requete->execute();
        return $requete->fetchAll();
    }

    public function find($id)
    {
        $sql = "SELECT * FROM $this->table WHERE id = :id";
        $requete = $this->bdd()->prepare($sql);
        $requete->execute([":id" => $id]);
        return $requete->fetch();
    }

    /**
     * Insère une nouvelle entrée.
     * $data est un tableau associatif [colonne => valeur]
     *
     * @param array $data
     * @return bool
     */
    public function insert($data)
    {
        $cols = array_keys($data);
        $placeholders = ":" . implode(",:", $cols);
        $colonnes = implode(",", $cols);

        $sql = "INSERT INTO $this->table ($colonnes) VALUES ($placeholders)";
        $requete = $this->bdd()->prepare($sql);
        return $requete->execute($data);
    }

    /**
     * Met à jour une entrée par ID.
     * $data est un tableau associatif [colonne => valeur]
     *
     * @param int $id
     * @param array $data
     * @return bool
     */
    public function update($id, $data)
    {
        $sets = [];
        foreach ($data as $col => $val) {
            $sets[] = "$col = :$col";
        }
        $setsStr = implode(", ", $sets);

        $sql = "UPDATE $this->table SET $setsStr WHERE id = :id";
        $requete = $this->bdd()->prepare($sql);

        // Ajoute l'id au tableau des paramètres pour la requête
        $data['id'] = $id;

        return $requete->execute($data);
    }

    /**
     * Supprime une entrée par ID
     *
     * @param int $id
     * @return bool
     */
    public function destroy($id)
    {
        $sql = "DELETE FROM $this->table WHERE id = :id";
        $requete = $this->bdd()->prepare($sql);
        return $requete->execute([":id" => $id]);
    }
}
