<?php

namespace App\Http\Controllers\Asn\Presidio;

use App\Models\Asset;
use App\Models\AssetStatus;
use App\Models\AssetHistory;
use App\Models\AsnUnwantedPart;
use App\Http\Controllers\Controller;
use App\Http\Traits\Asn\AsnAssetTrait;
use App\Http\Requests\Asn\Presidio\StoreAsnUnwantedParts;
use App\Http\Requests\CsvFileUploadRequest;
use App\Services\Asn\Presidio\PresidioUnwantedPartsService;

class PresidioUnwantedPartsController extends Controller
{
    use AsnAssetTrait;

    protected $service;

    public function __construct(PresidioUnwantedPartsService $service)
    {
        $this->service  = $service;
    }

    /**
     * Show Presidio Filtered out part# mapping page
     *
     * @return view
     */
    public function index()
    {
        $unwantedParts = $this->service->getUnwantedPartsData()->get();
        return view('asn.presidio.unwanted-parts', compact('unwantedParts'));
    }

    /**
     * Searches mapping data using given text
     *
     */
    public function search()
    {
        $unwantedParts      = $this->service->getUnwantedPartsSearch();
        $view['hardware']   = view('asn.presidio.partials.data.asn-unwanted-parts-data', compact('unwantedParts'))->render();
        return response()->json($view);
    }

    /**
     * store new mapping data
     *
     */
    public function store(StoreAsnUnwantedParts $request)
    {
        $mappingData = AsnUnwantedPart::where('provider', 'presidio')->where('part_no', request('part_no'))->first();

        if (!$mappingData) {

            AsnUnwantedPart::Create([
                'provider'  => 'presidio',
                'part_no'   => request('part_no')
            ]);
            return redirect('/presidio-unwanted-parts')->with('message', "Mapping added successfully");
        } else {

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

    /**
     * updates existing mapping data
     *
     */
    public function update()
    {
        $mappingData = AsnUnwantedPart::findOrFail(request('id'));

        if ($mappingData) {

            $mappingData->update([
                'part_no' => request('part_no')
            ]);

            $assets = Asset::select('id')->where('asset_status_id', $this->getAssetStatusId())->where('description', $mappingData->part_no)->get();

            foreach ($assets as $key => $asset) {

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

            return response()->json(['status' => 'success', 'message' => 'Updated successfully']);
        }

        return response()->json(['status' => 'error', 'message' => 'Failed to update.']);
    }

    /**
     * Deletes selected mapping data
     *
     */
    public function destroy()
    {
        $mappingData = AsnUnwantedPart::findOrFail(request('id'));

        if ($mappingData) {

            $mappingData->delete();
            return response()->json(['status' => 'success', 'message' => 'Deleted Successfully']);
        }
        return response()->json(['status' => 'error', 'message' => 'Failed to delete.']);
    }

    /**
     * Redirects to edit/delete fn as per request
     *
     */
    public function ajax()
    {
        if (request('action') == 'edit') {
            return $this->update();
        }

        if (request('action') == 'delete') {
            return $this->destroy();
        }

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

    /**
     * bulkUpload
     *
     * @param CsvFileUploadRequest $request
     *
     * @return \Illuminate\Http\RedirectResponse The redirect response with a success or error message.
     */
    public function bulkUpload(CsvFileUploadRequest $request)
    {
        setUnlimitedExecutionTimeAndMemoryLimit();

        $result = $this->service->bulkUpload($request);

        if (isset($result['errors'])) {
            session()->flash('error', $result['errors']);
        }

        session()->flash('message', $result['message'] ?? '');

        return response()->json(['status' => true]);
    }

    /**
     * sync Presidio assets with unwanted part# mappings
     *
     */
    public function resync()
    {
        $allMappings = AsnUnwantedPart::where('provider', 'presidio')->whereNotNull('part_no')->get();

        if ($allMappings) {

            $this->removeUnWantedParts($allMappings, $this->getAssetStatusId());
        }

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

    /**
     * Gets the asset status ID associated with Presidio in-transit.
     *
     * @return int
     */
    public function getAssetStatusId()
    {
        return AssetStatus::where('slug', 'presidio_in_transit')->first()->id;
    }
}
