<?php /** @noinspection PhpPossiblePolymorphicInvocationInspection */

namespace App\Http\Controllers;

use App\Company;
use App\CompanyStatus;
use App\MediaPrice;
use App\SocialPaymentHistory;
use App\TmpRegistration;
use App\Tools\SmsTools;
use App\Traits\CpanelApi;
use App\User;
use App\WhitelistedIp;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\Validator;

class companyApiController extends Controller
{
    public function register(Request $request)
    {
        // try {

        $data = $request->except(['sender_id_document', 'contact_person_id', 'business_document']);

        $this->appLog("Request Params " . json_encode($data));

        $validator = Validator::make(
            $request->all(),
            [
                'name' => 'required|unique:companies',
                'date_of_incorporation' => 'nullable',
                'legal_status' => 'nullable',
                'nature_of_business' => 'nullable',
                'mobile_money_number' => 'nullable|digits_between:10,20',
                'company_phone_number' => 'nullable|digits_between:10,20',
                'contact_person' => 'nullable',
                'register_as' => 'nullable',
                'business_location' => 'nullable',

                'name_of_director' => 'nullable',
                //base64
                'designation_of_director' => 'nullable',
                //base64

                'sender_id_document' => ['nullable'],
                'contact_person_id' => ['nullable'],
                'business_document' => ['nullable'],

                'sender_id_document_ext' => ['nullable', 'string', 'in:pdf,csv,xlsx,png,jpg,jpeg'],
                'contact_person_id_ext' => ['nullable', 'string', 'in:pdf,csv,xlsx,png,jpg,jpeg'],
                'business_document_ext' => ['nullable', 'string', 'in:pdf,csv,xlsx,png,jpg,jpeg'],

                //base64
                'contact_person_designation' => 'sometimes|nullable',
                'contact_person_phone' => 'nullable|unique:companies|digits_between:10,20',
                'contact_person_phone' => 'nullable|unique:users,phone_number|digits_between:10,20',
                'contact_person_email' => 'nullable|email|min:6|companies:contact_person_email',
                'contact_person_email' => 'nullable|email|min:6|unique:users,email',
                'service_id' => 'required',
                'order_id' => 'required',
                'order_item_id' => 'required'
            ]
        );



        if ($validator->fails()) {
            return response()->json(['code' => 401, 'msg' => $validator->errors()->all()]);
        }

        if ($request->file('sender_id_document') || ($request->has('sender_id_document') && !$this->isBase64Encoded($request->input('sender_id_document')))) {
            return response()->json(['code' => 401, 'msg' => 'The sender id document must be a valid base64-encoded string with a maximum size of 1MB.']);
        }

        if ($request->file('contact_person_id') || ($request->has('contact_person_id') && !$this->isBase64Encoded($request->input('contact_person_id')))) {
            return response()->json(['code' => 401, 'msg' => 'The contact person id must be a valid base64-encoded string with a maximum size of 1MB.']);
        }

        if ($request->file('business_document') || ($request->has('business_document') && !$this->isBase64Encoded($request->input('business_document')))) {
            return response()->json(['code' => 401, 'msg' => 'The business document must be a valid base64-encoded string with a maximum size of 1MB.']);
        }



        if ($request->input('register_as') == 'reseller_client') {
            $reseller_username = $request->input('reseller_username');

            if (empty($reseller_username))
                return response()->json([
                    'code' => 402,
                    'msg' =>
                    ['reseller username field required exist']
                ]);

            $user = User::query()->where('username', $reseller_username)->first();

            if (empty($user))
                return response()->json([
                    'code' => 403,
                    'msg' =>
                    ['reseller does not exist']
                ]);

            if (!empty($user) && $user->role_id != 3)
                return response()->json([
                    'code' => 405,
                    'msg' =>
                    ['this is not a valid reseller account']
                ]);
        }


        if (
            !empty($request->input('register_as')) &&
            !in_array($request->input('register_as'), ['reseller', 'reseller_client', 'direct_client'])
        ) {
            return response()->json([
                'code' => 406,
                'msg' =>
                ['register_as as parameter must be either reseller,reseller_client or direct_client']
            ]);
        }


        if (!$this->validate_legal($request))
            return response()->json([
                'code' => 406,
                'msg' => [
                    'legal status must one of the following '
                    . str_replace(['[', ']', "\\"], '', json_encode($this->legal_status()))
                ]
            ]);


        $records = $request->except(['contact_person_id', 'sender_id_document']);

        $records['nature_of_business'] = empty($request->input('nature_of_business')) ? 'N/A' : $request->input('nature_of_business');
        $records['company_phone_number'] = empty($request->input('company_phone_number')) ? 'N/A' : $request->input('company_phone_number');
        $records['contact_person_phone'] = SmsTools::format_gh_number($request->input('contact_person_phone'));
        $records['date_of_incorporation'] = empty($request->input('date_of_incorporation')) ? 'N/A' : $request->input('date_of_incorporation');
        $records['location_in_other_countries'] = empty($request->input('business_location')) ? 'N/A' : $request->input('business_location');
        $records['physical_address'] = empty($request->input('business_location')) ? 'N/A' : $request->input('business_location');
        $records['postal_address'] = empty($request->input('postal_address')) ? 'N/A' : $request->input('postal_address');

        $result = $this->generateUserInfo($request);

        $result['created_by'] = $records['register_as'] == 'reseller_client' ? $records['reseller_username'] : 'messenger';


        DB::beginTransaction();

        $user = User::query()->create($result);


        $records['user_id'] = $user->id;
        $records['date_of_incorporation'] = Carbon::parse($records['date_of_incorporation']);




        $user->credit()->create([
            'username' => $user->username,
            'price' => '0.032',
            'email_price' => '0.00332',
            'credit_alloted' => '0.00',
            'old_bal' => '0',
            'new_bal' => '0.00',
            'credit_used' => '0',
            'credited' => '0'
        ]); // create the user details for the company or individual

        $_data = $records;
        if (isset($_data['amount'])) {
            $this->user_bonus_top_up_balance($_data, $user);
        }


        $output = $this->saveFiles($request); // save files
        $company = Company::query()->create($records); //create the company
        $company->putToTrialMode($records); //put to trial mode
        $company->update($output); // update company records with the files captured


        if ($request->has(['name_of_director', 'designation_of_director']))
            $company->directors()->create([
                'name' => $request->input('name_of_director'),
                'designation' => $request->input('designation_of_director'),
            ]);


        //            $balance = $user->credit->price * 3;
//
//            $user->credit->update(['new_bal' => $balance, 'credited' => $balance]);

        $user->update(['company_id' => $company->id]); //update user table with company table

        $status = $this->setStatus($company); //sets the company to approved

        // we save the company's director here
//            $this->saveDirectors($request,$company);

        $company->update($status); //updates the company status to be approved


        $data['email'] = $user->email;
        $data['name'] = $user->full_name;
        $data['c_username'] = $user->username;
        $data['c_password'] = $user->pass;
        $data['url'] = route($result['url']);
        $data['content'] = "Your MTN MESSENGER account  has been created with username and password";



        try {

            Mail::send('emails.admin_login', ['company' => $company], function ($m) {
                $m->from('mtn@messenger.com', 'MESSENGER');
                $m->to('support@npontu.com');
                $m->cc('Josephine.asante@mtn.com', 'Josephine Asante');
                $m->cc('Maame.simpson@mtn.com', 'Maame Simpson');
                $m->subject('New Company Registration');
            });

        } catch (\Exception $ex) {
            $this->appLog('mail register-api Error');
            Log::info($ex->getMessage());
        }

        $msg = "Hello {$company->name},
            Your MTN MESSENGER Account has been created with username and password
            username : {$company->users->username}
            password : {$company->users->pass}s
            url : {$data['url']}
            Thank You,
            MESSENGER";
        //            $this->apiSendSms($msg, $company->users->phone_number);


        DB::commit();

        return response()->json(['code' => 200, 'msg' => $company, 'status' => 'success']);
        // } catch (\Exception $ex) {
        //     $this->appLog("App Error " . $ex->getMessage());
        //     return response()->json(['code' => 407, 'msg' => [$ex->getMessage()]]);
        // }

    }

