<?php
namespace DeeLauLab\AzuraCast;

class Cover_Finder {
    private $settings;
    public function __construct($settings) { $this->settings = $settings; }
    private function _clean_title($title) { return trim(preg_replace('/\s*\|.*/', '', $title)); }
    private function _clean_artist($artist) { return trim(preg_replace('/\s*,.*/', '', $artist)); }
    public function get_cover_url($artist, $title) {
        $cleanArtist = $this->_clean_artist($artist); $cleanTitle = $this->_clean_title($title);
        if (empty($cleanArtist) || empty($cleanTitle)) { return $this->settings['fallback_cover_url'] ?? ''; }
        $transient_key = 'dllfh_cover_' . md5(strtolower($cleanArtist . $cleanTitle));
        $cached_url = get_transient($transient_key);
        if (false !== $cached_url) { return $cached_url === 'not_found' ? ($this->settings['fallback_cover_url'] ?? '') : $cached_url; }
        $apis_to_try = ['spotify', 'deezer', 'itunes', 'lastfm']; $cover_url = false;
        foreach ($apis_to_try as $api) {
            switch ($api) {
                case 'spotify': $cover_url = $this->_try_spotify($cleanArtist, $cleanTitle); break;
                case 'deezer': $cover_url = $this->_try_deezer($cleanArtist, $cleanTitle); break;
                case 'itunes': $cover_url = $this->_try_itunes($cleanArtist, $cleanTitle); break;
                case 'lastfm': $cover_url = $this->_try_lastfm($cleanArtist, $cleanTitle); break;
            }
            if ($cover_url) { break; }
        }
        if ($cover_url) { set_transient($transient_key, $cover_url, WEEK_IN_SECONDS); return $cover_url; } 
        else { set_transient($transient_key, 'not_found', DAY_IN_SECONDS); return $this->settings['fallback_cover_url'] ?? ''; }
    }
    private function _get_spotify_token() {
        $token = get_transient('dllfh_spotify_token'); if ($token) return $token;
        $id = $this->settings['spotify_client_id'] ?? ''; $secret = $this->settings['spotify_client_secret'] ?? ''; if (empty($id) || empty($secret)) return false;
        $response = wp_remote_post('https://accounts.spotify.com/api/token', ['headers' => ['Authorization' => 'Basic ' . base64_encode($id . ':' . $secret)],'body' => ['grant_type' => 'client_credentials']]);
        if (is_wp_error($response)) return false;
        $body = json_decode(wp_remote_retrieve_body($response), true); $token = $body['access_token'] ?? false;
        if ($token) { set_transient('dllfh_spotify_token', $token, $body['expires_in'] - 60); } return $token;
    }
    private function _try_spotify($artist, $title) {
        if (empty($this->settings['spotify_client_id']) || empty($this->settings['spotify_client_secret'])) return false;
        $token = $this->_get_spotify_token(); if (!$token) return false;
        $url = "https://api.spotify.com/v1/search?q=" . urlencode("artist:{$artist} track:{$title}") . "&type=track&limit=1";
        $response = wp_remote_get($url, ['headers' => ['Authorization' => 'Bearer ' . $token]]);
        if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) return false;
        $data = json_decode(wp_remote_retrieve_body($response), true); return $data['tracks']['items'][0]['album']['images'][0]['url'] ?? false;
    }
    private function _try_deezer($artist, $title) {
        $url = "https://api.deezer.com/search?q=" . urlencode("artist:\"{$artist}\" track:\"{$title}\"") . "&limit=1";
        $response = wp_remote_get($url); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) return false;
        $data = json_decode(wp_remote_retrieve_body($response), true); return $data['data'][0]['album']['cover_xl'] ?? false;
    }
    private function _try_itunes($artist, $title) {
        $url = "https://itunes.apple.com/search?term=" . urlencode("{$artist} {$title}") . "&entity=musicTrack&limit=1";
        $response = wp_remote_get($url); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) return false;
        $data = json_decode(wp_remote_retrieve_body($response), true); $artwork_url = $data['results'][0]['artworkUrl100'] ?? false;
        if ($artwork_url) { return str_replace('100x100', '600x600', $artwork_url); } return false;
    }
    private function _try_lastfm($artist, $title) {
        if (empty($this->settings['lastfm_api_key'])) return false; $api_key = $this->settings['lastfm_api_key'];
        $url = "https://ws.audioscrobbler.com/2.0/?method=track.getInfo&api_key={$api_key}&artist=" . urlencode($artist) . "&track=" . urlencode($title) . "&format=json";
        $response = wp_remote_get($url); if (is_wp_error($response) || wp_remote_retrieve_response_code($response) !== 200) return false;
        $data = json_decode(wp_remote_retrieve_body($response), true); $images = $data['track']['album']['image'] ?? false;
        if ($images && is_array($images)) { $largest_image = end($images); return $largest_image['#text'] ?? false; } return false;
    }
}