<?php

namespace App\Controllers;

use App\Core\Controller;
use PDO;

class BlogController extends Controller {
    
    public function index() {
        $db = db_pdo();
        $stmt = $db->prepare("SELECT * FROM posts ORDER BY created_at DESC");
        $stmt->execute();
        $blogPosts = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $this->view('blog/index', ['blogPosts' => $blogPosts]);
    }

    public function detail($params) {
        $slug = $params['slug'];
        $db = db_pdo();
        $stmt = $db->prepare("SELECT * FROM posts WHERE slug = ?");
        $stmt->execute([$slug]);
        $post = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$post) {
            $this->view('404');
            return;
        }

        $this->view('blog/detail', ['post' => $post]);
    }
}
