using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using DrSousan.Api.Data; using DrSousan.Api.Models; namespace DrSousan.Api.Pages.Blog; public class BlogIndexModel : PageModel { private readonly AppDbContext _db; private const int PageSize = 10; public BlogIndexModel(AppDbContext db) => _db = db; public List Posts { get; private set; } = new(); public List Categories { get; private set; } = new(); public int CurrentPage { get; private set; } = 1; public int TotalPages { get; private set; } = 1; public int TotalPosts { get; private set; } = 0; public string? ActiveCat { get; private set; } public async Task OnGetAsync(int page = 1, string? category = null) { CurrentPage = page < 1 ? 1 : page; ActiveCat = category; var q = _db.BlogPosts.Include(p => p.Category).Where(p => p.IsPublished); if (!string.IsNullOrEmpty(category)) q = q.Where(p => p.Category != null && p.Category.Slug == category); TotalPosts = await q.CountAsync(); TotalPages = Math.Max(1, (int)Math.Ceiling(TotalPosts / (double)PageSize)); if (CurrentPage > TotalPages) CurrentPage = TotalPages; Posts = await q .OrderByDescending(p => p.PublishedAt) .Skip((CurrentPage - 1) * PageSize) .Take(PageSize) .ToListAsync(); Categories = await _db.BlogCategories .Include(c => c.Posts) .ToListAsync(); ViewData["SiteName"] = await GetSiteNameAsync(); ViewData["Title"] = "وبلاگ | دکتر سوسن آل‌طه"; return Page(); } private async Task GetSiteNameAsync() { var s = await _db.SiteSettings .FirstOrDefaultAsync(x => x.Section == "hero" && x.Key == "name"); return s?.Value ?? "دکتر سوسن آل‌طه"; } }