<?php
/**
 * Nesvra Blog Service: High-performance JSON Data Access Layer
 */

define('NESVRA_BLOG_DATA_FILE', __DIR__ . '/../data/blogs.json');

/**
 * Load all blog posts from JSON store with in-memory caching
 */
function get_all_blogs($status = 'all', $forceReload = false) {
    static $cachedBlogs = null;

    if ($cachedBlogs === null || $forceReload) {
        if (!file_exists(NESVRA_BLOG_DATA_FILE)) {
            return [];
        }
        $raw = file_get_contents(NESVRA_BLOG_DATA_FILE);
        $decoded = json_decode($raw, true);
        $cachedBlogs = is_array($decoded) ? $decoded : [];
    }

    if ($status === 'all') {
        return $cachedBlogs;
    }

    return array_values(array_filter($cachedBlogs, function($b) use ($status) {
        return ($b['status'] ?? 'published') === $status;
    }));
}

/**
 * Lookup a single blog post by slug or ID
 */
function get_blog_by_slug($slug) {
    if (empty($slug)) return null;

    $cleanSlug = strtolower(trim($slug));
    $cleanSlug = preg_replace('/\.php$/', '', $cleanSlug);
    $cleanSlug = preg_replace('/^blogs\//', '', $cleanSlug);

    $blogs = get_all_blogs('all');
    foreach ($blogs as $b) {
        $postSlug = strtolower($b['slug'] ?? '');
        $postId   = strtolower($b['id'] ?? '');
        if ($postSlug === $cleanSlug || $postId === $cleanSlug) {
            return $b;
        }
    }
    return null;
}

/**
 * Get distinct categories with active post counts
 */
function get_blog_categories() {
    $blogs = get_all_blogs('all');
    $counts = ['All Blog' => 0];

    foreach ($blogs as $b) {
        $counts['All Blog']++;
        $cat = trim($b['category'] ?? 'General');
        if (!isset($counts[$cat])) {
            $counts[$cat] = 0;
        }
        $counts[$cat]++;
    }

    return $counts;
}

/**
 * Get related posts for an active post
 */
function get_related_blogs($currentSlugOrId, $category = null, $limit = 3) {
    $blogs = get_all_blogs('all');
    $currentSlug = strtolower(preg_replace('/\.php$/', '', basename($currentSlugOrId)));

    $sameCat = [];
    $other = [];

    foreach ($blogs as $b) {
        $pSlug = strtolower($b['slug'] ?? '');
        $pId   = strtolower($b['id'] ?? '');

        if ($pSlug === $currentSlug || $pId === $currentSlug) {
            continue;
        }

        if ($category && strcasecmp($b['category'] ?? '', $category) === 0) {
            $sameCat[] = $b;
        } else {
            $other[] = $b;
        }
    }

    $combined = array_merge($sameCat, $other);
    return array_slice($combined, 0, $limit);
}

/**
 * Search blogs by query and category
 */
function search_blogs($query = '', $category = 'All Blog') {
    $blogs = get_all_blogs('all');
    $q = strtolower(trim($query));

    return array_values(array_filter($blogs, function($b) use ($q, $category) {
        // Category check
        if ($category !== 'All Blog' && strcasecmp($b['category'] ?? '', $category) !== 0) {
            return false;
        }

        // Query search
        if (!empty($q)) {
            $titleMatch = strpos(strtolower($b['title'] ?? ''), $q) !== false;
            $descMatch  = strpos(strtolower($b['description'] ?? ''), $q) !== false;
            $catMatch   = strpos(strtolower($b['category'] ?? ''), $q) !== false;
            if (!$titleMatch && !$descMatch && !$catMatch) {
                return false;
            }
        }

        return true;
    }));
}

/**
 * Save / Update a blog post (atomic write with file locking)
 */
function save_blog($postData) {
    $blogs = get_all_blogs('all');
    
    // Generate or clean slug
    $slug = !empty($postData['slug']) ? $postData['slug'] : preg_replace('/[^a-z0-9-]+/', '-', strtolower(trim($postData['title'])));
    $slug = trim($slug, '-');

    $foundIndex = -1;
    foreach ($blogs as $i => $b) {
        if ($b['slug'] === $slug || (!empty($postData['id']) && $b['id'] === $postData['id'])) {
            $foundIndex = $i;
            break;
        }
    }

    $newPost = [
        'id'          => $postData['id'] ?? ('post_' . uniqid()),
        'slug'        => $slug,
        'title'       => trim($postData['title'] ?? 'Untitled Article'),
        'description' => trim($postData['description'] ?? ''),
        'category'    => trim($postData['category'] ?? 'Fintech'),
        'image'       => trim($postData['image'] ?? 'Asset/home-v3.webp'),
        'publishDate' => $postData['publishDate'] ?? date('F d, Y'),
        'readTime'    => $postData['readTime'] ?? '6 min read',
        'featured'    => $postData['featured'] ?? 'no',
        'author'      => [
            'name' => $postData['author_name'] ?? 'Nesvra Strategy Team',
            'role' => $postData['author_role'] ?? 'Fintech & Systems Architecture'
        ],
        'content'     => $postData['content'] ?? '',
        'updatedAt'   => date('Y-m-d H:i:s')
    ];

    if ($foundIndex >= 0) {
        $newPost['createdAt'] = $blogs[$foundIndex]['createdAt'] ?? date('Y-m-d H:i:s');
        $blogs[$foundIndex] = $newPost;
    } else {
        $newPost['createdAt'] = date('Y-m-d H:i:s');
        array_unshift($blogs, $newPost);
    }

    $json = json_encode($blogs, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $res = file_put_contents(NESVRA_BLOG_DATA_FILE, $json, LOCK_EX);
    if ($res !== false) {
        get_all_blogs('all', true); // Force cache bust
        return true;
    }
    return false;
}

/**
 * Delete a blog post by slug
 */
function delete_blog($slug) {
    $blogs = get_all_blogs('all', true);
    $filtered = array_values(array_filter($blogs, function($b) use ($slug) {
        return $b['slug'] !== $slug && $b['id'] !== $slug;
    }));

    if (count($filtered) === count($blogs)) {
        return false;
    }

    $json = json_encode($filtered, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
    $res = file_put_contents(NESVRA_BLOG_DATA_FILE, $json, LOCK_EX);
    if ($res !== false) {
        get_all_blogs('all', true); // Force cache bust
        return true;
    }
    return false;
}