    private function isBase64Encoded($data)
    {
        return base64_encode(base64_decode($data, true)) === $data;
    }

    private function generateUserInfo(Request $request)
    {
        $inputs['phone_number'] = SmsTools::format_gh_number($request->input('contact_person_phone'));
        $inputs['full_name'] = $request->input('name');
        $words = explode(" ", trim($request->input('name')));
        $acronym = "";
        foreach ($words as $w) {
            if ($w && isset($w[0]) && !empty($w[0]))
                $acronym .= $w[0];
        }


        $demo = strtolower($acronym . $words[0]);
        $password = substr(hash('sha512', rand()), 0, 6);
        $username = $this->verifyUsername($demo);


        $role_id = in_array($request->input('register_as'), ['reseller_client', 'direct_client']) ? 2 : 3;

        $inputs['username'] = $username;
        $inputs['organisation'] = $request->input('name');
        ;
        $inputs['email'] = $request->input('contact_person_email');
        $inputs['role_id'] = $role_id;
        $inputs['password'] = bcrypt($password);
        $inputs['website_url'] = !empty($request->input('website_url')) ? $request->input('website_url') : null;
        $inputs['status'] = 'active';
        $inputs['location'] = empty($request->input('physical_address')) ? 'N/A' : $request->input('physical_address');
        $inputs['pass'] = $password;

        if ($inputs['role_id'] == 2) {
            $inputs['url'] = 'login';

        } else if ($inputs['role_id'] == 3) {
            $inputs['url'] = 'reseller.login';
        }

        return $inputs;
    }

