<?php
namespace App\Core;
use PDO;
use App\Post\PostsRepository;
use App\Post\CommentsRepository;
use App\Post\PostsController;
use App\User\UsersRepository;
use App\User\LoginController;
use App\User\LoginService;

class Container
{
  private $receips = [];           // Bauanleitung für verschiedene instances
  private $instances = [];

  public function __construct() {
    $this->receips = [
      'loginService' => function() {
        return new LoginService(
          $this->make('usersRepository')
        );
      },
      'loginController' => function() {
        return new LoginController(
          $this->make('loginService')
        );
      },
      'postsController' => function() {
        return new PostsController(         //neuer PostsController
           $this->make('postsRepository'),
           $this->make('commentsRepository')
        );
      },
      'usersRepository' => function() {
        return new UsersRepository(
          $this->make("pdo")
        );
      },
      'postsRepository' => function() {
        return new PostsRepository(
          $this->make("pdo")
        );
      },
      'commentsRepository' => function() {
        return new CommentsRepository(
          $this->make("pdo")
        );
      },
      'pdo' => function() {
        $servername = "mysqle8e6.netcup.net";
        $port = "3306";
        $username = "k46054_hbc";
        $password = "cXZm/E97dKvZy6Cg*";
        $dbname="k46054_hbc";
        
        $pdo = new PDO("mysql:host=$servername;dbname=$dbname;port=$port", $username, $password);

       // Attribut wegen Sicherheit auf false setzen
        $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
        return $pdo;
       }
   ];
  }

  public function make($name) {
    if (!empty($this->instances[$name])){
      return $this->instances[$name]; // DB-Verbindung besteht
      }
    // sonst ERZEUGE return $this->instances[$name
    if (isset($this->receips[$name])) {
      $this->instances[$name] = $this->receips[$name]();
      }
    return $this->instances[$name];
  }
}
?>
