<?php
namespace rosengart\realestate\services;

use Craft;
use craft\base\Component;
use GuzzleHttp\Client;

class ApiService extends Component
{
    private const ACCESS_KEY = '25c8781ce6$440250NAB6de48@4b';
    private const HASH_KEY = 'HG82hhaAY0193KjkjhHZ719OHEDZIUHBIUCGHVOJVH84F3HBhbhjbvgHGZUI2GIO2U';
    private const API_ENDPOINT = 'https://ws.rosengart.mc/listings/sales';

    public function getListings()
    {
        // Cache the results for 1 hour to stay performant
        return Craft::$app->getCache()->getOrSet('real_estate_listings', function() {
            $timestamp = time();
            $hash = $timestamp . "-" . hash_hmac('ripemd320', self::ACCESS_KEY, self::HASH_KEY . $timestamp);

            $client = new Client();
            try {
                $response = $client->request('GET', self::API_ENDPOINT, [
                    'headers' => [
                        'AUTHCLEHASH' => $hash,
                        'Accept' => 'application/json',
                    ]
                ]);

                return json_decode($response->getBody()->getContents(), true);
            } catch (\Exception $e) {
                Craft::error("API Error: " . $e->getMessage(), __METHOD__);
                return null;
            }
        }, 3600);
    }

    public function getPropertyByRef($ref)
    {
        $all = $this->getListings();
        if (!$all) return null;

        foreach ($all as $item) {
            if (isset($item['refP']) && $item['refP'] == $ref) {
                return $item;
            }
        }
        return null;
    }
}