<?php

namespace App\Imports\Blog;

use App\Jobs\SandownArticleImport;
use Illuminate\Console\OutputStyle;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Storage;
use Mtc\ContentManager\Models\ContentCategory;
use Mtc\MercuryDataModels\Template;

class SandownBlogImport
{
    use DispatchesJobs;

    public function __construct(
        private readonly OutputStyle $output,
        private readonly ?string $categorySlug = null
    ) {
        //
    }

    public function handle(): bool
    {
        $this->output->info('Import started!');

        $category = null;
        if (!empty($this->categorySlug)) {
            $category = ContentCategory::query()->where('slug', $this->categorySlug)->first();
        }

        $content = Storage::disk('file-storage')->get('sandown-news-export.csv');
        $file = storage_path('sandown-blog-import.csv');
        File::put($file, $content);

        $imagesContent = Storage::disk('file-storage')->get('sandown-images-import.csv');
        $imagesFile = storage_path('sandown-images-import.csv');
        File::put($imagesFile, $imagesContent);

        if (!file_exists($file)) {
            $this->output->error('File not found!');
            return false;
        }

        $row = 1;
        if (($handle = fopen($file, "r")) !== false) {
            $imagesLinks = $this->getImagesLinks($imagesFile);

            /** @var Template $template */
            $template = Template::query()
                ->where('slug', 'news-article')
                ->first();

            if (!$template) {
                $this->output->error('News article template not found');
                return false;
            }

            while (($data = fgetcsv($handle, 5000, ',', '"', '"')) !== false) {
                if ($data[0] == 'name') {
                    continue;
                }

                $this->dispatch(new SandownArticleImport($data, $imagesLinks, $template, $category));
                $row++;
            }
            fclose($handle);
        }

        $this->output->info('Imported ' . $row . ' records!');
        $this->output->info('Import finished!');
        return true;
    }


    private function getImagesLinks($imagesFile): array
    {
        if (!file_exists($imagesFile)) {
            return [];
        }

        $imagesLinks = [];

        if (($imagesHandle = fopen($imagesFile, "r")) !== false) {
            while (($imagesData = fgetcsv($imagesHandle, 1000, ',', '"', '"')) !== false) {
                if ($imagesData[0] == 'id') {
                    continue;
                }

                $imagesLinks[$imagesData[0]] = $imagesData[1];
            }
        }

        return $imagesLinks;
    }
}
