<?php

/**
 * Eurobydlení neumí PNG fotky (jako třeba mapy).
 *
 * Proto když na takovou narazíme tak ji zkusíme převést na JPG.
 */
class Dalten_Export_Api_Eurobydleni extends Dalten_Export_Api_SrealityLike
{
    protected function _addImages($listingCode, array $images)
    {
        $success = true;
        $status = 200;
        $message = "";
        $images = array_values($images);
        foreach ($images as $i => $image) {
            $file = realpath($image['soubor']);
            if ($file) {
                $fileContents = file_get_contents($file);
                if (str_ends_with($file, '.png')) {
                    $convertedImage = imagecreatefromstring($fileContents);
                    ob_start();
                    imagejpeg($convertedImage);
                    $fileContents = ob_get_contents();
                    ob_end_clean();
                }

                $image = [
                    'data' => $fileContents,
                    'main' => !$i,
                    'order' => $image['poradi'],
                    'alt' => $image['popis'],
                    'photo_rkid' => $image['id'],
                ];

                $response = $this->_backend->addPhoto(
                    $this->_getSessionId(),
                    null,
                    $listingCode,
                    $image
                );

                $status = $response->status;

                if ($status != 200) {
                    $success = false;
                    $message = $message . PHP_EOL . basename($file) . ' - ' . $this->_translatePhotoErrorMessage($response->status, $response->statusMessage);
                }

                if ($status == 407) {
                    return new Dalten_Export_Api_ServerResponseFatal(
                        false,
                        407,
                        sprintf('Selhal export %d. fotografie (photo_rkid=%d, soubor %s).', $image['order'], $image['photo_rkid'], basename($file))
                    );
                }
            }
        }

        if (empty($message)) {
            $message = 'OK';
        }

        return new Dalten_Export_Api_ServerResponse($success, $status, $message);
    }

}