<?php

namespace App\Http\Controllers\AssetsHealth;

use App\Http\Controllers\Controller;
use App\Models\AssetHealthAssetType;
use App\Models\AssetType;
use Illuminate\Http\Request;

class AssetsHealthAssetTypeController extends Controller
{


    /**
     * Retrieve all asset types and health test asset types and display them in the settings view.
     *
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
        $assetTypes = AssetType::get();
        $healthTestAssetTypes = AssetHealthAssetType::pluck('type_id')->toArray();

        return view('settings.asset-health', compact('assetTypes', 'healthTestAssetTypes'));
    }


    /**
     * Store the asset health asset types.
     *
     * @param  \Illuminate\Http\Request  $request The request containing asset health types data.
     *
     * @return \Illuminate\View\View The view with updated data.
     */
    public function store(Request $request)
    {
        AssetHealthAssetType::truncate();

        foreach ($request->all() as $key => $input) {
            if ($key == '_token') {
                continue;
            }

            AssetHealthAssetType::create(['type_id' => $key]);
        }

        $assetTypes = AssetType::get();
        $healthTestAssetTypes = AssetHealthAssetType::pluck('type_id')->toArray();

        return view('settings.asset-health', compact('assetTypes', 'healthTestAssetTypes'));
    }


    /**
     * Set the report asset type based on the request.
     *
     * @param  \Illuminate\Http\Request  $request The request containing the asset type ID.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response indicating success or failure.
     */
    public function setReportAssetType(Request $request)
    {
        $assetHealthAssetType = AssetHealthAssetType::firstOrNew(['type_id' => $request->id]);

        if ($assetHealthAssetType->exists) {
            $assetHealthAssetType->delete();
            $message = "Asset Type excluded from Asset Health Report.";
        } else {
            $assetHealthAssetType->save();
            $message = "Asset Type included in Asset Health Report.";
        }

        return response()->json([
            'success' => true,
            'message' => $message,
        ], 200);
    }
}
