<?php
class Article {
    private $db;

    public function __construct() {
        $database = new Database();
        $this->db = $database->getConnection();
    }

    public function create($data) {
        try {
            $query = "INSERT INTO articles (title, slug, content, excerpt, featured_image, type, status, author_id, category_id, published_at, is_ai_generated, source_url, meta_title, meta_description)
                      VALUES (:title, :slug, :content, :excerpt, :featured_image, :type, :status, :author_id, :category_id, :published_at, :is_ai_generated, :source_url, :meta_title, :meta_description)";

            $stmt = $this->db->prepare($query);

            $slug = $data['slug'] ?? generate_slug($data['title']);
            $published_at = $data['status'] === 'published' ? date('Y-m-d H:i:s') : null;

            $stmt->bindParam(':title', $data['title']);
            $stmt->bindParam(':slug', $slug);
            $stmt->bindParam(':content', $data['content']);
            $stmt->bindParam(':excerpt', $data['excerpt']);
            $stmt->bindParam(':featured_image', $data['featured_image']);
            $stmt->bindParam(':type', $data['type']);
            $stmt->bindParam(':status', $data['status']);
            $stmt->bindParam(':author_id', $data['author_id']);
            $stmt->bindParam(':category_id', $data['category_id']);
            $stmt->bindParam(':published_at', $published_at);
            $stmt->bindParam(':is_ai_generated', $data['is_ai_generated']);
            $stmt->bindParam(':source_url', $data['source_url']);
            $stmt->bindParam(':meta_title', $data['meta_title']);
            $stmt->bindParam(':meta_description', $data['meta_description']);

            if ($stmt->execute()) {
                return $this->db->lastInsertId();
            }

            return false;
        } catch (Exception $e) {
            error_log("Create article error: " . $e->getMessage());
            return false;
        }
    }

    public function update($id, $data) {
        try {
            $query = "UPDATE articles SET title = :title, slug = :slug, content = :content, excerpt = :excerpt,
                      featured_image = :featured_image, type = :type, status = :status, category_id = :category_id,
                      meta_title = :meta_title, meta_description = :meta_description, updated_at = NOW()";

            if ($data['status'] === 'published') {
                $query .= ", published_at = :published_at";
            }

            $query .= " WHERE id = :id";

            $stmt = $this->db->prepare($query);

            $slug = $data['slug'] ?? generate_slug($data['title']);

            $stmt->bindParam(':id', $id);
            $stmt->bindParam(':title', $data['title']);
            $stmt->bindParam(':slug', $slug);
            $stmt->bindParam(':content', $data['content']);
            $stmt->bindParam(':excerpt', $data['excerpt']);
            $stmt->bindParam(':featured_image', $data['featured_image']);
            $stmt->bindParam(':type', $data['type']);
            $stmt->bindParam(':status', $data['status']);
            $stmt->bindParam(':category_id', $data['category_id']);
            $stmt->bindParam(':meta_title', $data['meta_title']);
            $stmt->bindParam(':meta_description', $data['meta_description']);

            if ($data['status'] === 'published') {
                $published_at = date('Y-m-d H:i:s');
                $stmt->bindParam(':published_at', $published_at);
            }

            $result = $stmt->execute();

            // Auto-publish to international platforms if this is an external article being published
            if ($result && $data['status'] === 'published' && $data['type'] === 'external') {
                $this->autoPublishToInternationalPlatforms($id);
            }

            return $result;
        } catch (Exception $e) {
            error_log("Update article error: " . $e->getMessage());
            return false;
        }
    }

    private function autoPublishToInternationalPlatforms($articleId) {
        try {
            // Get article info to check if it's external
            $articleInfo = $this->getById($articleId);
            if (!$articleInfo || $articleInfo['type'] !== 'external') {
                return; // Only auto-publish external articles
            }

            // Check if auto-publishing is enabled
            $settings = new Settings();
            $autoPublishEnabled = $settings->get('auto_publish_enabled', '0');

            if ($autoPublishEnabled) {
                $publisher = new Publisher();
                $result = $publisher->publishToExternalPlatforms($articleId);
                if ($result) {
                    error_log("Auto-published external article {$articleId} to international platforms");
                } else {
                    error_log("Failed to auto-publish article {$articleId} to international platforms");
                }
            }
        } catch (Exception $e) {
            error_log("Auto-publish error: " . $e->getMessage());
        }
    }

