<?php

namespace MediaTrim\Core;

use MediaTrim\Traits\Singleton;

defined('ABSPATH') || exit;

/**
 * Class StockManager
 *
 * Handles Pexels Stock Images API and importing to Media Library.
 *
 * @package MediaTrim\Core
 */
class StockManager
{
    use Singleton;

    /**
     * API Base URL
     */
    private $api_base = 'https://api.pexels.com/v1/';

    /**
     * Constructor
     */
    public function __construct()
    {
        $this->init_hooks();
    }

    /**
     * Initialize hooks
     */
    public function init_hooks()
    {
        add_action('wp_ajax_mtrim_get_stock_images', [$this, 'ajax_get_stock_images']);
        add_action('wp_ajax_mtrim_import_stock_image', [$this, 'ajax_import_stock_image']);
    }

    /**
     * Get Pexels API Key from settings
     */
    private function get_api_key()
    {
        $settings = get_option('mtrim_settings', []);
        return isset($settings['pexels_api_key']) ? $settings['pexels_api_key'] : '';
    }

    /**
     * AJAX handler to search stock images
     */
    public function ajax_get_stock_images()
    {
        check_ajax_referer('mtrim_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'media-trim')]);
        }

        $api_key = $this->get_api_key();
        if (empty($api_key)) {
            wp_send_json_error(['message' => __('Please set Pexels API Key in Settings first', 'media-trim')]);
        }

        $query = isset($_POST['query']) ? sanitize_text_field(wp_unslash($_POST['query'])) : '';
        $page = isset($_POST['page']) ? absint($_POST['page']) : 1;
        $per_page = 20;

        $url = add_query_arg([
            'query' => $query,
            'page' => $page,
            'per_page' => $per_page,
        ], $this->api_base . 'search');

        if (empty($query)) {
            $url = add_query_arg([
                'page' => $page,
                'per_page' => $per_page,
            ], $this->api_base . 'curated');
        }

        $response = wp_remote_get($url, [
            'headers' => [
                'Authorization' => $api_key,
            ],
            'timeout' => 15,
        ]);

        if (is_wp_error($response)) {
            wp_send_json_error(['message' => $response->get_error_message()]);
        }

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

        if (isset($data['error'])) {
            wp_send_json_error(['message' => $data['error']]);
        }

        wp_send_json_success($data);
    }

    /**
     * AJAX handler to import stock image
     */
    public function ajax_import_stock_image()
    {
        check_ajax_referer('mtrim_admin_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Unauthorized', 'media-trim')]);
        }

        $image_url = isset($_POST['image_url']) ? esc_url_raw(wp_unslash($_POST['image_url'])) : '';
        $title = isset($_POST['title']) ? sanitize_text_field(wp_unslash($_POST['title'])) : '';

        if (empty($image_url)) {
            wp_send_json_error(['message' => __('Invalid image URL', 'media-trim')]);
        }

        // Include required files for sideloading
        require_once(ABSPATH . 'wp-admin/includes/media.php');
        require_once(ABSPATH . 'wp-admin/includes/file.php');
        require_once(ABSPATH . 'wp-admin/includes/image.php');

        // Download and attach image
        $attachment_id = media_sideload_image($image_url, 0, $title, 'id');

        if (is_wp_error($attachment_id)) {
            wp_send_json_error(['message' => $attachment_id->get_error_message()]);
        }

        wp_send_json_success([
            'message' => __('Image imported successfully!', 'media-trim'),
            'attachment_id' => $attachment_id,
        ]);
    }
}
