<?php

namespace Inside\BCLH\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Inside\BCLH\Events\BasketGeneratedEvent;
use Inside\Content\Models\Contents\Folders;
use Inside\Content\Models\Contents\Photo;
use ZipArchive;

/**
 * Class PublishContent
 *
 * @category Class
 * @author   Maecia <technique@maecia.com>
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.maecia.com/
 */
class GenerateAlbumZip implements ShouldQueue
{
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

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

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

    public function __construct(string $uuid)
    {
        $this->uuid = $uuid;
    }

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

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

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

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

        $photos = Photo::query()->whereIn('uuid', DB::table('inside_pivots')
            ->where('related_type', Folders::class)
            ->where('parent_type', Photo::class)
            ->where('related_uuid', $this->uuid)
            ->pluck('parent_uuid'))
            ->get();

        foreach ($photos as $photo) {
            $uri = env('APP_STORAGE_PATH').'/'.$photo->file;

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

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

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

        $this->delete();
    }
}
