<?php

namespace App\Http\Controllers\Assets;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Responses\ReportJsonResponse;
use App\Models\Asset;
use App\Models\AssetComment;
use App\Models\AssetStatus;
use App\Models\Manufacturer;
use Facades\App\Services\Asset\AssetStatusService;
use App\Repositories\AssetRepository;
use App\Services\Asset\AssetDataService;
use App\Services\Asset\AssetLockService;
use Exception;
use App\Services\AssetsHealth\AssetsHealthReportService;
use Illuminate\Support\Facades\Auth;

class IndexController extends Controller
{
    public function __construct(
        protected AssetRepository $assetRepo,
        protected AssetsHealthReportService $assetsHealthReportService,
        protected AssetDataService $assetDataService,
        protected AssetLockService $assetLockService
    ) {}

    /**
     * Displays the Assets home page.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = ['title' => 'Assets', 'parent' => '', 'type' => 'it', 'parentUrl' => '/assets'];

        $statuses = AssetStatus::orderBy('slug')->get();
        $manufacturers = Manufacturer::select('id', 'name')->orderBy('name')->get();

        return view('assets.index', compact('statuses', 'data', 'manufacturers'));
    }

    /**
     * Display the mobile assets page.
     *
     * @return \Illuminate\Http\Response
     */
    public function mobileAsset()
    {
        $data = ['title' => 'Mobile Assets', 'parent' => '', 'type' => 'mobile', 'parentUrl' => '/assets'];

        $statuses = AssetStatus::orderBy('slug')->get();
        $manufacturers = Manufacturer::select('id', 'name')->orderBy('name')->get();

        return view('assets.index', compact('statuses', 'data', 'manufacturers'));
    }

    /** Shows the asset detail page
     * @param mixed $id
     *
     * @return [type]
     */
    public function show($id)
    {
        try {
            $asset = Asset::with('location', 'user', 'vendor', 'assetType', 'makeAndModel.manufacturer', 'technicalSpec', 'assetStatus', 'parentAsset', 'carrier', 'assetHistory:id,action,user_id,asset_id,created_at,updated_at,ticket_no', 'assetTypeAttributeValue', 'airwatch', 'chromebook', 'jamf', 'intune', 'assetVulnerabilty', 'lockStatus', 'revivnAsset')->find($id);
            $statuses = AssetStatusService::availableStatusesForUpdate($asset->assetStatus?->slug) ?? [];
        } catch (Exception $e) {
            return redirect('/assets')->with('error', 'No Asset Found');
        }
        $data = ['title' => 'Asset Details', 'parent' => 'Assets', 'type' => 'it', 'parentUrl' => '/assets'];

        $user = $this->assetRepo->searchAssetUser();

        $assetHealth = $this->assetsHealthReportService->getAssetHealthDetailByAsset($id);

        return view('assets.detail-page.detail-index', compact('asset', 'data', 'statuses', 'user', 'assetHealth'));
    }

    /**
     * Retrieves filtered asset data and returns it in a JSON response suitable for DataTables.
     *
     * @param Request $request The HTTP request object containing query parameters.
     *
     * @return \Illuminate\Http\JsonResponse The JSON response containing paginated and filtered asset data.
     */
    public function data(Request $request)
    {
        $filteredData = $this->assetDataService->getAssets();
        $assets =  $filteredData['assets'];
        $start = request('start');
        $data = [];

        if (!empty($assets)) {
            $data = $this->assetDataService->getAssetData($assets, $start, $data);
        }

        return new ReportJsonResponse(intval($request->input('draw')), $data, $filteredData['count']);
    }

    /**
     * Get the Lock code from detail page
     * @param Request $request
     *
     * @return string
     */
    public function getLockCode(Request $request)
    {
        $request->validate([
            'asset_id' => 'required'
        ]);

        return $this->assetLockService->getUnlockCode($request->all());
    }

    /**
     * Add a comment to the asset with the given ID.
     *
     * @param int $assetId The ID of the asset to add a comment to.
     *
     * @return \Illuminate\Http\RedirectResponse A redirect response to the asset detail page.
     */
    public function addComment($assetId)
    {
        if (request('comment')) {
            AssetComment::create([
                'user_id' => Auth::id(),
                'asset_id' => $assetId,
                'comment' => request('comment'),
                'ticket_no' => request('ticket_no')
            ]);

            return redirect('/assets/' . $assetId)->with('success-message', 'Comment added successfully');
        }

        return redirect('/assets/' . $assetId);
    }
}
