<?php

namespace App\Models;

class Author
{
    private $db;

    public function __construct()
    {
        $this->db = \App\Database::getInstance();
    }

    public function getAll()
    {
        $authors = $this->db->fetchAll("SELECT * FROM authors ORDER BY created_at DESC");
        
        foreach ($authors as &$author) {
            if (!empty($author['social_links'])) {
                $author['social_links'] = json_decode($author['social_links'], true);
            }
        }
        
        return $authors;
    }

    public function getById($id)
    {
        $author = $this->db->fetchOne("SELECT * FROM authors WHERE id = ?", [$id]);
        
        if ($author && !empty($author['social_links'])) {
            $author['social_links'] = json_decode($author['social_links'], true);
        }
        
        return $author;
    }

    public function create($data)
    {
        $socialLinks = '';
        if (isset($data['social_links']) && is_array($data['social_links'])) {
            $socialLinks = json_encode($data['social_links']);
        }

        $this->db->execute("
            INSERT INTO authors (name, image, description, social_links, created_at) 
            VALUES (?, ?, ?, ?, datetime('now'))
        ", [
            $data['name'] ?? '',
            $data['image'] ?? '',
            $data['description'] ?? '',
            $socialLinks
        ]);

        return $this->db->lastInsertId();
    }

    public function update($id, $data)
    {
        $socialLinks = '';
        if (isset($data['social_links']) && is_array($data['social_links'])) {
            $socialLinks = json_encode($data['social_links']);
        }

        return $this->db->execute("
            UPDATE authors 
            SET name = ?, image = ?, description = ?, social_links = ?, updated_at = datetime('now')
            WHERE id = ?
        ", [
            $data['name'] ?? '',
            $data['image'] ?? '',
            $data['description'] ?? '',
            $socialLinks,
            $id
        ]);
    }

    public function delete($id)
    {
        return $this->db->execute("DELETE FROM authors WHERE id = ?", [$id]);
    }

    public function search($query)
    {
        $searchTerm = '%' . $query . '%';
        $authors = $this->db->fetchAll("
            SELECT * FROM authors 
            WHERE name LIKE ? OR description LIKE ?
            ORDER BY created_at DESC
        ", [$searchTerm, $searchTerm]);
        
        foreach ($authors as &$author) {
            if (!empty($author['social_links'])) {
                $author['social_links'] = json_decode($author['social_links'], true);
            }
        }
        
        return $authors;
    }
}