<?php


namespace Shop\Application\Shopping\CreateFileFromOrderItems;


use Diamond\Application\Imaging\ImagingService;
use ExportEngine\Exporter;

class CreateFileFromOrderItemsHandler
{

    protected $imagingService;

    public function __construct(ImagingService $imagingService)
    {
        $this->imagingService = $imagingService;
    }

    /**
     * @param CreateFileFromOrderItemsCommand $command
     */
    public function handle(CreateFileFromOrderItemsCommand $command): void
    {
        $driver = \ExportEngine\Factories\DriverFactory::buildXls();

        $exporter = new Exporter($driver);

        $exporter->setHeader([
            'id' ,
            'order_id',
            'name' ,
            'brand',
            'article',
            'desc',
            'price',
            'amount',
            'menager_comment',
            'destination' ,
            'ref_id'
        ]);

        $items = $command->getItems();

        foreach($items as $item){
            $exporter->addRow([
                'id' => $item['id'],
                'order_id' => $item['order_id'],
                'name' => $item['name'],
                'brand' => $item['brand'],
                'article' => $item['article'],
                'desc' => $item['desc'],
                'price' => $item['price'],
                'amount' => $item['amount'],
                'menager_comment' => $item['menager_comment'],
                'destination' => $item['destination'],
                'ref_id'=>$item['ref_id']
            ]);
        }

        $path = $this->imagingService->getCacheDir().'/docs';

        if(!is_dir($path) && !mkdir($path)){
            throw new CreateFileFromOrderItemsException('not create temp docs dir ' . $path);
        }

        $fileName = $command->getFileName();

        $link = $path.'/' . $fileName .'.xls';

        $exporter->exportToFile($link);

        $command->getResultLink()->setFileLink($link);
    }
}