<?php

namespace App\Models;

use App\Database;

class Faq
{
    private $db;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
    }
    
    public function getAll()
    {
        return $this->db->fetchAll("SELECT * FROM faqs ORDER BY created_at DESC");
    }
    
    public function getById($id)
    {
        $result = $this->db->fetchOne("SELECT * FROM faqs 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($faqableType, $faqableId)
    {
        $result = $this->db->fetchAll(
            "SELECT * FROM faqs WHERE faqable_type = ? AND faqable_id = ? ORDER BY created_at ASC", 
            [strtolower($faqableType), $faqableId]
        );
        
        // Decode extra_fields JSON for each record
        foreach ($result as &$item) {
            if (!empty($item['extra_fields'])) {
                $item['extra_fields'] = json_decode($item['extra_fields'], true) ?: [];
            } else {
                $item['extra_fields'] = [];
            }
        }
        
        return $result;
    }
    
    public function create($data)
    {
        $sql = "INSERT INTO faqs (faqable_type, faqable_id, title, extra_fields) VALUES (?, ?, ?, ?)";
        $params = [
            strtolower($data['faqable_type']),
            $data['faqable_id'],
            $data['title'] ?? 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 faqs SET faqable_type = ?, faqable_id = ?, title = ?, extra_fields = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?";
        $params = [
            strtolower($data['faqable_type']),
            $data['faqable_id'],
            $data['title'] ?? null,
            $data['extra_fields'] ? json_encode($data['extra_fields']) : null,
            $id
        ];
        
        return $this->db->execute($sql, $params);
    }
    
    public function updateOrCreate($faqableType, $faqableId, $data)
    {
        $faqableType = strtolower($faqableType);
        $existing = $this->getByMorphable($faqableType, $faqableId);
        
        $data['faqable_type'] = $faqableType;
        $data['faqable_id'] = $faqableId;
        
        if (!empty($existing)) {
            return $this->update($existing[0]['id'], $data);
        } else {
            return $this->create($data);
        }
    }
    
    public function delete($id)
    {
        return $this->db->execute("DELETE FROM faqs WHERE id = ?", [$id]);
    }
    
    public function deleteByMorphable($faqableType, $faqableId)
    {
        return $this->db->execute(
            "DELETE FROM faqs WHERE faqable_type = ? AND faqable_id = ?", 
            [strtolower($faqableType), $faqableId]
        );
    }
    
    public function exists($faqableType, $faqableId)
    {
        $result = $this->db->fetchOne(
            "SELECT COUNT(*) as count FROM faqs WHERE faqable_type = ? AND faqable_id = ?", 
            [strtolower($faqableType), $faqableId]
        );
        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);
    }
}