<?php
/**
 * ZLO Platform - Page Model
 */

declare(strict_types=1);

require_once __DIR__ . '/../core/Model.php';

class Page extends Model
{
    protected string $table = 'pages';
    protected string $primaryKey = 'id';
    
    /**
     * Get active page by slug
     */
    public function getBySlug(string $slug): ?array
    {
        return $this->db->fetchOne(
            "SELECT * FROM {$this->table} WHERE slug = ? AND status = 'active'",
            [$slug]
        );
    }
    
    /**
     * Get all active pages
     */
    public function getActive(): array
    {
        return $this->db->fetchAll(
            "SELECT * FROM {$this->table} WHERE status = 'active' ORDER BY menu_order ASC"
        );
    }
    
    /**
     * Get menu pages
     */
    public function getMenuPages(): array
    {
        return $this->db->fetchAll(
            "SELECT id, title, slug, menu_order FROM {$this->table} 
             WHERE status = 'active' AND show_in_menu = 1 
             ORDER BY menu_order ASC"
        );
    }
    
    /**
     * Create page with slug
     */
    public function createPage(array $data): int
    {
        if (empty($data['slug'])) {
            $data['slug'] = $this->generateSlug($data['title']);
        }
        
        return $this->create($data);
    }
    
    /**
     * Update page
     */
    public function updatePage(int $id, array $data): bool
    {
        if (!empty($data['title']) && empty($data['slug'])) {
            $data['slug'] = $this->generateSlug($data['title'], $id);
        }
        
        return $this->update($id, $data);
    }
    
    /**
     * Generate unique slug
     */
    public function generateSlug(string $title, ?int $excludeId = null): string
    {
        $slug = $this->slugify($title);
        $originalSlug = $slug;
        $counter = 1;
        
        while (true) {
            $sql = "SELECT id FROM {$this->table} WHERE slug = ?";
            $params = [$slug];
            
            if ($excludeId) {
                $sql .= " AND id != ?";
                $params[] = $excludeId;
            }
            
            $existing = $this->db->fetchOne($sql, $params);
            
            if (!$existing) {
                break;
            }
            
            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }
    
    /**
     * Convert title to slug
     */
    private function slugify(string $text): string
    {
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        $text = preg_replace('~[^-\w]+~', '', $text);
        $text = trim($text, '-');
        $text = preg_replace('~-+~', '-', $text);
        $text = strtolower($text);
        
        return $text ?: 'n-a';
    }
    
    /**
     * Get pages by template
     */
    public function getByTemplate(string $template): array
    {
        return $this->db->fetchAll(
            "SELECT * FROM {$this->table} WHERE template = ? AND status = 'active'",
            [$template]
        );
    }
}
