<?php

namespace CCDN\Helpers;

use CCDN\Helpers\Api\Response\ResponseInterface;
use CCDN\Helpers\DB\Model;
use CCDN\Helpers\Entities\Config;
use FileUploader;

class CCDNUploadPoster
{
    /**
     * @param  Config  $config
     * @param  ResponseInterface  $response
     * @param  int  $postId
     * @return array|null
     */
    public static function upload(Config $config, ResponseInterface $response, $postId = 0)
    {
        require_once ENGINE_DIR.'/classes/uploads/upload.class.php';

        $xfParam = [];
        $xfields = XFields::loadNative();
        foreach ($xfields as $item) {
            if ($item[0] === $config->new_franchise_download_poster) {
                $xfParam = $item;
                break;
            }
        }

        global $member_id, $config, $member_id_group;
        $_REQUEST['xfname'] = $config->new_franchise_download_poster;
        $_POST['imageurl'] = $response->getPoster();
        $config['max_up_side'] = $xfParam[9];
        $config['max_up_size'] = $xfParam[10];
        $config['min_up_side'] = $xfParam[22];
        $config['files_allow'] = false;
        $member_id_group[$member_id['user_group']]['allow_file_upload'] = false;

        $uploader = new FileUploader(
            'xfieldsimage',
            $postId,
            $member_id['name'],
            $xfParam[13],
            (int) $config['t_seite'],
            $xfParam[12] ? true : false,
            $xfParam[11] ? true : false,
            0,
            (int) $config['t_seite'],
            false
        );

        return json_decode($uploader->FileUpload(), true);
    }

    /**
     * @param  int  $postId
     * @return bool
     */
    public static function deleteImage($postId)
    {

        $model = new Model();

        $images = $model->select("SELECT `images`  FROM `{$model->getPrefix()}_images` WHERE  `news_id` ={$postId}");

        if (!empty($images)) {

            $model->query("DELETE FROM `{$model->getPrefix()}_images` WHERE `news_id` ={$postId}");

            $images = explode('|||', $images['images']);

            foreach ($images as $image) {

                $url_image = explode('/', $image);

                if (count($url_image) === 2) {
                    $folder_prefix = $url_image[0].'/';
                    $image = $url_image[1];
                } else {
                    $folder_prefix = '';
                    $image = $url_image[0];

                }
                $image = totranslit($image);

                @unlink(ROOT_DIR.'/uploads/posts/'.$folder_prefix.$image);
                @unlink(ROOT_DIR.'/uploads/posts/'.$folder_prefix.'thumbs/'.$image);
                @unlink(ROOT_DIR.'/uploads/posts/'.$folder_prefix.'medium/'.$image);
            }

            return true;
        }
        return false;
    }
}
