<?php
/**
 * CMS Management Class
 * 
 * Handles all content management operations
 * 
 * @author ESDN Development Team
 * @version 1.0.0
 */

require_once __DIR__ . '/DB.php';

class CMS
{
    private $db;

    public function __construct()
    {
        $this->db = new DB();
    }

    /**
     * Static helper for easy template access
     */
    public static function get(string $key, string $default = ''): string
    {
        $cms = new self();
        $record = $cms->getContent($key);
        return $record['content_value'] ?? $default;
    }

    /**
     * Get content by key
     */
    public function getContent(string $key): ?array
    {
        $sql = "SELECT * FROM site_content WHERE content_key = :key";
        return $this->db->getRecordFilled($sql, [':key' => $key]);
    }

    /**
     * Get all content for a page
     */
    public function getPageContent(string $pageName): array
    {
        $sql = "SELECT * FROM site_content WHERE page_name = :page";
        return $this->db->getRecordSetFilled($sql, [':page' => $pageName]);
    }

    /**
     * Get all content grouped by page
     */
    public function getAllContent(): array
    {
        $sql = "SELECT * FROM site_content ORDER BY page_name ASC, content_label ASC";
        return $this->db->getRecordSetFilled($sql);
    }

    /**
     * Update or Create content
     */
    public function upsertContent(array $data): bool
    {
        $sql = "INSERT INTO site_content (content_key, page_name, content_label, content_value, content_type)
                VALUES (:key, :page, :label, :value, :type)
                ON DUPLICATE KEY UPDATE 
                page_name = VALUES(page_name),
                content_label = VALUES(content_label),
                content_value = VALUES(content_value),
                content_type = VALUES(content_type)";

        return $this->db->dbQuery($sql, [
            ':key' => $data['content_key'],
            ':page' => $data['page_name'] ?? 'global',
            ':label' => $data['content_label'] ?? $data['content_key'],
            ':value' => $data['content_value'] ?? '',
            ':type' => $data['content_type'] ?? 'text'
        ]);
    }

    /**
     * Delete content
     */
    public function deleteContent(string $key): bool
    {
        $sql = "DELETE FROM site_content WHERE content_key = :key";
        return $this->db->dbQuery($sql, [':key' => $key]);
    }
}