    private function verifyUsername($string)
    {
        $length = 2;
        $query = User::query()->where('username', $string)->first();
        //if query returns true that means we ought to regenerate the user the name.

        //while $query remains true
        while ($query):
            $random = substr(str_shuffle(str_repeat($x = '0123456789', ceil($length / strlen($x)))), 1, $length);
            $string = $string . $random;
            break;
        endwhile;

        return $string;
    }

    private function saveFiles(Request $request)
    {
        $records = array();

        $senderIdExt = $request->input('sender_id_document_ext') ?? 'jpg';
        $contactPersonExt = $request->input('contact_person_id_ext') ?? 'jpg';
        $businessDocumentExt = $request->input('business_document_ext') ?? 'jpg';
        $businessLogoExt = $request->input('business_logo_ext') ?? 'jpg';


        if (!empty($request->input('contact_person_id'))) {

            $file = $request->input('contact_person_id'); //base64 code
            $name = $request->input('name');
            $_name = $this->convertToFile($file, $name, 'contact_person', $contactPersonExt);
            $records['contact_person_id'] = $_name;

        }



        if (!empty($request->input('sender_id_document'))) {

            $file = $request->input('sender_id_document'); //base64 code
            $name = $request->input('name');
            $_name = $this->convertToFile($file, $name, 'sender_docs', $senderIdExt);
            $records['sender_id_document'] = $_name;

        }


        if (!empty($request->input('business_document'))) {

            $file = $request->input('business_document'); //base64 code
            $name = $request->input('name');
            $_name = $this->convertToFile($file, $name, 'business_doc', $businessDocumentExt);
            $records['business_document'] = $_name;

        }


        if (!empty($request->input('business_logo'))) {

            $file = $request->input('business_logo'); //base64 code
            $name = $request->input('name');
            $_name = $this->convertToFile($file, $name, 'business_logo', $businessLogoExt);
            $records['business_logo'] = $_name;

        }

        return $records;
    }

    public function convertImage($encoded, $name, $path, $ext = 'jpg')
    {
        $file = $encoded; // base64 code

        $name = $name . date('h:i:s') . '.' . $ext;
        $_name = str_replace(' ', '_', $name);
        $file = str_replace(' ', '+', $file);

        /*** End of Base64 Conversion ***/
        $file = base64_decode($file);

        $storagePath = storage_path('app/public/' . $path);
        if (!is_dir($storagePath)) {
            mkdir($storagePath, 0755, true); // create the directory if it doesn't exist
        }

        file_put_contents($storagePath . '/' . $_name, $file);
        return $_name;
    }

    public function convertToFile($encoded, $name, $path, $ext)
    {
        $file = $encoded; // base64 code

        $name = $name . date('h:i:s') . '.' . $ext;
        $_name = str_replace(' ', '_', $name);
        $file = str_replace(' ', '+', $file);

        /*** End of Base64 Conversion ***/
        $file = base64_decode($file);

        $storagePath = storage_path('app/public/' . $path);
        if (!is_dir($storagePath)) {
            mkdir($storagePath, 0755, true); // create the directory if it doesn't exist
        }

        file_put_contents($storagePath . '/' . $_name, $file);
        return $_name;
    }


    private function setStatus($company, $_status = 3)
    {

        $status['company_id'] = $company->id;
        $status['r_code'] = $this->returnCode(4);
        $status['status'] = $_status;
        $save = CompanyStatus::query()->create($status);

        //create a new array and send results
        $expose['company_status_id'] = $save->id;
        $expose['code'] = $status['r_code'];

        return $expose;

    }

