<?php

namespace App\Post;

use App\Core\AbstractController;
use App\User\LoginService;
use App\Post\CommentsRepository;
use PDO;


class PostsAdminController extends AbstractController
{

  public function __construct(
    PostsRepository $postsRepository,
    CommentsRepository $commentsRepository,
    LoginService $loginService
  )
  {
    $this->postsRepository = $postsRepository;
    $this->commentsRepository = $commentsRepository;
    $this->loginService = $loginService;
  }

  public function index() {
    $this->loginService->check();
    $all = $this->postsRepository->all();
    $this->render("post/admin/index", [
      'all' => $all
    ]);
  }

  public function index_c() {
    $this->loginService->check();
    $all = $this->postsRepository->all();
//    $comments = $this->commentsRepository->allCommentsByID($id);  //allByPost($id);
    $this->render("post/admin/index_c", [
      'all' => $all,
//      'comments' => $comments
    ]);
  }

  public function getComment($id) {
   $post = $this->postsRepository->find($id);
   $comments = $this->commentsRepository->allByPost($id);
   return $comments;
 }

  public function edit_c() {
    $id = getAndSetSession('id', 'id', '1');
    $this->loginService->check();
    $savedSuccess = false;

    if (!empty($_POST['id']) AND !empty($_POST['content'])) {
      $content = $_POST['content'];
      $postId = $_POST['post_id'];
      $p_id = $_POST['id'];
      $org = $_POST['original'];
      $this->commentsRepository->update($postId, $content, $p_id, $org);
      $savedSuccess = true;
    }

    $post = $this->postsRepository->find($id);
    $comments = $this->commentsRepository->allCommentsByID($id);
    $this->render("post/admin/edit_c", [
      'comments' => $comments,
      'post'  => $post,
      'savedSuccess' => $savedSuccess
    ]);
  }

  public function edit() {
    $this->loginService->check();
    $id = $_GET['id'];
    $entry = $this->postsRepository->find($id);
    $savedSuccess = false;
    if (!empty($_POST['title']) AND !empty($_POST['content'])) {
      $entry->title = $_POST['title'];
      $entry->content = $_POST['content'];
      $this->postsRepository->update($entry);
      $savedSuccess = true;
    }
    $this->render("post/admin/edit", [
      'entry' => $entry,
      'savedSuccess' => $savedSuccess
    ]);
  }

}
 ?>
