<?php

namespace App\Http\Controllers;

use App\Facades\Settings;
use App\Http\Requests\ImportBlogXmlRequest;
use App\Jobs\WordPressBlogImport;
use App\Models\BulkImportLog;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Mtc\MercuryDataModels\Template;

class WordPressBlogImportController extends Controller
{
    public function import(ImportBlogXmlRequest $request): array
    {
        $templateId = Settings::get('app-content-blog-default-template');
        $template = $templateId
            ? Template::query()->find($templateId)
            : Template::query()->where('slug', 'blog-article')->first();

        if (!$template) {
            return [
                'success' => false,
                'message' => 'No blog template found '
                    . '(checked setting "app-content-blog-default-template" and slug "blog-article")',
            ];
        }

        $xmlContent = $request->file('file')->getContent();
        libxml_use_internal_errors(true);
        $xml = simplexml_load_string($xmlContent, 'SimpleXMLElement', LIBXML_NOCDATA);
        libxml_clear_errors();

        if ($xml === false) {
            return [
                'success' => false,
                'message' => 'Failed to parse the XML file. Please check the file is valid WordPress export XML.',
            ];
        }

        $tmpName = 'blog-import-' . Str::random(8) . '-' . Carbon::now()->format('Y_m_d_H_i_s') . '.xml';
        $pathToFile = 'blog-import/' . $tmpName;

        Storage::disk('file-storage')->put($pathToFile, $xmlContent);

        BulkImportLog::query()->create([
            'user_id' => Auth::id(),
            'object_type' => 'blog',
            'filename' => $pathToFile,
        ]);

        WordPressBlogImport::dispatch($pathToFile);

        return [
            'success' => true,
            'message' => 'Blog import has been queued for processing.',
        ];
    }
}