    private function returnCode($length)
    {
        $t = Carbon::parse()->format('s');
        $random = substr(str_shuffle(str_repeat($x = '0123456789', ceil($length / strlen($x)))), 1, $length);
        return 'DY' . $random . $t;
    }

    public function validate_business(Request $request)
    {
        return in_array($request->input('nature_of_business'), $this->business());
    }

    public function validate_legal(Request $request)
    {
        return in_array($request->input('legal_status'), $this->legal_status());
    }

    public function business()
    {
        return array(
            'Arts, entertainment and recreation',
            'Banking & finance',
            'Beauty industry',
            'Educational services',
            'Health care and social assistance',
            'Information Technology',
            'Information and cultural industries',
            'Insurance Insurance',
            'Manufacturing Manufacturing',
            'Mining, quarrying, and oil and gas',
            'Non-Governmental Organisations',
            'Other services',
            'Public administration',
            'Real estate, rental and leasing',
            'Religious Organisations',
            'Retail trade',
            'Transportation and warehousing',
            'Utilities',
            'Waste management',
            'Wholesale trade',
        );
    }

    public function legal_status()
    {
        return array(
            'SME',
            'LCA/MNO',
            'PUBLIC',
        );
    }

    public function tmp_register(Request $request)
    {
        $data = $request->all();

        $validator = Validator::make(
            $data,
            [
                'mobile_money_number' => 'sometimes|nullable|unique:tmp_registrations|digits_between:10,12',
                'first_name' => 'required',
                'last_name' => 'required',
                'phone_number' => 'required|unique:tmp_registrations|digits_between:10,12'
            ]
        );


        if ($validator->fails())
            return $this->validationError($validator->errors()->all());


        if (!$this->lookUp($request)) {
            return $this->unAuthorisedAccess('You are not authorized to access this resource');
        }

        $inputs = $validator->getData();
        DB::beginTransaction();
        $tmp = TmpRegistration::query()->create($inputs);
        $tmp->url();
        DB::commit();

        return response()->json(['code' => 200, 'status' => 'success', 'msg' => 'account successfully registered', 'url' => $tmp->tmp_url]);
    }

    public function check_balance(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make(
            $data,
            [
                'phone_number' => 'required',
            ]
        );


        if ($validator->fails())
            return $this->validationError($validator->errors()->all());



        if (!$this->lookUp($request)) {
            return $this->unAuthorisedAccess('You are not authorized to access this resource');
        }


        $user = (new \App\User)->byPhoneNumber($data['phone_number']);

        if (empty($user))
            return $this->infoNotFound("User not found");


        if (!$user->credit)
            return $this->infoNotFound("User Credit Details  not found");

        $_resp = $user->credit()->first(['username', 'new_bal']);

        return $this->successResponse($_resp);

    }

    public function top_up_balance(Request $request)
    {
        $data = $request->all();

        $validator = Validator::make(
            $data,
            [
                'phone_number' => 'required',
                'amount' => 'required',
            ]
        );

        if ($validator->fails())
            return $this->validationError($validator->errors()->all());


        if (!$this->lookUp($request)) {
            return $this->unAuthorisedAccess('You are not authorized to access this resource');
        }


        $user = (new \App\User)->byPhoneNumber($data['phone_number']);

        if (empty($user))
            return $this->infoNotFound("User not found");


        if (!$user->credit)
            return $this->infoNotFound("User Credit Details  not found");



        //update payment history
        if ($data['amount'] > 0) {

            $user->creditHistory()->create([
                'date_credited' => Carbon::now()->toDateTimeString(),
                'username' => $user->username,
                'price' => $user->credit->price,
                'credit_alloted' => $user->credit->credit_alloted + $data['amount'],
                'old_bal' => $user->credit->new_bal,
                'new_bal' => $user->credit->new_bal + $data['amount'],
                'credit_used' => $user->credit->credit_used,
                'credited' => $data['amount'],
                'credited_by' => 'api_user',
                'status' => 'active',
                'comments' => $user->username . ' has been credited by api_user with ' . $data['amount'],
            ]);

        }

        //credit new client
        $user->credit()->update([
            'credit_alloted' => $user->credit->credit_alloted + $data['amount'],
            'old_bal' => $user->credit->new_bal,
            'new_bal' => $user->credit->new_bal + $data['amount'],
            'credited' => $data['amount'],
            'updated_by' => 'api_user isolate'
        ]);


        $this->appLog("ISOLATED API : - phone_number: {$data['phone_number']}  Username:{$user->username} successfully credited with amount {$data['amount']}");

        return $this->successResponse("User successfully credited with amount {$data['amount']}");

    }


