<?php

namespace App\Classes\Modules\Companies\Services;


use App\Classes\Constants;
use App\Classes\Modules\AddressBook\Services\CreatesAddress;
use App\Classes\Modules\AddressBook\DataTransferObjects\AddressBookObject;
use App\Classes\Modules\Documents\UpdateDocuments;
use App\Models\AddressBook;
use App\Models\Company;
use Illuminate\Http\Request;
use App\Http\Resources\Company as CompanyResource;

class UpdatesCompany
{
   /** @var  AddressBook */
    private $repository;

    /** @var  CreatesAddress */
    private $createsAddress;

    /**
     * UpdatesCompany constructor.
     * @param AddressBook $repository
     * @param CreatesAddress $createsAddress
     */
    public function __construct(AddressBook $repository, CreatesAddress $createsAddress)
    {
        $this->repository = $repository;
        $this->createsAddress = $createsAddress;
    }


    public function execute(Request $request){

        $company = $request->method() === 'PUT' ?  Company::findOrFail($request->input('id')) : new company;
        $company->fill($request->except(array_merge(Constants::COMPANY_DOCUMENTS, Constants::ADDRESS_FIELDS)));

        if($company->save()){

            foreach (Constants::COMPANY_DOCUMENTS as $documentType){

                $documents = $request->input($documentType);

                if($documents !== null){

                    (new updateDocuments(
                        Constants::MODULE_TYPES['company'],
                        $company->id,
                        $documentType))->execute($documents);

                }
            }

            $this->repository->where('type', 1)->where('reference', $company->id)->where('billing', true)->delete();

            $billing = new AddressBookObject(1, $company->id, null, null,
                $request->input('street_one'), $request->input('street_two'), $request->input('city'),
                $request->input('state'), $request->input('post_code'), $request->input('country'), false, true);

            $this->createsAddress->execute($billing);

            return new CompanyResource($company);
        }
    }

}