<?php

namespace Inside\BCLH\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Inside\BCLH\Events\BasketGeneratedEvent;
use ZipArchive;

class GenerateBasket implements ShouldQueue
{
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * @var string
     */
    protected $userUuid;

    /**
     * @var Collection
     */
    protected $data;

    public function __construct(string $userUuid, Collection $data)
    {
        $this->userUuid = $userUuid;
        $this->data = $data;
    }

    public function handle(): void
    {
        $zipLocation = env('APP_STORAGE_PATH').'/protected/basket/';

        if (! is_dir($zipLocation)) {
            mkdir($zipLocation);
        }

        $zipLocation .= $this->userUuid.'.zip';

        $zip = new ZipArchive();
        $zip->open($zipLocation, ZipArchive::CREATE | ZipArchive::OVERWRITE);

        foreach ($this->data as $reaction) {
            $query = call_user_func($reaction->reactionable_type.'::query');
            $file = $query->find($reaction->reactionable_uuid);

            if (! $file) {
                continue;
            }

            $uri = env('APP_STORAGE_PATH').'/'.$file->file;

            if (! file_exists($uri)) {
                continue;
            }

            $pathinfo = pathinfo($file->file);
            $zip->addFile($uri, $pathinfo['basename']);
        }

        if ($zip->numFiles > 0) {
            $zip->close();

            event(new BasketGeneratedEvent($this->userUuid));
        }

        $this->delete();
    }
}
