<?php

if (!defined('ABSPATH')) {
    exit;
}

/**
 * External API handler for title-article operations
 */
class ContentCraftAI_TitleArticleAPI extends ContentCraftAI_ApiBase
{
    /**
     * Generate titles based on keywords from the external API
     * 
     * @param array $data The data containing keywords and other parameters
     * @return array Result with generated titles
     */
    public function generate_titles($data)
    {
        // Process keywords - handle both comma-separated string and array inputs
        $keywords = $data['keywords'];
        if (is_array($keywords)) {
            $keywords = implode(', ', array_map('trim', $keywords));
        } else {
            // Handle newlines and commas
            $keywords = str_replace(["\r\n", "\r", "\n"], ',', $keywords);
            $keywords_array = array_map('trim', explode(',', $keywords));
            $keywords_array = array_filter($keywords_array); // Remove empty entries

            // Limit to maximum 10 keywords
            if (count($keywords_array) > 10) {
                $keywords_array = array_slice($keywords_array, 0, 10);
            }

            $keywords = implode(', ', $keywords_array);
        }

        if (empty($keywords)) {
            return [
                'success' => false,
                'message' => 'No keywords provided'
            ];
        }

        // Prepare request body
        $request_body = [
            'keywords' => $keywords,
            'count' => intval($data['titleCount'] ?? 5),
            'language' => $data['language'] ?? 'en',
            'category' => $data['categoryName'] ?? '',
            'aiModel' => $data['aiModel'] ?? 'gpt-4o-mini'
        ];

        // Make API request
        $response = wp_remote_post($this->api_url . '/articles/keywords/generate-titles', [
            'headers' => $this->get_common_headers(),
            'body' => json_encode($request_body, JSON_UNESCAPED_UNICODE),
            'timeout' => 120
        ]);

        // Use parent method to handle the API response
        $api_data = $this->handle_response($response);

        // If the response was not successful, return the error
        if (!isset($api_data['success']) || !$api_data['success']) {
            return [
                'success' => false,
                'message' => $api_data['message'] ?? 'Failed to generate titles'
            ];
        }

        // Process titles to remove any numbering (e.g., "1. Title" becomes "Title")
        $titles = array_map(function ($title) {
            return trim(preg_replace('/^\d+\.\s*"|"$/', '', $title));
        }, $api_data['titles']);

        // Prepare keyword list for response
        $keyword_list = array_map('trim', explode(',', $keywords));
        $keyword_list = array_filter($keyword_list);

        return [
            'success' => true,
            'data' => [
                'titles' => $titles,
                'keywords' => $keyword_list
            ]
        ];
    }
}
