<?php
/**
 * SmartThink3 LMS - Site Content Class
 *
 * Manages CMS-controlled content blocks for public website pages.
 */

class SiteContent {
    /** @var Database */
    private $db;

    public function __construct() {
        $this->db = Database::getInstance();
    }

    /**
     * Get a single content block value with optional default and region fallback.
     */
    public function getBlockValue(string $pageSlug, string $blockKey, string $region = 'global', string $default = ''): string {
        // Try region-specific block first (if not global)
        if ($region !== 'global') {
            $block = $this->db->get(
                "SELECT content FROM site_content_blocks WHERE page_slug = ? AND block_key = ? AND region = ? LIMIT 1",
                [$pageSlug, $blockKey, $region]
            );
            if ($block && $block['content'] !== null && $block['content'] !== '') {
                return $block['content'];
            }
        }

        // Fallback to global
        $block = $this->db->get(
            "SELECT content FROM site_content_blocks WHERE page_slug = ? AND block_key = ? AND region = 'global' LIMIT 1",
            [$pageSlug, $blockKey]
        );

        if ($block && $block['content'] !== null && $block['content'] !== '') {
            return $block['content'];
        }

        return $default;
    }

    /**
     * Create or update a content block (upsert).
     */
    public function saveBlock(string $pageSlug, string $blockKey, string $content, string $label = null, string $region = 'global', string $contentType = 'text', ?int $updatedBy = null): void {
        // Check if block exists
        $existing = $this->db->get(
            "SELECT id FROM site_content_blocks WHERE page_slug = ? AND block_key = ? AND region = ? LIMIT 1",
            [$pageSlug, $blockKey, $region]
        );

        $data = [
            'page_slug'    => $pageSlug,
            'block_key'    => $blockKey,
            'label'        => $label,
            'region'       => $region,
            'content'      => $content,
            'content_type' => $contentType,
            'updated_by'   => $updatedBy,
        ];

        if ($existing && isset($existing['id'])) {
            $this->db->update('site_content_blocks', $data, 'id = ?', [$existing['id']]);
        } else {
            $this->db->insert('site_content_blocks', $data);
        }
    }

    /**
     * Get all blocks, optionally filtered by page.
     */
    public function getBlocks(?string $pageSlug = null): array {
        if ($pageSlug) {
            return $this->db->getAll(
                "SELECT * FROM site_content_blocks WHERE page_slug = ? ORDER BY page_slug, block_key, region",
                [$pageSlug]
            );
        }

        return $this->db->getAll(
            "SELECT * FROM site_content_blocks ORDER BY page_slug, block_key, region",
            []
        );
    }

    /**
     * Get a single block by ID.
     */
    public function getBlockById(int $id): ?array {
        $block = $this->db->get("SELECT * FROM site_content_blocks WHERE id = ?", [$id]);
        return $block ?: null;
    }

    /**
     * Delete a block by ID.
     */
    public function deleteBlock(int $id): void {
        $this->db->delete('site_content_blocks', 'id = ?', [$id]);
    }
}