    public function user_bonus_top_up_balance($data, $user)
    {
        //        $phone_number = User::query()->where('email', $request->contact_person_email)->pluck('phone_number')->first();
//        $request['phone_number'] = $phone_number;
//        $data = $request->all();
//
//        $validator = Validator::make($data,
//            [
//                'phone_number' => 'required',
//                'amount' => 'required',
//            ]
//        );
//
//        if ($validator->fails())
//            return $this->validationError($validator->errors()->all());
//
//
//        $user = (new \App\User)->byPhoneNumber($data['phone_number']);
//
//
//        if(empty($user))
//            return  $this->infoNotFound("User not found");

        //        if(!$user->credit)
//            return  $this->infoNotFound("User Credit Details  not found");
        //update payment history
        if ($data['amount'] > 0) {

            $user->creditHistory()->create([
                'date_credited' => Carbon::now()->toDateTimeString(),
                'username' => $user->username,
                'price' => $user->credit->price,
                'credit_alloted' => $user->credit->credit_alloted + $data['amount'],
                'old_bal' => $user->credit->new_bal,
                'new_bal' => $user->credit->new_bal + $data['amount'],
                'credit_used' => $user->credit->credit_used,
                'credited' => $data['amount'],
                'credited_by' => 'api_user',
                'status' => 'active',
                'comments' => $user->username . ' has been credited by api_user with ' . $data['amount'],
            ]);

            //credit new client
            $user->credit()->update([
                'credit_alloted' => $user->credit->credit_alloted + $data['amount'],
                'old_bal' => $user->credit->new_bal,
                'new_bal' => $user->credit->new_bal + $data['amount'],
                'credited' => $data['amount'],
                'updated_by' => 'api_user'
            ]);

            $this->appLog("BONUS API : - phone_number: {$user->phone_number}  Username:{$user->username} successfully credited with amount {$data['amount']}");
            //return $this->successResponse("User successfully credited with amount {$data['amount']}");
        }
    }


    public function listPlans(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make(
            $data,
            [
                'phone_number' => 'required',
            ]
        );


        if ($validator->fails())
            return $this->validationError($validator->errors()->all());


        if (!$this->lookUp($request)) {
            return $this->unAuthorisedAccess('You are not authorized to access this resource');
        }

        $user = (new \App\User)->byPhoneNumber($data['phone_number']);

        if (empty($user))
            return $this->infoNotFound("User not found");


        $media = MediaPrice::query()->where('business_type', $user->company->legal_status)->first(['id', 'business_type', 'cost']);
        return $this->successResponse($media);
    }


    public function listAllPlans(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make(
            $data,
            [
                'phone_number' => 'required|exists:users',
            ]
        );


        if ($validator->fails())
            return $this->validationError($validator->errors()->all());


        if (!$this->lookUp($request)) {
            return $this->unAuthorisedAccess('You are not authorized to access this resource');
        }

        $media = MediaPrice::query()->get(['id', 'business_type', 'cost'])->toArray();
        return $this->successResponse($media);
    }

    public function subscribeUser(Request $request)
    {
        $data = $request->all();

        $validator = Validator::make(
            $data,
            [
                'phone_number' => 'required',
                'plan_id' => 'required',
            ]
        );



        if ($validator->fails())
            return $this->validationError($validator->errors()->all());



        if (!$this->lookUp($request)) {
            return $this->unAuthorisedAccess('You are not authorized to access this resource');
        }

        $user = (new \App\User)->byPhoneNumber($data['phone_number']);

        if (empty($user))
            return $this->infoNotFound("User not found");

        $plan = MediaPrice::query()->find($request->input('plan_id'));

        if (empty($plan))
            return $this->infoNotFound("Plan with id {$request->input('plan_id')} does not exist");


        if (empty($user->socialCredit)) {
            $trans = $user->username . uniqid();

            $user->socialCredit()->create([
                'trans_id' => $trans,
                'amount' => $plan->cost,
                'paid' => true,
                'expiry_date' => Carbon::parse()->addMonth(),
            ]);


            SocialPaymentHistory::query()->create([
                'user_id' => $user->id,
                'amount' => $plan->cost,
                'mm_number' => $user->phone_number,
                'p_status' => 'success',
                'res_mes' => 'paid via ussd',
                'trans_id' => $trans
            ]);

        } else {
            return $this->packageExist("User already subscribed to a package");
        }


        return $this->successResponse("User successfully  subscribed to the {$plan->business_type} package");

    }

