<?php

namespace App\Jobs;

use App\Exports\OutAndAboutExport;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Http;
use Mtc\MercuryDataModels\SalesChannelHistory;

class OutAndAboutExportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->onQueue('export');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $data = (new OutAndAboutExport())->getExportData();

            // TODO: transfer xml
            // need endpoint, credentials etc

            // TODO: check if we need any headers
            Http::post($this->endpoint(), $this->generateXml((new OutAndAboutExport())->getExportData()));

            SalesChannelHistory::store(
                'out-and-about',
                true,
                $data->count() . ' records exported',
                null,
                $data->map(fn($row) => [
                    'uuid' => $row['StockNumber'],
                    'price' => $row['Price'],
                    'image count' => substr_count($row['Images'] ?? '', ';')
                ])->toArray()
            );
        } catch (Exception $exception) {
            SalesChannelHistory::store('out-and-about', false, $exception->getMessage());
        }
    }

    protected function generateXml(Collection $data): string
    {
        $xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $xml .= '<Products>';
        $data->each(function ($item) use (&$xml) {
            $xml .= '<Product>';
            $item->each(function ($value, $key) use (&$xml) {
                $xml .= "<$key>$value</$key>";
            });
            $xml .= '</Product>';
        });
        $xml .= '</Products>';

        return $xml;
    }

    protected function endpoint(): string
    {
        // TODO: get endpoint
        return 'todo-get-endpoint';
    }
}
