<?php

namespace App\Http\Controllers\Asn\Shi;

use App\Http\Requests\Asn\Shi\StoreShiUnwantedParts;
use App\Services\Asn\Shi\ShiUnwantedPartsService;
use App\Http\Controllers\Controller;
use App\Models\AsnUnwantedPart;
use App\Models\AssetHistory;
use Illuminate\Http\Request;
use App\Models\AssetStatus;
use App\Models\Asset;

class ShiUnwantedPartsController extends Controller
{

    /**
     * @var ShiUnwantedPartsService
     */
    protected $unwantedPartsService;


    /**
     * Constructor for the controller.
     *
     * @param \App\Services\ShiUnwantedPartsService $unwantedPartsService The unwanted parts service instance.
     */
    public function __construct(ShiUnwantedPartsService $unwantedPartsService)
    {
        $this->unwantedPartsService = $unwantedPartsService;
    }


    /**
     * Display a listing of SHI unwanted parts.
     *
     * @return \Illuminate\View\View The view displaying the unwanted parts.
     */
    public function index()
    {
        $unwantedParts = $this->unwantedPartsService->getUnwantedPartsData();

        return view('asn.shi.shi-unwanted-parts', compact('unwantedParts'));
    }


    /**
     * Search for SHI unwanted parts.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing the rendered search results view.
     */
    public function search()
    {
        $unwantedParts = $this->unwantedPartsService->getUnwantedPartsSearch();

        $view['hardware'] = view('asn.shi.partials.data.shi-unwanted-parts-data', compact('unwantedParts'))->render();

        return response()->json($view);
    }


    /**
     * Store a new SHI unwanted part mapping.
     *
     * @param \App\Http\Requests\StoreShiUnwantedParts $request The incoming HTTP request validated using the StoreShiUnwantedParts request class.
     *
     * @return \Illuminate\Http\RedirectResponse The redirect response with a success or error message.
     */
    public function store(StoreShiUnwantedParts $request)
    {
        $mappingData = AsnUnwantedPart::where(['provider' => 'shi', 'part_no' => $request->description])->first();

        if (!$mappingData) {
            AsnUnwantedPart::Create([
                'part_no' => request('description'),
                'provider' => 'shi'
            ]);

            return redirect('/shi-unwanted-parts')->with('message', 'Mapping added successfully.');
        }

        return redirect('/shi-unwanted-parts')->withErrors(['Mapping already exist']);
    }


    /**
     * Update an existing SHI unwanted part mapping.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response with the status and message.
     */
    public function update()
    {
        AsnUnwantedPart::findOrFail(request('id'))
            ->update([
                'part_no' => request('description')
            ]);

        return response()->json(['status' => 'success', 'message' => "Unwanted parts mapping updated successfully."]);
    }


    /**
     * Delete an existing SHI unwanted part mapping.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response with the status and success message.
     */
    public function destroy()
    {
        $mappingData = AsnUnwantedPart::findOrFail(request('id'));
        $mappingData->delete();

        return response()->json(['status' => 'success', 'message' => "Unwanted parts mapping deleted successfully."]);
    }


    /**
     * Handle AJAX requests for updating or deleting SHI unwanted parts mappings.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response with the status and message from the update or destroy method, or a boolean value.
     */
    public function ajax()
    {
        if (request('action') == 'edit') {
            return $this->update();
        } elseif (request('action') == 'delete') {
            return $this->destroy();
        }

        return response()->json(true);
    }


    /**
     * Handle the bulk upload of SHI unwanted parts mappings.
     *
     * @return \Illuminate\Http\RedirectResponse The redirect response with a success or error message.
     */
    public function bulkUpload()
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $result = $this->unwantedPartsService->bulkUpload();

        if (isset($result['errors'])) {
            return redirect('/shi-unwanted-parts')->with(['message' => $result['message'] ?? '', 'error' => $result['errors'] ?? '']);
        }

        return redirect('/shi-unwanted-parts')->with(['message' => $result['message'] ?? '']);
    }


    /**
     * Resync SHI unwanted parts mappings.
     *
     * @return \Illuminate\Http\RedirectResponse The redirect response with a success message.
     */
    public function resync()
    {
        $allMappings = AsnUnwantedPart::where('provider', 'shi')->whereNotNull('part_no')->get();
        $status      = AssetStatus::whereIn('slug', ['shi_in_transit'])->first();

        foreach ($allMappings as $mapping) {
            $assets = Asset::select('id')
                ->where('asset_status_id', $status->id)
                ->where('part_no', $mapping->part_no)
                ->get();

            foreach ($assets as $asset) {
                AssetHistory::where('asset_id', $asset->id)->delete();
                $asset->delete();
            }
        }

        return redirect('/shi-unwanted-parts')->with('message', "Resynced Successfully");
    }
}
