<?php
// app/Models/PageContent.php - Page Content Model

class PageContent {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Create new page content
     */
    public function create($data) {
        $sql = "INSERT INTO page_contents (
                    page_slug, page_title, meta_description, hero_title, hero_subtitle, 
                    hero_image, content_section_1_title, content_section_1_body, 
                    content_section_2_title, content_section_2_body, 
                    content_section_3_title, content_section_3_body, 
                    contact_info, faq_ids, is_active, last_modified_by, created_at
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
        
        $result = $this->db->execute($sql, [
            $data['page_slug'],
            $data['page_title'],
            $data['meta_description'] ?? null,
            $data['hero_title'] ?? null,
            $data['hero_subtitle'] ?? null,
            $data['hero_image'] ?? null,
            $data['content_section_1_title'] ?? null,
            $data['content_section_1_body'] ?? null,
            $data['content_section_2_title'] ?? null,
            $data['content_section_2_body'] ?? null,
            $data['content_section_3_title'] ?? null,
            $data['content_section_3_body'] ?? null,
            $data['contact_info'] ?? null,
            $data['faq_ids'] ?? null,
            $data['is_active'] ?? 1,
            $data['last_modified_by'] ?? null
        ]);
        
        return $result ? $this->db->lastInsertId() : false;
    }
    
    /**
     * Find page content by ID
     */
    public function find($id) {
        $sql = "SELECT pc.*, u.email as last_modified_by_email 
                FROM page_contents pc 
                LEFT JOIN users u ON pc.last_modified_by = u.id 
                WHERE pc.id = ? LIMIT 1";
        return $this->db->fetch($sql, [$id]);
    }
    
    /**
     * Find page content by slug
     */
    public function findBySlug($slug) {
        $sql = "SELECT pc.*, u.email as last_modified_by_email 
                FROM page_contents pc 
                LEFT JOIN users u ON pc.last_modified_by = u.id 
                WHERE pc.page_slug = ? AND pc.is_active = 1 LIMIT 1";
        return $this->db->fetch($sql, [$slug]);
    }
    
    /**
     * Get all page contents
     */
    public function getAll($filters = []) {
        $sql = "SELECT pc.*, u.email as last_modified_by_email 
                FROM page_contents pc 
                LEFT JOIN users u ON pc.last_modified_by = u.id 
                WHERE 1=1";
        $params = [];
        
        if (isset($filters['is_active'])) {
            $sql .= " AND pc.is_active = ?";
            $params[] = $filters['is_active'];
        }
        
        if (!empty($filters['search'])) {
            $sql .= " AND (pc.page_title LIKE ? OR pc.page_slug LIKE ?)";
            $search = '%' . $filters['search'] . '%';
            $params[] = $search;
            $params[] = $search;
        }
        
        $sql .= " ORDER BY pc.page_title ASC";
        
        return $this->db->fetchAll($sql, $params);
    }
    
    /**
     * Get page with related FAQs
     */
    public function getPageWithFaqs($slug) {
        $page = $this->findBySlug($slug);
        if (!$page) return null;
        
        // Get related FAQs if any
        if (!empty($page['faq_ids'])) {
            $faqIds = explode(',', $page['faq_ids']);
            $placeholders = str_repeat('?,', count($faqIds) - 1) . '?';
            
            $sql = "SELECT * FROM faqs WHERE id IN ($placeholders) AND is_active = 1 ORDER BY display_order ASC";
            $page['related_faqs'] = $this->db->fetchAll($sql, $faqIds);
        } else {
            $page['related_faqs'] = [];
        }
        
        return $page;
    }
    
    /**
     * Update page content
     */
    public function update($id, $data) {
        $fields = [];
        $params = [];
        
        foreach ($data as $key => $value) {
            $fields[] = "{$key} = ?";
            $params[] = $value;
        }
        
        $params[] = $id;
        
        $sql = "UPDATE page_contents SET " . implode(', ', $fields) . ", updated_at = NOW() WHERE id = ?";
        return $this->db->execute($sql, $params);
    }
    
    /**
     * Update by slug
     */
    public function updateBySlug($slug, $data) {
        $page = $this->findBySlug($slug);
        if (!$page) return false;
        
        return $this->update($page['id'], $data);
    }
    
    /**
     * Delete page content
     */
    public function delete($id) {
        $sql = "DELETE FROM page_contents WHERE id = ?";
        return $this->db->execute($sql, [$id]);
    }
    
    /**
     * Toggle active status
     */
    public function toggleActive($id) {
        $page = $this->find($id);
        if (!$page) return false;
        
        $newStatus = $page['is_active'] ? 0 : 1;
        return $this->update($id, ['is_active' => $newStatus]);
    }
    
    /**
     * Get public pages (for navigation, sitemap, etc.)
     */
    public function getPublicPages() {
        $sql = "SELECT page_slug, page_title, updated_at 
                FROM page_contents 
                WHERE is_active = 1 
                ORDER BY page_title ASC";
        return $this->db->fetchAll($sql);
    }
    
    /**
     * Get page statistics
     */
    public function getStats() {
        $sql = "SELECT 
                COUNT(*) as total_pages,
                SUM(CASE WHEN is_active = 1 THEN 1 ELSE 0 END) as active_pages,
                SUM(CASE WHEN is_active = 0 THEN 1 ELSE 0 END) as inactive_pages
                FROM page_contents";
        
        return $this->db->fetch($sql);
    }
    
    /**
     * Check if page slug exists
     */
    public function slugExists($slug, $excludeId = null) {
        $sql = "SELECT id FROM page_contents WHERE page_slug = ?";
        $params = [$slug];
        
        if ($excludeId) {
            $sql .= " AND id != ?";
            $params[] = $excludeId;
        }
        
        $result = $this->db->fetch($sql, $params);
        return $result !== false;
    }
    
    /**
     * Get all available slugs
     */
    public function getAllSlugs() {
        $sql = "SELECT page_slug FROM page_contents WHERE is_active = 1 ORDER BY page_slug";
        return $this->db->fetchAll($sql);
    }
}