<?php
class Articles extends Controller{
    
    private $articleModel;
    
    public function __construct(){
        $this->articleModel = $this->model('Article');
    }

    public function index(){

        $page = isset($_GET['page']) && is_numeric($_GET['page']) && $_GET['page'] > 0
            ? (int)$_GET['page']
            : 1;

        $limit = 20; // Number of items per page
        $offset = ($page - 1) * $limit;

        
        $articles = $this->articleModel->getAllArticles($limit, $offset);
        $randomArticle = $this->articleModel->getRandomArticle();
        $totalArticles = $this->articleModel->getTotalArticlesCount(); 
        
        $totalPages = ceil($totalArticles / $limit);
          // Load View
          $this->view('articles/index', [
            'articles' => $articles,
            'randomArticle' => $randomArticle,
            'page' => $page, // optional, but helpful for pagination links
            'totalPages' => $totalPages 
        ]);

    }
    public function show($slugWithId)
{
    // Split slug and id
    $parts = explode('-', $slugWithId);
    $id = array_pop($parts); // Last part is the ID

    $article = $this->articleModel->getArticleById($id);


    $this->view('articles/details', [
        'article' => $article
    ]);
}
}