<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

try {

    $db = Database::getInstance();

    $blogId = (int)($_GET['id'] ?? 0);
    if ($blogId <= 0) {
        Response::error('Invalid blog id', 422);
    }

    /* ================= BLOG CORE + PUBLISHER ================= */
    $stmt = $db->prepare("
        SELECT
            b.*,
            CONCAT(e.first_name, ' ', e.last_name) AS published_by_name
        FROM blogs b
        LEFT JOIN employees e ON e.id = b.published_by
        WHERE b.id = :id
    ");
    $stmt->execute(['id' => $blogId]);
    $blog = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$blog) {
        Response::error('Blog not found', 404);
    }

    /* ================= FEATURED IMAGE (PRIMARY) ================= */
    $stmt = $db->prepare("
        SELECT
            image_path,
            alt_text,
            caption
        FROM blog_images
        WHERE blog_id = :id
          AND is_primary = 1
          AND status = 'Active'
        ORDER BY sort_order ASC
        LIMIT 1
    ");
    $stmt->execute(['id' => $blogId]);
    $featuredImage = $stmt->fetch(PDO::FETCH_ASSOC);

    // Inject into blog payload
    $blog['featured_image'] = $featuredImage['image_path'] ?? null;
    $blog['featured_image_alt'] = $featuredImage['alt_text'] ?? null;
    $blog['featured_image_caption'] = $featuredImage['caption'] ?? null;

    /* ================= SEO ================= */
    $stmt = $db->prepare("
        SELECT *
        FROM blog_seo
        WHERE blog_id = :id
    ");
    $stmt->execute(['id' => $blogId]);
    $seo = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;

    /* ================= CATEGORIES ================= */
    $stmt = $db->prepare("
        SELECT c.id, c.name
        FROM blog_categories c
        JOIN blog_category_map bcm ON bcm.category_id = c.id
        WHERE bcm.blog_id = :id
    ");
    $stmt->execute(['id' => $blogId]);
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

    /* ================= TAGS ================= */
    $stmt = $db->prepare("
        SELECT t.id, t.name
        FROM blog_tags t
        JOIN blog_tag_map btm ON btm.tag_id = t.id
        WHERE btm.blog_id = :id
    ");
    $stmt->execute(['id' => $blogId]);
    $tags = $stmt->fetchAll(PDO::FETCH_ASSOC);

    /* ================= APPROVAL ================= */
    $approval = [
        'approval_status'  => $blog['approval_status'] ?? null,
        'approved_at'      => $blog['approved_at'] ?? null,
        'rejected_at'      => $blog['rejected_at'] ?? null,
        'rejection_reason' => $blog['rejection_reason'] ?? null
    ];

    Response::success('Blog loaded', [
        'blog'       => $blog,
        'seo'        => $seo,
        'categories' => $categories,
        'tags'       => $tags,
        'approval'   => $approval
    ]);

} catch (Throwable $e) {

    // Prevent silent 500s
    Response::error(
        'Server error: ' . $e->getMessage(),
        500
    );
}
