<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\Payment;
use App\Services\PayService;
use App\Services\XeroService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Storage;

class PayController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function index()
    {
        return view('pay.index');
    }

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function account()
    {
        return view('pay.account');
    }

    /**
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function fixed()
    {
        return view('pay.fixed');
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function choosePay(Request $request)
    {
        $paypalemail  = "paypal@thinking.fish";
        $currency     = "GBP";
        $payNowButtonUrl = 'https://www.paypal.com/cgi-bin/webscr';
        $total_amount = 0;

        $total_amount_another_currency = 0;

        $list_amount = [];

        $list_amount_start_currency = [];

        if($request->get('pay_amount')) {

            foreach ($request->get('pay_amount') as $key => $pay_amount) {

                if( in_array( $key, $request->get('invoices') ) ) {
                    if( $request->get('invoice_currency') != 'GBP' ) {
                        $total_amount_another_currency += $pay_amount;
                        $list_amount_start_currency[$key] = $pay_amount;
                        $pay_amount = PayService::convertCurrency( $pay_amount,  $request->get('invoice_currency') );
                    }
                    $total_amount +=  $pay_amount;
                    $list_amount[$key] = $pay_amount;
                }
            }
            $invoices_to_form_another_currency = [];
            foreach ($request->get('invoices') as $key => $invoice) {

                foreach ( $request->get('pay_amount') as $key2 => $pay_amount) {

                    if( $invoice == $key2 ) {
                        if(  $request->get('invoice_currency') != 'GBP' ) {
                            $invoices_to_form_another_currency[$invoice] = $pay_amount;
                            $pay_amount = PayService::convertCurrency( $pay_amount,  $request->get('invoice_currency') );
                        }
                        $invoices_to_form[$invoice] = $pay_amount;
                    }
                }
            }
            session()->put('total_amount', $total_amount);
            session()->put('invoices.invoices_list', $request->get('invoices'));
            session()->put('invoices.currency', $request->get('invoice_currency'));
            session()->put('list_amount', $list_amount);

            if( $request->get('invoice_currency') != 'GBP' ) {
                session()->put('list_amount_another_currency', $list_amount_start_currency);
            }
            session()->put('invoices_to_form.invoices_list', $invoices_to_form);
            session()->put('invoices_to_form.invoices_list_another_currency', $invoices_to_form_another_currency);
            session()->put('invoices_to_form.currency',  $request->get('invoice_currency'));
            session()->put('invoice_start_currency',  $request->get('invoice_currency'));
            session()->put('invoice_start_currency_sum',  number_format($total_amount_another_currency, 2, '.', ''));
            session()->put('invoice_currency', 'GBP');
        }

        else {
            session()->put('total_amount', session('fixed_summ'));

        }

        return view('pay.choose_pay', compact('paypalemail', 'payNowButtonUrl', 'total_amount_another_currency', 'total_amount', 'currency'));

    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkAccount(Request $request)
    {
        $account_number = strtoupper($request['account']);
        $xero = new XeroService();
        $contact = $xero->getXeroContactByAccountNumber($account_number);

        if(isset($contact['ContactID'])){
            session()->put('contact', $contact['ContactID']);
            return response()->json(['success' => $contact['ContactID']], 200);
        }
        return response()->json(['error' => 2], 200);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkFixed(Request $request)
    {
        if (!$request->get('amount')) {
            return response()->json(['error' => ['Please fill amount']], 200);
        } else {
            session()->put('fixed_summ', $request->get('amount'));
            return response()->json(['success' => 1], 200);
        }
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse
     */
    public function cardPayment(Request $request)
    {
        if( session('payment_success')) {
            return view('pay.card_payment_payed');
        }
        if(!session('total_amount')){
            return redirect()->route('pay.index');
        }
        $payment = new Payment();
        if($request->get('check_submit')){
            if($payment->run() == 'form'){
                return view('pay.card_payment', compact('payment'));
            }
        }else{
            session()->forget('SuccessMessage');
            session()->forget('payment_success');
            session()->forget('errors');

            return view('pay.card_payment', compact('payment'));
        }
        $amount_suc = 0;
        if (session('payment_success') && !(session('pay_fixed'))) {

        }elseif (session('pay_fixed')){
            $amount_suc = session('total_amount');
        }

        return view('pay.card_payment');
    }


    public function paypal()
    {

    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function invoices(Request $request)
    {
        $xero = new XeroService();
        if($request->get('username')) {
            $account_number = strtoupper($request->get('username'));
            $contact = $xero->getXeroContactByAccountNumber($account_number);
            $contact_id = $contact['ContactID'];
            $contact_name = $contact['Name'];

        } else {
            $contact_id = $request['contact_id'];
            $contact_name = $request['account'];
        }
        $invoices = $xero->getInvoicesForCustomer($contact_id);
        return view('pay.invoices', compact('contact_id', 'contact_name', 'invoices'));
    }

    /**
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     */
    public function downloadInvoice(Request $request)
    {
        $invoice_id = $request->get('invoice_id');
        $xero = new XeroService();
        $invoice = $xero->getXeroInvoice($invoice_id);

        $user = User::first();
        $response = Http::withHeaders([
            'Accept' => 'application/pdf',
            'Content-Type' => 'application/json',
            'Xero-Tenant-Id' => $user->tenant_id,
            'Authorization' => 'Bearer ' . json_decode($user->xero_access_token, true)['access_token']
        ])->get('https://api.xero.com/api.xro/2.0/Invoices/' . $invoice['InvoiceNumber']);

        $pdf = $response->body();

        Storage::put('invoices/'.$invoice['InvoiceNumber'].".pdf", $pdf);
        return response()->download(storage_path('app/invoices/'.$invoice['InvoiceNumber'].".pdf"));

    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View
     */
    public function paypalCallback(Request $request)
    {
        return view('pay.success');
    }

}
