<?php

namespace App\Models;

use App\Database;

class SeoMeta
{
    private $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    
    public function getAll()
    {
        return $this->db->fetchAll("SELECT * FROM seo_metas ORDER BY created_at DESC");
    }
    
    public function getById($id)
    {
        $result = $this->db->fetchOne("SELECT * FROM seo_metas 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 getByMorphable($seoableType, $seoableId)
    {
        $result = $this->db->fetchOne(
            "SELECT * FROM seo_metas WHERE seoable_type = ? AND seoable_id = ?", 
            [$seoableType, $seoableId]
        );
        
        // 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)
    {
        $sql = "INSERT INTO seo_metas (seoable_type, seoable_id, title, description, keywords, canonical, image, extra_fields) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        $params = [
            $data['seoable_type'],
            $data['seoable_id'],
            $data['title'] ?? null,
            $data['description'] ?? null,
            $data['keywords'] ?? null,
            $data['canonical'] ?? null,
            $data['image'] ?? null,
            $data['extra_fields'] ? json_encode($data['extra_fields']) : null
        ];
        
        $this->db->execute($sql, $params);
        return $this->db->lastInsertId();
    }
    
    public function update($id, $data)
    {
        $sql = "UPDATE seo_metas SET seoable_type = ?, seoable_id = ?, title = ?, description = ?, keywords = ?, canonical = ?, image = ?, extra_fields = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $params = [
            $data['seoable_type'],
            $data['seoable_id'],
            $data['title'] ?? null,
            $data['description'] ?? null,
            $data['keywords'] ?? null,
            $data['canonical'] ?? null,
            $data['image'] ?? null,
            $data['extra_fields'] ? json_encode($data['extra_fields']) : null,
            $id
        ];
        
        return $this->db->execute($sql, $params);
    }
    
    public function updateOrCreate($seoableType, $seoableId, $data)
    {
        $seoableType = strtolower($seoableType);
        $existing = $this->getByMorphable($seoableType, $seoableId);
        
        $data['seoable_type'] = $seoableType;
        $data['seoable_id'] = $seoableId;
        
        if ($existing) {
            return $this->update($existing['id'], $data);
        } else {
            return $this->create($data);
        }
    }
    
    public function delete($id)
    {
        return $this->db->execute("DELETE FROM seo_metas WHERE id = ?", [$id]);
    }
    
    public function deleteByMorphable($seoableType, $seoableId)
    {
        return $this->db->execute(
            "DELETE FROM seo_metas WHERE seoable_type = ? AND seoable_id = ?", 
            [$seoableType, $seoableId]
        );
    }
    
    public function exists($seoableType, $seoableId)
    {
        $result = $this->db->fetchOne(
            "SELECT COUNT(*) as count FROM seo_metas WHERE seoable_type = ? AND seoable_id = ?", 
            [$seoableType, $seoableId]
        );
        return $result['count'] > 0;
    }
    
    // Helper methods for any entity type
    public function getForRecord($entityType, $entityId)
    {
        return $this->getByMorphable($entityType, $entityId);
    }
    
    public function createForRecord($entityType, $entityId, $data)
    {
        return $this->updateOrCreate($entityType, $entityId, $data);
    }
    
    public function deleteForRecord($entityType, $entityId)
    {
        return $this->deleteByMorphable($entityType, $entityId);
    }
    
    // Convenience methods for specific entity types
    public function getForPage($pageId)
    {
        return $this->getForRecord('Page', $pageId);
    }
    
    public function createForPage($pageId, $data)
    {
        return $this->createForRecord('Page', $pageId, $data);
    }
    
    public function deleteForPage($pageId)
    {
        return $this->deleteForRecord('Page', $pageId);
    }
}