<?php

namespace App\Http\Controllers\Terminations\Retriever;

use App\Http\Controllers\Controller;
use App\Http\Requests\Retreiver\StoreRetreiverShipmentRequest;
use App\Services\Terminations\Retriever\RetrieverShipmentService;

/**
 * RetrieverReportController
 */
class RetrieverShipmentController extends Controller
{

    /**
     *
     */
    public function __construct(protected RetrieverShipmentService $service)
    {
    }

    /**
     * Creates a shipment request.
     *
     * @param StoreRetreiverShipmentRequest $request The request object containing the shipment data.
     * @return \Illuminate\Http\RedirectResponse Redirects back with an error message if the shipment request fails,
     *                                           or with a success message if the shipment request is created successfully.
     */
    public function createShipmentRequest(StoreRetreiverShipmentRequest $request)
    {
        if ($this->service->checkConnection() === false) {
            return redirect()->back()->with('error', 'Connection failed. Please try again.');
        }

        $response = $this->service->createShipmentRequest($request->all());

        if ($response['status'] === false) {
            $errorMessages = $this->flattenErrorMessages($response['errors']);
            $errorMessage = 'Shipment request failed.' . PHP_EOL . implode(PHP_EOL, $errorMessages);

            return redirect()->route('retriever-report.index')->with('error', $errorMessage);
        }

        return redirect()->route('retriever-report.index')->with('message', 'Shipment request created successfully.');
    }

    /**
     * Flattens the nested error messages into a single array.
     *
     * @param mixed $errors The nested error messages.
     * @return mixed The flattened error messages.
     */
    private function flattenErrorMessages($errors): mixed
    {
        $flattenedErrors = [];

        if (is_object($errors)) {
            $errors = get_object_vars($errors);
        }

        foreach ($errors as $error) {
            if (is_object($error)) {
                $error = get_object_vars($error);
            }
            if (is_array($error)) {
                $flattenedErrors = array_merge($flattenedErrors, $this->flattenErrorMessages($error));
            } else {
                // Remove { and } characters from the error message
                $error = str_replace(['{', '}'], '', $error);
                $flattenedErrors[] = $error;
            }
        }

        return $flattenedErrors;
    }
}
