<?php
/**
 * Pexels API Handler
 *
 * @package AIContentGenerator
 */

namespace AICG;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Handles Pexels API for image fetching
 */
class Pexels_Api
{

    /**
     * API base URL
     */
    const API_URL = 'https://api.pexels.com/v1';

    /**
     * Get API key
     */
    private function get_api_key()
    {
        return get_option('roidaico_pexels_api_key', '');
    }

    /**
     * Make API request
     */
    private function request($endpoint, $params = array(), $api_key = null)
    {
        $key = $api_key ?: $this->get_api_key();

        if (empty($key)) {
            return new \WP_Error('no_api_key', __('Pexels API key is not configured.', 'roidnet-ai-content-generator'));
        }

        $url = self::API_URL . $endpoint;

        if (!empty($params)) {
            $url = add_query_arg($params, $url);
        }

        $response = wp_remote_get($url, array(
            'timeout' => 30,
            'headers' => array(
                'Authorization' => $key,
            ),
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        $body = wp_remote_retrieve_body($response);
        $decoded = json_decode($body, true);

        if (wp_remote_retrieve_response_code($response) !== 200) {
            $error_message = isset($decoded['error'])
                ? $decoded['error']
                : __('Unknown Pexels API error.', 'roidnet-ai-content-generator');
            return new \WP_Error('api_error', $error_message);
        }

        return $decoded;
    }

    /**
     * Test API connection
     */
    public function test_connection($api_key = null)
    {
        $result = $this->request('/search', array('query' => 'test', 'per_page' => 1), $api_key);

        if (is_wp_error($result)) {
            return $result;
        }

        return true;
    }

    /**
     * Search for images
     */
    public function search_images($query, $count = 5, $orientation = 'landscape')
    {
        // Clean the query before search
        $query = $this->clean_query($query);

        $params = array(
            'query' => $query,
            'per_page' => min($count, 80),
            'orientation' => $orientation,
        );

        $result = $this->request('/search', $params);

        if (is_wp_error($result)) {
            return $result;
        }

        if (!isset($result['photos']) || empty($result['photos'])) {
            return new \WP_Error('no_images', __('No images found for this query.', 'roidnet-ai-content-generator'));
        }

        $images = array();
        foreach ($result['photos'] as $photo) {
            $images[] = array(
                'id' => $photo['id'],
                'url' => $photo['src']['large2x'],
                'url_medium' => $photo['src']['medium'],
                'url_original' => $photo['src']['original'],
                'photographer' => $photo['photographer'],
                'alt' => $photo['alt'] ?: $query,
                'width' => $photo['width'],
                'height' => $photo['height'],
            );
        }

        return $images;
    }

    /**
     * Check if image is already used
     */
    public function is_duplicate($pexels_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'roidaico_used_images';

        $exists = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table WHERE pexels_id = %s",
            $pexels_id
        ));

        return $exists > 0;
    }

    /**
     * Download image and add to media library
     */
    public function download_image($image_data, $post_id = 0)
    {
        // Check for duplicate
        if ($this->is_duplicate($image_data['id'])) {
            return new \WP_Error('duplicate_image', __('This image has already been used.', 'roidnet-ai-content-generator'));
        }

        require_once ABSPATH . 'wp-admin/includes/file.php';
        require_once ABSPATH . 'wp-admin/includes/media.php';
        require_once ABSPATH . 'wp-admin/includes/image.php';

        // Download the image
        $temp_file = download_url($image_data['url']);

        if (is_wp_error($temp_file)) {
            return $temp_file;
        }

        // Prepare file array
        $file_array = array(
            'name' => 'pexels-' . $image_data['id'] . '.jpg',
            'tmp_name' => $temp_file,
        );

        // Upload to media library
        $attachment_id = media_handle_sideload($file_array, $post_id, $image_data['alt']);

        // Clean up temp file
        if (file_exists($temp_file)) {
            @unlink($temp_file);
        }

        if (is_wp_error($attachment_id)) {
            return $attachment_id;
        }

        // Update alt text
        update_post_meta($attachment_id, '_wp_attachment_image_alt', $image_data['alt']);

        // Add Pexels attribution
        update_post_meta($attachment_id, '_roidaico_pexels_photographer', $image_data['photographer']);
        update_post_meta($attachment_id, '_roidaico_pexels_id', $image_data['id']);

        // Record usage to prevent duplicates
        $this->record_image_usage($image_data['id'], $attachment_id);

        return $attachment_id;
    }

    /**
     * Record image usage in database
     */
    private function record_image_usage($pexels_id, $attachment_id)
    {
        global $wpdb;
        $table = $wpdb->prefix . 'roidaico_used_images';

        // Generate hash from pexels ID
        $hash = hash('sha256', $pexels_id);

        $wpdb->insert(
            $table,
            array(
                'pexels_id' => $pexels_id,
                'image_hash' => $hash,
                'attachment_id' => $attachment_id,
                'used_at' => current_time('mysql'),
            ),
            array('%s', '%s', '%d', '%s')
        );
    }

    /**
     * Get a unique image for a keyword (skips duplicates)
     */
    public function get_unique_image($query, $orientation = 'landscape')
    {
        // Try exact search first
        $images = $this->search_images($query, 15, $orientation);

        if (is_wp_error($images)) {
            return $images;
        }

        // Find first unused image
        foreach ($images as $image) {
            if (!$this->is_duplicate($image['id'])) {
                return $image;
            }
        }

        return new \WP_Error('no_unique_image', __('No unique images available for this query.', 'roidnet-ai-content-generator'));
    }

    /**
     * Clean and simplify a search query for Pexels
     */
    public function clean_query($query)
    {
        // Remove special characters and extra whitespace
        $query = preg_replace('/[^\p{L}\p{N}\s]/u', '', $query);
        $query = preg_replace('/\s+/', ' ', trim($query));

        // If it's mostly Arabic, we can't really "clean" it for Pexels, return as is
        if (preg_match('/\p{Arabic}/u', $query)) {
            return $query;
        }

        // For English, simplify to a few keywords
        $words = explode(' ', $query);
        
        // Remove common stopwords (very basic list)
        $stopwords = array('a', 'an', 'the', 'and', 'or', 'but', 'in', 'on', 'at', 'with', 'for', 'of', 'by', 'photo', 'image', 'picture', 'showing', 'of', 'a', 'modern', 'luxurious', 'professional');
        $filtered_words = array_filter($words, function($word) use ($stopwords) {
            return !in_array(strtolower($word), $stopwords) && strlen($word) > 2;
        });

        if (empty($filtered_words)) {
            return !empty($words[0]) ? $words[0] : 'office';
        }

        // Use only first 3-4 keywords
        return implode(' ', array_slice($filtered_words, 0, 4));
    }
}
