<?php

namespace App\Models;

use App\Enums\PageLayout;

class Page 
{
    private $db;
    
    public function __construct()
    {
        $this->db = \db();
    }
    
    public function getAll()
    {
        return $this->db->fetchAll("SELECT * FROM pages ORDER BY id DESC");
    }
    
    public function getById($id)
    {
        $result = $this->db->fetchOne("SELECT * FROM pages WHERE id = ?", [$id]);
        
        // Decode extra_fields JSON
        if ($result && !empty($result['extra_fields'])) {
            $result['extra_fields'] = json_decode($result['extra_fields'], true) ?: [];
        } else if ($result) {
            $result['extra_fields'] = [];
        }
        
        return $result;
    }
    
    public function getBySlug($slug)
    {
        $result = $this->db->fetchOne("SELECT * FROM pages WHERE slug = ?", [$slug]);
        
        // Decode extra_fields JSON
        if ($result && !empty($result['extra_fields'])) {
            $result['extra_fields'] = json_decode($result['extra_fields'], true) ?: [];
        } else if ($result) {
            $result['extra_fields'] = [];
        }
        
        return $result;
    }
    
    public function create($data)
    {
        // If this page is being set as homepage, unset all other homepages
        if (!empty($data['is_homepage']) && $data['is_homepage'] == 1) {
            $this->db->execute("UPDATE pages SET is_homepage = 0");
        }
        
        $sql = "INSERT INTO pages (name, slug, title, content, extra_fields, layout, is_homepage) VALUES (?, ?, ?, ?, ?, ?, ?)";
        $params = [
            $data['name'],
            $data['slug'],
            $data['title'] ?? null,
            $data['content'] ?? null,
            $data['extra_fields'] ? json_encode($data['extra_fields']) : null,
            $data['layout'] ?? PageLayout::Default->value,
            $data['is_homepage'] ?? 0
        ];
        
        $this->db->execute($sql, $params);
        return $this->db->lastInsertId();
    }
    
    public function update($id, $data)
    {
        // If this page is being set as homepage, unset all other homepages
        if (!empty($data['is_homepage']) && $data['is_homepage'] == 1) {
            $this->db->execute("UPDATE pages SET is_homepage = 0 WHERE id != ?", [$id]);
        }
        
        $sql = "UPDATE pages SET name = ?, slug = ?, title = ?, content = ?, extra_fields = ?, layout = ?, is_homepage = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $params = [
            $data['name'],
            $data['slug'],
            $data['title'] ?? null,
            $data['content'] ?? null,
            $data['extra_fields'] ? json_encode($data['extra_fields']) : null,
            $data['layout'] ?? PageLayout::Default->value,
            $data['is_homepage'] ?? 0,
            $id
        ];
        
        return $this->db->execute($sql, $params);
    }
    
    public function delete($id)
    {
        return $this->db->execute("DELETE FROM pages WHERE id = ?", [$id]);
    }
    
    public function updateOrCreate($slug, $data)
    {
        $existing = $this->getBySlug($slug);
        
        if ($existing) {
            $this->update($existing['id'], $data);
            return $existing['id'];
        } else {
            return $this->create($data);
        }
    }
    
    public function exists($slug, $excludeId = null)
    {
        if ($excludeId) {
            return $this->db->fetchOne("SELECT id FROM pages WHERE slug = ? AND id != ?", [$slug, $excludeId]);
        }
        
        return $this->db->fetchOne("SELECT id FROM pages WHERE slug = ?", [$slug]);
    }
}