<?php

namespace Modules\Main\Http\Controllers\Company;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Modules\Main\Models\Company\Company;
use Modules\Main\Models\Company\Details;
use Modules\Main\Models\Company\CompanyAdmin;
use Modules\Main\Models\Company\CompanyType;
class DetailsController extends Controller
{
    public function index($companyId = null)
    {
        $company = false;
        if (!$companyId)
        {
            $userId = auth()->user()->id;
            $admin = CompanyAdmin::where('user_id', $userId);
            if ($admin->count() == 1)
            {
                $agent = $admin->first();
                $company = Company::find($agent->company_id);
            }
            else
            {
                abort(code: 401);
            }
        }
        else
        {
            $company = Company::find($companyId);
        }

        $details = new Details($company);
        $details = $details->get();
        if ($company->type == CompanyType::SoleProperty)
        {
            return view('main::company.details.selfemp', [
                'company' => $company,
                'details' => $details
            ]);
        }
        ;
        if ($company->type == CompanyType::Agency)
        {
            return view('main::company.details.agency', [
                'company' => $company,
                'details' => $details
            ]);
        }
        ;
    }
    public function store(Request $request, Company $company)
    {
        if ($request->user()->cannot('update', $company))
        {
            abort(403, 'Unauthorized action');
        }

        $userId = auth()->user()->id;
        $admin = CompanyAdmin::where('user_id', $userId)->get();
        if ($admin->count() == 1)
        {
            $agent = $admin->first();
            if ($agent->company_id != $company->id)
            {
                return;
            }
        }
        else
        {
            return back();
        }
        $company->details = $request->all();
        $company->save();
        return to_route('company.details', [
            'company' => $company
        ]);
    }
}
