<?php
/**
 * CustomPost Model
 * Manages custom post entries
 */
namespace Models;

class CustomPost
{
    private static $pdo;

    public static function setPdo($pdo)
    {
        self::$pdo = $pdo;
    }

    /**
     * Get all posts of a type
     */
    public static function all($postType, $status = null)
    {
        $sql = "SELECT * FROM custom_posts WHERE post_type = ?";
        $params = [$postType];

        if ($status) {
            $sql .= " AND status = ?";
            $params[] = $status;
        }

        $sql .= " ORDER BY created_at DESC";

        $stmt = self::$pdo->prepare($sql);
        $stmt->execute($params);
        $results = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        // Parse fields_data
        foreach ($results as &$result) {
            $result['fields_data'] = json_decode($result['fields_data'], true) ?: [];
        }

        return $results;
    }

    /**
     * Get single post by ID
     */
    public static function find($id)
    {
        $stmt = self::$pdo->prepare("SELECT * FROM custom_posts WHERE id = ?");
        $stmt->execute([$id]);
        $result = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ($result) {
            $result['fields_data'] = json_decode($result['fields_data'], true) ?: [];
        }
        return $result;
    }

    /**
     * Get post by slug
     */
    public static function findBySlug($slug)
    {
        $stmt = self::$pdo->prepare("SELECT * FROM custom_posts WHERE slug = ?");
        $stmt->execute([$slug]);
        $result = $stmt->fetch(\PDO::FETCH_ASSOC);
        if ($result) {
            $result['fields_data'] = json_decode($result['fields_data'], true) ?: [];
        }
        return $result;
    }

    /**
     * Create post
     */
    public static function create($data)
    {
        $stmt = self::$pdo->prepare("
            INSERT INTO custom_posts (post_type, title, slug, content, excerpt, thumbnail, fields_data, status, author_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
        ");

        $fieldsData = is_array($data['fields_data'] ?? null)
            ? json_encode($data['fields_data'])
            : ($data['fields_data'] ?? '{}');

        $stmt->execute([
            $data['post_type'],
            $data['title'],
            $data['slug'],
            $data['content'] ?? '',
            $data['excerpt'] ?? '',
            $data['thumbnail'] ?? '',
            $fieldsData,
            $data['status'] ?? 'draft',
            $data['author_id'] ?? null
        ]);

        return self::$pdo->lastInsertId();
    }

    /**
     * Update post
     */
    public static function update($id, $data)
    {
        $fields = [];
        $values = [];

        $allowedFields = ['title', 'slug', 'content', 'excerpt', 'thumbnail', 'fields_data', 'status'];

        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $fields[] = "$field = ?";
                $value = $data[$field];
                if ($field === 'fields_data' && is_array($value)) {
                    $value = json_encode($value);
                }
                $values[] = $value;
            }
        }

        if (empty($fields))
            return false;

        $values[] = $id;
        $sql = "UPDATE custom_posts SET " . implode(', ', $fields) . ", updated_at = CURRENT_TIMESTAMP WHERE id = ?";

        $stmt = self::$pdo->prepare($sql);
        return $stmt->execute($values);
    }

    /**
     * Delete post
     */
    public static function delete($id)
    {
        // Delete term relationships
        $stmt = self::$pdo->prepare("DELETE FROM term_relationships WHERE post_id = ?");
        $stmt->execute([$id]);

        // Delete post
        $stmt = self::$pdo->prepare("DELETE FROM custom_posts WHERE id = ?");
        return $stmt->execute([$id]);
    }

    /**
     * Generate unique slug
     */
    public static function generateSlug($title, $excludeId = null)
    {
        $slug = strtolower(trim($title));
        $slug = preg_replace('/[^a-z0-9]+/', '-', $slug);
        $slug = trim($slug, '-');

        $originalSlug = $slug;
        $counter = 1;

        while (true) {
            $sql = "SELECT id FROM custom_posts WHERE slug = ?";
            $params = [$slug];

            if ($excludeId) {
                $sql .= " AND id != ?";
                $params[] = $excludeId;
            }

            $stmt = self::$pdo->prepare($sql);
            $stmt->execute($params);

            if (!$stmt->fetch()) {
                break;
            }

            $slug = $originalSlug . '-' . $counter;
            $counter++;
        }

        return $slug;
    }

    /**
     * Get posts with term
     */
    public static function getByTerm($termId)
    {
        $stmt = self::$pdo->prepare("
            SELECT cp.* FROM custom_posts cp
            JOIN term_relationships tr ON cp.id = tr.post_id
            WHERE tr.term_id = ?
            ORDER BY cp.created_at DESC
        ");
        $stmt->execute([$termId]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * Set post terms
     */
    public static function setTerms($postId, $termIds)
    {
        // Clear existing
        $stmt = self::$pdo->prepare("DELETE FROM term_relationships WHERE post_id = ?");
        $stmt->execute([$postId]);

        // Add new
        $stmt = self::$pdo->prepare("INSERT INTO term_relationships (post_id, term_id) VALUES (?, ?)");
        foreach ($termIds as $termId) {
            $stmt->execute([$postId, $termId]);
        }

        // Update term counts
        self::updateTermCounts($termIds);
    }

    /**
     * Get post terms
     */
    public static function getTerms($postId)
    {
        $stmt = self::$pdo->prepare("
            SELECT t.* FROM terms t
            JOIN term_relationships tr ON t.id = tr.term_id
            WHERE tr.post_id = ?
        ");
        $stmt->execute([$postId]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    /**
     * Update term counts
     */
    private static function updateTermCounts($termIds)
    {
        foreach ($termIds as $termId) {
            $stmt = self::$pdo->prepare("
                UPDATE terms SET count = (
                    SELECT COUNT(*) FROM term_relationships WHERE term_id = ?
                ) WHERE id = ?
            ");
            $stmt->execute([$termId, $termId]);
        }
    }

    /**
     * Search posts
     */
    public static function search($postType, $query)
    {
        $stmt = self::$pdo->prepare("
            SELECT * FROM custom_posts 
            WHERE post_type = ? AND (title LIKE ? OR content LIKE ?)
            ORDER BY created_at DESC
        ");
        $searchTerm = '%' . $query . '%';
        $stmt->execute([$postType, $searchTerm, $searchTerm]);
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }
}
