<?php

namespace auctionforge\inc;

use auctionforge\inc\abs\ImageModel;
use auctionforge\inc\helpers\LotLogging;
use auctionforge\inc\helpers\SettingsHelper;
use auctionforge\inc\model\Lot;
use WP_Post;

class ImageUploader extends ImageModel
{
    /**
     * Initialization of primary parameters
     * @param $postId
     * @param $lot Lot
     * @param $logger LotLogging
     */
    public function __construct($postId, $lot, $logger)
    {
        $this->setPostId($postId);
        $this->setLot($lot);
        $this->setLogger($logger);
        $this->setPrefixImage();
        $this->setImageCloned($lot->getImagesCloned());

        $this->initImageParams();

        $this->setImageList();
    }

    public static function deleteLotAttachment($postId)
    {
        if (has_post_thumbnail($postId)) {
            $attachments = get_attached_media('', $postId);
            self::deleteTrashAttachment($attachments);
        }
    }

    /**
     * Delete old post attachments
     * @return void
     */
    public function deleteOldAttachment()
    {
        $attachments = get_attached_media('', $this->getPostId());
        self::deleteTrashAttachment($attachments);
    }

    /**
     * @param $attachments WP_Post[]
     */
    public static function deleteTrashAttachment($attachments) {
        if (!empty($attachments) && is_array($attachments)) {
            /** @var WP_Post $attachment */
            foreach ($attachments as $attachment) {
                if ($attachment->post_type == self::LABEL_ATTACH) {
                    wp_delete_attachment($attachment->ID, true);
                }
            }
        }
    }

    /**
     * Download images from bidspirit server and assign them to their respective posts
     * @return void
     */
    public function upload()
    {
        if (!empty($this->getImageList())) {
            $attachIds = array();
            $i = 0;

            $this->deleteMetaImageOriginal($this->getPostId());
            foreach ($this->getImageList() as $image) {
                $tmpImg = download_url($image[self::LABEL_CUSTOM], 10);
                if (!is_wp_error($tmpImg)) {
                    $file_array = array(
                        'name' => uniqid() . "_" . basename($image[self::LABEL_CUSTOM]),
                        'tmp_name' => $tmpImg
                    );
                    $attachId = media_handle_sideload($file_array, $this->getPostId());

                    if ($i == 0) {
                        if (!is_wp_error($attachId) && set_post_thumbnail($this->getPostId(), $attachId)) {
                            $this->setPostThumbnailSet(true);
                        } else {
                            $this->instanceLogger()->setErrors(["Main picture setting error"]);
                        }
                    }

                    $i++;
                } else {
                    $this->instanceLogger()->setErrors(["Image saving error: " . $image[self::LABEL_CUSTOM]]);
                }

                @unlink($tmpImg);
            }
            $postData = array(
                'ID' => $this->getPostId(),
                'meta_input' => $attachIds,
            );
            $update = wp_update_post($postData);
            if (intval($update) == 0 || is_wp_error($update)) {
                $this->instanceLogger()->setErrors(["Lot update error when saving images"]);
            }
        } else {
            $this->instanceLogger()->setErrors(["Image list empty"]);
        }
    }

    /**
     * @param $postId int
     * @return void
     */
    private function deleteMetaImageOriginal($postId) {
        $db = InstanceDB::getInstanceDB();
        $sql = "DELETE FROM " . $db->postmeta . " WHERE meta_key LIKE 'lot_image_original%' AND post_id = %d";
        $sql = $db->prepare($sql, $postId);
        $db->query($sql);
    }
}