    public function renewSubscription(Request $request)
    {

        $data = $request->all();
        $validator = Validator::make(
            $data,
            [
                'phone_number' => 'required',
                'plan_id' => 'required',
            ]
        );


        if ($validator->fails())
            return $this->validationError($validator->errors()->all());


        if (!$this->lookUp($request)) {
            return $this->unAuthorisedAccess('You are not authorized to access this resource');
        }


        $user = (new \App\User)->byPhone($data['phone_number']);

        if (empty($user))
            return $this->infoNotFound("No User found");

        $plan = MediaPrice::query()->find($request->input('plan_id'));


        if (empty($plan))
            return $this->infoNotFound("Plan with id {$request->input('plan_id')} does not exist");

        if (!empty($user->socialCredit)) {

            $trans = $user->username . uniqid();

            $pay = $user->socialCredit()->create([
                'trans_id' => $trans,
                'amount' => $plan->cost,
                'paid' => true,
                'expiry_date' => Carbon::parse()->addMonth(),
            ]);

            SocialPaymentHistory::query()->create([
                'user_id' => $user->id,
                'amount' => $plan->cost,
                'mm_number' => $user->phone_number,
                'p_status' => 'success',
                'res_mes' => 'paid via ussd',
                'trans_id' => $trans
            ]);

        } else {
            return response()->json(['code' => 304, 'status' => 'failed', 'msg' => "User has not been subscribed to a package"]);
        }

        return $this->successResponse("User subscription renewed to {$pay->expiry_date}");

    }


    public function lookUp($request)
    {
        $data = $request->all();
        $requestIP = request()->ip();


        $app_user = $request->header('X-User');
        $app_user_token = $request->header('X-Authorization');

        $this->appLog('LOGGING IP => ' . $requestIP . ' BODY => ' . json_encode($data));

        if (empty($app_user) || empty($app_user_token))
            return false;

        $authorizer = WhitelistedIp::query()->where('ip', $requestIP)
            ->where('app_user', $app_user)
            ->first();

        if (!empty($authorizer)) {

            $token = hash_hmac('sha256', $authorizer->client_key, $authorizer->client_secrete);

            if ($app_user_token !== $token)
                return false;

        } else {
            return false;
        }

        return true;

    }

    public function check_legal_status(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make(
            $data,
            [
                'phone_number' => 'required',
            ]
        );

        if ($validator->fails())
            return response()->json(['code' => 505, 'status' => 'failed', 'msg' => $validator->errors()->all()]);

        // Check IP
        if (!$this->lookUp($request)) {
            return $this->failureResponse('You are not authorized to access this resource');
        }

        // Find User
        $findUser = User::query()->where('phone_number', $data['phone_number'])->first();

        //Check company user is registered to
        $legal = Company::with('users')->where('user_id', $findUser->id)->first();
        if (empty($legal)) {
            return $this->failureResponse('User has not been fully registered yet');
        }

        //Send response
        return $this->successResponse('User is registered with legal status ' . $legal->legal_status);
    }

    public function successResponse($message)
    {
        return response()->json(['code' => 200, 'status' => 'success', 'msg' => [$message]]);
    }

    public function infoNotFound($message = null)
    {
        return response()->json(['code' => 204, 'status' => 'failed', 'msg' => [$message] ?? ["No Records found"]]);
    }

    public function failureResponse($message)
    {
        return response()->json(['code' => 206, 'status' => 'failed', 'msg' => [$message]]);
    }

    public function packageExist($message = null)
    {
        return response()->json(['code' => 304, 'status' => 'failed', 'msg' => [$message]]);
    }

    public function validationError($message = null)
    {
        return response()->json(['code' => 401, 'status' => 'failed', 'msg' => [$message]]);
    }


    public function unAuthorisedAccess($message)
    {
        return response()->json(['code' => 403, 'status' => 'failed', 'msg' => [$message]]);
    }


    public function invalidResponse($message)
    {
        return response()->json(['code' => 507, 'status' => 'failed', 'msg' => $message]);
    }





}