<?php

namespace App\Http\Controllers\Assets;

use App\Http\Controllers\Controller;
use App\Services\Asset\UpdateAssetAttributeService;
use App\Services\Asset\UpdateAssigneeService;
use Exception;
use Illuminate\Http\Request;

class UpdateAssetAttributeController extends Controller
{
    /**
     * Constructs a new instance of the class.
     *
     * @param UpdateAssetAttributeService $service The asset update service to use.
     */
    public function __construct(protected UpdateAssetAttributeService $service, protected UpdateAssigneeService $updateAssigneeService) {}

    /**
     * Updates an attribute of asset and creates history for it.
     */
    /**
     * Updates an attribute of an asset and creates history for it.
     * Handles both AJAX and regular form submissions.
     *
     * @throws Exception
     *
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function updateAttribute()
    {
        try {
            request()->validate([
                'id' => 'required',
                'attribute' => 'required',
            ]);

            $validationResult = $this->service->validateData(request()->all());

            if ($validationResult !== true) {
                return request()->ajax()
                    ? response()->json(['status' => false, 'message' => "Invalid form data."])
                    : redirect()->back()->with('error', "Invalid form data.");
            }

            $data = $this->service->updateAssetAttribute(request()->all());

            if (request()->ajax()) {
                return response()->json(['status' => true, 'attribute' => $data['name'], 'value' => $data['new_value']]);
            }

            return redirect()->back()->with('message', "The {$data['name']} has been updated.");
        } catch (Exception) {
            if (request()->ajax()) {
                return response()->json(['status' => false, 'message' => 'Unable to update asset attribute.']);
            }

            return redirect()->back()->with('error', "Some error occurred.");
        }
    }


    /**
     * Update the asset user
     *
     */
    public function updateAssignee()
    {
        request()->validate([
            'asset_id' => 'required',
            'user_id' => 'required',
        ]);

        if ($this->updateAssigneeService->updateAssignee(request()->all())) {
            return back()->with('message', 'The assignee has been updated.');
        }

        return back()->with('error', 'Something went wrong. Try again later');
    }

    /**
     * Updates hardware and specifications for an asset.
     *
     * @param Request $request The request containing asset details.
     * @throws Exception If an error occurs during the update process.
     * @return bool Whether the update was successful or not.
     */
    public function updateHardwareAndSpecs(Request $request)
    {
        $request->validate([
            'asset_id' => 'required',
            'asset_type_id' => 'required',
            'make_and_model_id' => 'required',
            'technical_spec_id' => 'required',
        ]);

        if ($this->service->updateHardwareAndSpecs($request->except('_token')) === true) {
            session()->flash('message', 'Asset attributes updated successfully.');

            return true;
        }

        session()->flash('error', 'Some error occurred.');

        return false;
    }
}
