<?php

namespace App\Services;

use App\Models\User;
use LangleyFoxall\XeroLaravel\OAuth2;
use LangleyFoxall\XeroLaravel\XeroApp;
use League\OAuth2\Client\Token\AccessToken;

class XeroService
{
    /**
     * @var XeroApp
     */
    protected $xero;

    /**
     * XeroCustomerService constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        $user = User::first();

        $accessToken = new AccessToken(json_decode($user->xero_access_token, true));
        if ($accessToken->hasExpired()) {
            $accessToken = $this->getOAuth2()->refreshAccessToken($accessToken);
            $user->xero_access_token = json_encode($accessToken);
            $user->save();
        }
        $this->xero = new XeroApp($accessToken, $user->tenant_id);
    }

    /**
     * @return OAuth2
     */
    private function getOAuth2()
    {
        return new OAuth2();
    }

    /**
     * @return array
     * @throws \Exception
     */
    public function getXeroTaxes()
    {
        $xero_taxes = $this->xero->taxRates()->get();
        $array = [];
        foreach ($xero_taxes as $tax) {
            $array[$tax['TaxType']] = $tax['Name'];
        }
        return $array;
    }

    /**
     * @return mixed
     */
    public function getXeroContacts()
    {
        return $this->xero->contacts()->get();
    }

    /**
     * @param $guid
     * @return mixed
     */
    public function getXeroContact($guid)
    {
        return $this->xero->contacts()->find($guid);
    }


    /**
     * @param $account_number
     * @return mixed
     */
    public function getXeroContactByAccountNumber($account_number)
    {
        return $this->xero->contacts()->where('AccountNumber', $account_number)->first();
    }

    /**
     * @return mixed
     */
    public function getAccounts()
    {
        return $this->xero->accounts()->get();
    }

    /**
     * @param $guid
     * @return mixed
     */
    public function getXeroInvoice($guid)
    {
        return $this->xero->invoices()->find($guid);
    }


    /**
     * @param $contact_id
     * @return mixed
     */
    public function getInvoicesForCustomer($contact_id)
    {
        return $this->xero->invoices()->where('Contact.ContactID', $contact_id)->where('Status', 'AUTHORISED')->get();
    }

}