    public function delete($id) {
        try {
            $query = "DELETE FROM articles WHERE id = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Delete article error: " . $e->getMessage());
            return false;
        }
    }

    public function updateStatus($id, $status) {
        try {
            $published_at = null;
            if ($status === 'published') {
                $published_at = date('Y-m-d H:i:s');
            }

            $query = "UPDATE articles SET status = :status, published_at = :published_at, updated_at = NOW() WHERE id = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            $stmt->bindParam(':status', $status);
            $stmt->bindParam(':published_at', $published_at);

            $result = $stmt->execute();

            // Auto-publish to international platforms when article is published
            if ($result && $status === 'published') {
                $this->autoPublishToInternationalPlatforms($id);
            }

            return $result;
        } catch (Exception $e) {
            error_log("Update article status error: " . $e->getMessage());
            return false;
        }
    }

    public function getById($id) {
        try {
            $query = "SELECT a.*, u.username as author_name, c.name as category_name
                      FROM articles a
                      LEFT JOIN users u ON a.author_id = u.id
                      LEFT JOIN categories c ON a.category_id = c.id
                      WHERE a.id = :id";

            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            $stmt->execute();

            return $stmt->fetch();
        } catch (Exception $e) {
            error_log("Get article by ID error: " . $e->getMessage());
            return false;
        }
    }

    public function getBySlug($slug) {
        try {
            $query = "SELECT a.*, u.username as author_name, c.name as category_name
                      FROM articles a
                      LEFT JOIN users u ON a.author_id = u.id
                      LEFT JOIN categories c ON a.category_id = c.id
                      WHERE a.slug = :slug AND a.status = 'published'";

            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':slug', $slug);
            $stmt->execute();

            $article = $stmt->fetch();

            if ($article) {
                $this->incrementViews($article['id']);
            }

            return $article;
        } catch (Exception $e) {
            error_log("Get article by slug error: " . $e->getMessage());
            return false;
        }
    }

    public function getAll($type = null, $limit = 10, $offset = 0, $category_id = null, $status = null, $search = null) {
        try {
            $query = "SELECT a.*, u.username as author_name, c.name as category_name, c.color as category_color
                      FROM articles a
                      LEFT JOIN users u ON a.author_id = u.id
                      LEFT JOIN categories c ON a.category_id = c.id
                      WHERE 1=1";

            // For frontend, only show published articles (when both status and search are null)
            if ($status === null && $search === null) {
                $query .= " AND a.status = 'published'";
            }

            // For admin, filter by status if specified
            if ($status) {
                $query .= " AND a.status = :status";
            }

            if ($type) {
                $query .= " AND a.type = :type";
            }

            if ($category_id) {
                $query .= " AND a.category_id = :category_id";
            }

            if ($search) {
                $query .= " AND (a.title LIKE :search OR a.content LIKE :search OR a.excerpt LIKE :search)";
            }

            $query .= " ORDER BY a.created_at DESC LIMIT :limit OFFSET :offset";

            $stmt = $this->db->prepare($query);

            if ($status) {
                $stmt->bindParam(':status', $status);
            }

            if ($type) {
                $stmt->bindParam(':type', $type);
            }

            if ($category_id) {
                $stmt->bindParam(':category_id', $category_id);
            }

            if ($search) {
                $searchParam = '%' . $search . '%';
                $stmt->bindParam(':search', $searchParam);
            }

            $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
            $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);

            $stmt->execute();

            return $stmt->fetchAll();
        } catch (Exception $e) {
            error_log("Get all articles error: " . $e->getMessage());
            return [];
        }
    }

    public function search($query, $type = null, $limit = 10, $offset = 0) {
        try {
            $sql = "SELECT a.*, u.username as author_name, c.name as category_name
                    FROM articles a
                    LEFT JOIN users u ON a.author_id = u.id
                    LEFT JOIN categories c ON a.category_id = c.id
                    WHERE a.status = 'published' AND (a.title LIKE :query OR a.content LIKE :query)";

            if ($type) {
                $sql .= " AND a.type = :type";
            }

            $sql .= " ORDER BY a.published_at DESC LIMIT :limit OFFSET :offset";

            $stmt = $this->db->prepare($sql);

            $searchQuery = "%{$query}%";
            $stmt->bindParam(':query', $searchQuery);

            if ($type) {
                $stmt->bindParam(':type', $type);
            }

            $stmt->bindParam(':limit', $limit, PDO::PARAM_INT);
            $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);

            $stmt->execute();

            return $stmt->fetchAll();
        } catch (Exception $e) {
            error_log("Search articles error: " . $e->getMessage());
            return [];
        }
    }

    public function incrementViews($id) {
        try {
            $query = "UPDATE articles SET views = views + 1 WHERE id = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Increment views error: " . $e->getMessage());
            return false;
        }
    }

    public function incrementLikes($id) {
        try {
            $query = "UPDATE articles SET likes = likes + 1 WHERE id = :id";
            $stmt = $this->db->prepare($query);
            $stmt->bindParam(':id', $id);
            return $stmt->execute();
        } catch (Exception $e) {
            error_log("Increment likes error: " . $e->getMessage());
            return false;
        }
    }

    public function getCount($type = null, $category_id = null, $status = null, $search = null) {
        try {
            $query = "SELECT COUNT(*) as count FROM articles WHERE 1=1";

            // For frontend, only count published articles (when both status and search are null)
            if ($status === null && $search === null) {
                $query .= " AND status = 'published'";
            }

            // For admin, filter by status if specified
            if ($status) {
                $query .= " AND status = :status";
            }

            if ($type) {
                $query .= " AND type = :type";
            }

            if ($category_id) {
                $query .= " AND category_id = :category_id";
            }

            if ($search) {
                $query .= " AND (title LIKE :search OR content LIKE :search OR excerpt LIKE :search)";
            }

            $stmt = $this->db->prepare($query);

            if ($status) {
                $stmt->bindParam(':status', $status);
            }

            if ($type) {
                $stmt->bindParam(':type', $type);
            }

            if ($category_id) {
                $stmt->bindParam(':category_id', $category_id);
            }

            if ($search) {
                $searchParam = '%' . $search . '%';
                $stmt->bindParam(':search', $searchParam);
            }

            $stmt->execute();

            $result = $stmt->fetch();
            return $result['count'];
        } catch (Exception $e) {
            error_log("Get article count error: " . $e->getMessage());
            return 0;
        }
    }
}
?>