<?php

namespace App\Http\Controllers\Assets;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\Location;
use App\Models\AssetStatus;
use App\Services\Asset\ReturnAssetService;
use Illuminate\Support\Facades\Auth;
use App\User;

class ReturnController extends Controller
{
    public function __construct(protected ReturnAssetService $returnAssetService) {}

    public function index()
    {
        $data = ['title' => 'Return Asset', 'parent' => 'Asset', 'type' => 'it', 'parentUrl' => '/assets'];
        $assetStatus = AssetStatus::GetReturnStatus()->get();
        return view('assets.return.return', compact('assetStatus', 'data'));
    }

    public function mobile()
    {
        $assetStatus = AssetStatus::GetReturnStatus()->get();

        $data = ['title' => 'Return ' . ucfirst('mobile') . ' Asset', 'parent' => ucfirst('mobile') . ' Asset', 'type' => 'mobile', 'parentUrl' => $this->getParentUrl('mobile')];

        return view('assets.return.return', compact('assetStatus', 'data'));
    }

    public function av()
    {
        $assetStatus = AssetStatus::GetReturnStatus()->get();

        $data = ['title' => 'Return ' . ucfirst('av') . ' Asset', 'parent' => ucfirst('av') . ' Asset', 'type' => 'avassets', 'parentUrl' => $this->getParentUrl('av')];

        return view('assets.return.return', compact('assetStatus', 'data'));
    }

    public function network()
    {
        $assetStatus = AssetStatus::GetReturnStatus()->get();

        $data = ['title' => 'Return ' . ucfirst('network') . ' Asset', 'parent' => ucfirst('network') . ' Asset', 'type' => 'network', 'parentUrl' => $this->getParentUrl('network')];

        return view('assets.return.return', compact('assetStatus', 'data'));
    }

    public function research()
    {
        $assetStatus = AssetStatus::GetReturnStatus()->get();

        $data = ['title' => 'Return ' . ucfirst('research') . ' Asset', 'parent' => ucfirst('research') . ' Asset', 'type' => 'research', 'parentUrl' => $this->getParentUrl('research')];

        return view('assets.return.return', compact('assetStatus', 'data'));
    }

    public function getParentUrl($type)
    {
        if ($type == 'network') {
            return "/network-assets";
        }
        if ($type == 'it') {
            return "/assets";
        }
        if ($type == 'mobile') {
            return "/mobile-assets";
        }
        if ($type == 'avassets') {
            return "/av-assets";
        }
        if ($type == 'research') {
            return "/research-assets";
        }
    }

    public function updateRows()
    {
        $count = request('count_add') + 1;
        $asset = Asset::with('makeAndModel.manufacturer', 'technicalSpec', 'user', 'location')->where('serial_no', request('serial_no'))->orWhere('asset_tag', request('serial_no'))->first();
        // dd($asset);
        $toLocation = Location::findOrFail(request('location_id'));

        $status = AssetStatus::find(request('asset_status_id'))
            ->name;

        $view = view('assets.partials.added-assets-return', compact('asset', 'toLocation', 'status', 'count'))->render();
        return response()->json($view);
    }

    /**
     * Handles the return of assets based on the provided category and count.
     * 
     * Iterates over the count of assets to be returned, processes each asset, 
     * and then redirects to the corresponding category index with a success message.
     * 
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store()
    {
        $user = User::find(Auth::id());
        $count = request('count');
        $returnedCount = 0;
        $notReturnedCount = 0;

        for ($i = 1; $i <= $count; $i++) {
            if ($this->returnAssetService->returnAsset(request()->all(), $user, $i) === true) {
                $returnedCount++;
            } else {
                $notReturnedCount++;
            }
        }

        session(['count_add' => 0]);

        $message = '';
        $errorMessage = '';

        $category = ucfirst(request('category'));

        if ($returnedCount > 0) {
            $message = "$returnedCount $category asset" . ($returnedCount > 1 ? 's' : '') . " returned.";
        }

        if ($notReturnedCount > 0) {
            $errorMessage = "$notReturnedCount $category asset" . ($notReturnedCount > 1 ? 's were' : ' was') . " not returned.";
        }

        if ($returnedCount === 0) {
            return redirect(route("assets-return.index"))->with('error', "No $category assets were returned.");
        }

        if ($category === "Mobile") {
            return redirect(route('assets-return.mobile', ['type' => request('category')]))->with('message', $message)->with('error', $errorMessage);
        }

        if ($category === "Network") {
            return redirect(route('assets-return.network', ['type' => request('category')]))->with('message', $message)->with('error', $errorMessage);
        }

        if ($category === "Avassets") {
            return redirect(route('assets-return.av', ['type' => request('category')]))->with('message', $message)->with('error', $errorMessage);
        }

        return redirect(route('assets-return.index'))->with('message', $message)->with('error', $errorMessage);
    }

    /** Return a single asset
     * @return [type]
     */
    public function returnSingleAsset(Request $request)
    {
        $request->merge([
            'to_location_id' => request('location_id')
        ]);

        $user = User::find(Auth::id());

        if ($this->returnAssetService->returnAsset($request->all(), $user, '') === false) {
            return back()->with('error', 'Invalid form data.');
        }

        return back()->with('message', 'The asset has been returned.');
    }
}
