<?php

namespace MovieEngine\Api;

if (! defined("ABSPATH")) {
    exit; // Exit if accessed directly
}

class OmdbClient {

    private $api_key;
    private $base_url = 'https://www.omdbapi.com/';

    public function __construct() {
        $options = get_option('movie_engine_api_settings', []);
        $this->api_key = isset($options['movie_engine_omdb_api_key']) ? sanitize_text_field($options['movie_engine_omdb_api_key']) : '';
    }

    public function validate() {
        if (empty($this->api_key)) return false;

        $url = add_query_arg(['apikey' => $this->api_key, 't' => 'Batman'], 'http://www.omdbapi.com/');
        $response = wp_remote_get($url, [
            'timeout'   => 15,
            'sslverify' => false
        ]);

        $trans_key = 'movie_engine_omdb_error_' . md5($this->api_key);

        if (is_wp_error($response)) {
            set_transient($trans_key, $response->get_error_message(), HOUR_IN_SECONDS);
            return false;
        }

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

        if (isset($data['Response']) && $data['Response'] === 'True') {
            delete_transient($trans_key);
            return true;
        }

        $error = $data['Error'] ?? esc_html__('Unknown error', 'cine-movie-engine');
        set_transient($trans_key, $error, HOUR_IN_SECONDS);

        return false;
    }

    public function get_ratings($imdb_id) {
        $imdb_id = sanitize_text_field($imdb_id);
        if (empty($this->api_key) || empty($imdb_id)) {
            return false;
        }

        $cache_key = 'omdb_ratings_' . $imdb_id;
        $cached_data = \MovieEngine\Core\Cache::get($cache_key);
        if ($cached_data !== false) {
            return $cached_data;
        }

        $url = add_query_arg([
            'apikey' => $this->api_key,
            'i'      => $imdb_id,
        ], esc_url_raw($this->base_url));

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

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

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

        if (empty($data) || !isset($data['Response']) || $data['Response'] === 'False') {
            return false;
        }

        $result = [
            'imdb'      => $data['imdbRating'] ?? '',
            'tomatoes'  => $this->extract_rating($data['Ratings'] ?? [], 'Rotten Tomatoes'),
            'metacritic' => $data['Metascore'] ?? '',
            'votes'     => $data['imdbVotes'] ?? '',
        ];

        // Cache for 24 hours
        \MovieEngine\Core\Cache::set($cache_key, $result, DAY_IN_SECONDS);

        return $result;
    }

    private function extract_rating($ratings, $source) {
        if (!is_array($ratings)) return '';

        foreach ($ratings as $rating) {
            if ($rating['Source'] === $source) {
                return $rating['Value'];
            }
        }
        return '';
    }
}
