<?php
require "core.php";

// Get author ID from URL
$author_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($author_id <= 0) {
    header('Location: ' . SITE_URL . '/Post');
    exit;
}

// Get author information
$stmt = $connect->prepare("SELECT * FROM users WHERE user_id = :id AND user_status = 1");
$stmt->execute([':id' => $author_id]);
$author = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$author) {
    header('Location: ' . SITE_URL . '/Post');
    exit;
}

// Pagination
$itemsPerPage = 12;
$currentPage = isset($_GET['page']) ? intval($_GET['page']) : 1;
$offset = ($currentPage - 1) * $itemsPerPage;

// Get total posts by this author
$totalPosts = $connect->prepare("SELECT COUNT(*) FROM blog_posts WHERE post_author = :author AND post_status = 'published'");
$totalPosts->execute([':author' => $author_id]);
$totalPosts = $totalPosts->fetchColumn();
$totalPages = ceil($totalPosts / $itemsPerPage);

// Get author's blog posts
$query = "SELECT bp.*, bc.blog_cat_name, bc.blog_cat_slug 
          FROM blog_posts bp
          LEFT JOIN blog_categories bc ON bp.post_category = bc.blog_cat_id
          WHERE bp.post_author = :author AND bp.post_status = 'published'
          ORDER BY bp.published_at DESC
          LIMIT $itemsPerPage OFFSET $offset";

$stmt = $connect->prepare($query);
$stmt->execute([':author' => $author_id]);
$posts = $stmt->fetchAll(PDO::FETCH_ASSOC);

// SEO
$titleSeoHeader = getSeoTitle($translation['tr_1'], "Posts by " . $author['user_name']);
$descriptionSeoHeader = getSeoDescription($translation['tr_3'], $author['user_bio'] ?: "Read all posts by " . $author['user_name']);
$canonicalUrl = SITE_URL . '/author/' . $author_id;
$pageTitle = $author['user_name'];

// Set itemDetails for ad views
$itemDetails = [
    'page_ad_header' => 1,
    'page_ad_footer' => 1,
    'page_footer' => 1
];

include './header.php';
include './sections/header.php';
include './sections/views/header-ad.view.php';
include './views/author.view.php';
include './sections/views/footer-ad.view.php';
include './sections/footer.php';
include './footer.php';
?>
