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

declare(strict_types=1);

require_once __DIR__ . '/../models/Page.php';
require_once __DIR__ . '/../core/Router.php';

class PageController
{
    private Page $pageModel;
    
    public function __construct()
    {
        $this->pageModel = new Page();
    }
    
    /**
     * Get all pages (admin)
     */
    public function index(array $params): array
    {
        AuthController::requirePermission('pages.view');
        
        $query = Router::getQuery();
        $page = (int) ($query['page'] ?? 1);
        $limit = (int) ($query['limit'] ?? 20);
        $status = $query['status'] ?? null;
        
        if ($status) {
            $sql = "SELECT * FROM pages WHERE status = ? ORDER BY menu_order ASC";
            return $this->pageModel->paginate($sql, [$status], $page, $limit);
        }
        
        $sql = "SELECT * FROM pages ORDER BY menu_order ASC, created_at DESC";
        return $this->pageModel->paginate($sql, [], $page, $limit);
    }
    
    /**
     * Get single page
     */
    public function show(array $params): ?array
    {
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Page ID is required'];
        }
        
        $page = $this->pageModel->find($id);
        
        if (!$page) {
            http_response_code(404);
            return ['error' => 'Page not found'];
        }
        
        return $page;
    }
    
    /**
     * Get page by slug (public)
     */
    public function bySlug(array $params): ?array
    {
        $slug = $params['slug'] ?? '';
        
        if (!$slug) {
            http_response_code(400);
            return ['error' => 'Slug is required'];
        }
        
        $page = $this->pageModel->getBySlug($slug);
        
        if (!$page) {
            http_response_code(404);
            return ['error' => 'Page not found'];
        }
        
        return $page;
    }
    
    /**
     * Create page (admin)
     */
    public function create(array $params): array
    {
        AuthController::requirePermission('pages.create');
        
        $body = Router::getBody();
        $security = new Security();
        
        // Validate required fields
        if (empty($body['title'])) {
            http_response_code(400);
            return ['error' => 'Title is required'];
        }
        
        // Sanitize content
        $data = [
            'title' => $security->sanitize($body['title']),
            'content' => $body['content'] ?? '',
            'template' => $body['template'] ?? 'default',
            'meta_title' => !empty($body['meta_title']) ? $security->sanitize($body['meta_title']) : null,
            'meta_description' => !empty($body['meta_description']) ? $security->sanitize($body['meta_description']) : null,
            'meta_keywords' => !empty($body['meta_keywords']) ? $security->sanitize($body['meta_keywords']) : null,
            'og_image' => !empty($body['og_image']) ? $security->sanitize($body['og_image']) : null,
            'status' => $body['status'] ?? 'draft',
            'show_in_menu' => $body['show_in_menu'] ?? false,
            'menu_order' => $body['menu_order'] ?? 0
        ];
        
        try {
            $id = $this->pageModel->createPage($data);
            
            http_response_code(201);
            return $this->pageModel->find($id);
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to create page'];
        }
    }
    
    /**
     * Update page (admin)
     */
    public function update(array $params): ?array
    {
        AuthController::requirePermission('pages.edit');
        
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Page ID is required'];
        }
        
        $body = Router::getBody();
        $security = new Security();
        
        $data = [];
        
        if (!empty($body['title'])) {
            $data['title'] = $security->sanitize($body['title']);
        }
        if (isset($body['content'])) {
            $data['content'] = $body['content'];
        }
        if (!empty($body['template'])) {
            $data['template'] = $body['template'];
        }
        if (isset($body['meta_title'])) {
            $data['meta_title'] = $security->sanitize($body['meta_title']);
        }
        if (isset($body['meta_description'])) {
            $data['meta_description'] = $security->sanitize($body['meta_description']);
        }
        if (isset($body['meta_keywords'])) {
            $data['meta_keywords'] = $security->sanitize($body['meta_keywords']);
        }
        if (isset($body['og_image'])) {
            $data['og_image'] = $security->sanitize($body['og_image']);
        }
        if (isset($body['status'])) {
            $data['status'] = $body['status'];
        }
        if (isset($body['show_in_menu'])) {
            $data['show_in_menu'] = $body['show_in_menu'] ? 1 : 0;
        }
        if (isset($body['menu_order'])) {
            $data['menu_order'] = (int) $body['menu_order'];
        }
        
        try {
            $this->pageModel->updatePage($id, $data);
            return $this->pageModel->find($id);
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to update page'];
        }
    }
    
    /**
     * Delete page (admin)
     */
    public function delete(array $params): array
    {
        AuthController::requirePermission('pages.delete');
        
        $id = (int) ($params['id'] ?? 0);
        
        if (!$id) {
            http_response_code(400);
            return ['error' => 'Page ID is required'];
        }
        
        try {
            $this->pageModel->delete($id);
            return ['message' => 'Page deleted successfully'];
        } catch (Exception $e) {
            http_response_code(500);
            return ['error' => 'Failed to delete page'];
        }
    }
    
    /**
     * Get menu pages (public)
     */
    public function menu(array $params): array
    {
        return $this->pageModel->getMenuPages();
    }
    
    /**
     * Get templates
     */
    public function templates(array $params): array
    {
        return [
            ['id' => 'default', 'name' => 'Default'],
            ['id' => 'full-width', 'name' => 'Full Width'],
            ['id' => 'sidebar-left', 'name' => 'Sidebar Left'],
            ['id' => 'sidebar-right', 'name' => 'Sidebar Right'],
            ['id' => 'landing', 'name' => 'Landing Page'],
            ['id' => 'legal', 'name' => 'Legal Page']
        ];
    }
}
