<?php

namespace App\Http\Controllers\Api\V1\Admin;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Traits\MediaUploadingTrait;
use App\Http\Requests\StoreAmcContractRequest;
use App\Http\Requests\UpdateAmcContractRequest;
use App\Http\Resources\Admin\AmcContractResource;
use App\Models\AmcContract;
use Gate;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;

class AmcContractApiController extends Controller
{
    use MediaUploadingTrait;

    public function index()
    {
        abort_if(Gate::denies('amc_contract_access'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        return new AmcContractResource(AmcContract::with(['client', 'assets', 'assigned_team', 'team'])->get());
    }

    public function store(StoreAmcContractRequest $request)
    {
        $amcContract = AmcContract::create($request->all());
        $amcContract->assets()->sync($request->input('assets', []));
        if ($request->input('amc_document', false)) {
            $amcContract->addMedia(storage_path('tmp/uploads/' . basename($request->input('amc_document'))))->toMediaCollection('amc_document');
        }

        return (new AmcContractResource($amcContract))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }

    public function show(AmcContract $amcContract)
    {
        abort_if(Gate::denies('amc_contract_show'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        return new AmcContractResource($amcContract->load(['client', 'assets', 'assigned_team', 'team']));
    }

    public function update(UpdateAmcContractRequest $request, AmcContract $amcContract)
    {
        $amcContract->update($request->all());
        $amcContract->assets()->sync($request->input('assets', []));
        if ($request->input('amc_document', false)) {
            if (! $amcContract->amc_document || $request->input('amc_document') !== $amcContract->amc_document->file_name) {
                if ($amcContract->amc_document) {
                    $amcContract->amc_document->delete();
                }
                $amcContract->addMedia(storage_path('tmp/uploads/' . basename($request->input('amc_document'))))->toMediaCollection('amc_document');
            }
        } elseif ($amcContract->amc_document) {
            $amcContract->amc_document->delete();
        }

        return (new AmcContractResource($amcContract))
            ->response()
            ->setStatusCode(Response::HTTP_ACCEPTED);
    }

    public function destroy(AmcContract $amcContract)
    {
        abort_if(Gate::denies('amc_contract_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden');

        $amcContract->delete();

        return response(null, Response::HTTP_NO_CONTENT);
    }
}
