<?php

namespace App\Http\Controllers;

use App\Models\Domain;
use App\Models\NominetPrice;
use App\Models\RenewRequest;
use App\Models\User;
use App\Services\DomainService;
use App\Services\XeroService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Storage;

class PaymentController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Contracts\View\Factory|\Illuminate\Contracts\View\View|\Illuminate\Http\RedirectResponse
     */
    public function paymentForRenewal(Request $request)
    {
        $paymentData = $request->all();
        $requestObject = RenewRequest::where('judopay_md', $paymentData['MD'])->first();
        $renew_data = $requestObject->renew_data;

        $url = 'https://gw1.judopay.com/transactions/'.$requestObject->judopay_id;

        $basicAuth =  base64_encode(config('services.judo.key'));

        $fields = array("PaRes" => $paymentData['PaRes'],"Md" => $paymentData['MD']);
        $headers = [
            'Content-Type: application/json',
            'Api-Version: 5.6',
            'Authorization: Basic ' . $basicAuth
        ];

        $req = curl_init();
        curl_setopt($req, CURLOPT_URL, $url);
        curl_setopt($req, CURLOPT_CUSTOMREQUEST, "PUT");
        curl_setopt($req, CURLOPT_POSTFIELDS, json_encode($fields));
        curl_setopt($req, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($req, CURLOPT_HTTPHEADER, $headers);
        $response = curl_exec($req);
        $result = json_decode($response);

        $requestObjects = RenewRequest::where('judopay_md', $paymentData['MD'])->get();

        if( !isset( $result->result ) ) {
            $errorMessage = $result->message;
            return view('renew.error', compact('requestObject', 'errorMessage'));
        }
        if( $result->result != 'Success' ) {
            foreach ($requestObjects as $key => $renewalRequest) {
                $renewalRequest->error = 'judopay';
                $renewalRequest->error_text = $result->message;
                $renewalRequest->save();
            }
            $errorMessage = $result->message;
            return view('renew.error', compact('requestObject', 'errorMessage'));
        } else {

            $xeroInvoice = DomainService::createInvoiceForRenew( $renew_data );
            foreach ($requestObjects as $key => $requestObject) {
                if( $xeroInvoice['result'] == false ) {
                    $requestObject->error = 'xero';
                    $requestObject->error_text = $xeroInvoice['message'];
                } else {
                    $requestObject->invoice_id = $xeroInvoice['invoice'];
                    $requestObject->invoice_main_id = $xeroInvoice['invoice_id'];
                }
                $requestObject->save();
            }
            if( $xeroInvoice['result'] == false ) {
                $errorMessage = $xeroInvoice['message'];
                return view('renew.error_сontact', compact('errorMessage'));
            }

            DomainService::renewDomains($requestObject);


            $last_four = $result->cardDetails->cardLastfour;
            $invoice_id = $requestObject->invoice_main_id;

            $payment_data = [
                'Invoice' => [
                    'InvoiceID' => $invoice_id
                ],
                'Account' => [
                    'AccountID' => '1540fb57-d41f-4ffc-9493-bc679ef35546'
                ],
                'Date' => date('Y-m-d'),
                'Amount' => $result->amount,
                'Reference' => 'Paid by card ending ' . $last_four
            ];
            $user = User::first();
            $response = Http::withHeaders([
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
                'Xero-Tenant-Id' => $user->tenant_id,
                'Authorization' => 'Bearer ' . json_decode($user->xero_access_token, true)['access_token']
            ])->post('https://api.xero.com/api.xro/2.0/Payments', $payment_data);


            $xero_contact_id = $requestObject->domain->customer->xero_contact_id;
            $xero = new XeroService();
            $contact = $xero->getXeroContact($xero_contact_id);

            $persons = (array)$contact['ContactPersons'];

            $email = $contact['EmailAddress'];

            $ContactPersons = [];

            foreach ($persons as $key => $person) {
                if( isset($person['IncludeInEmails']) && $person['IncludeInEmails'] == 'true') {
                    $ContactPersons[] = $person['EmailAddress'];
                }
            }
            $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_id);

            $pdf = $response->body();

            Storage::put('invoices/'.$requestObject->invoice_id.".pdf", $pdf);

            $customer_name = str_replace('(DD)', '', $requestObject->domain->customer->xero_name);
            $data['customer_name'] = $customer_name;
            $data['new_invoice_number'] = $requestObject->invoice_id;
            $data['last_four'] = $last_four;
            $data['renewal_request'] = $requestObject;
            $new_invoice['email'] = $email;
            $new_invoice['contact_persons'] = $ContactPersons;
            $new_invoice['new_invoice_number'] = $requestObject->invoice_id;


            Mail::send('emails.invoice_paid', ['data' => $data], function ($message) use ($new_invoice) {
                $message->from('hello@thinking.fish', 'Thinking Fish');
                $message->attach(storage_path('app/invoices/'.$new_invoice['new_invoice_number'].".pdf"));
                $message->attach(storage_path('app/terms_conditions/terms_and_conditions.docx'));
                $message->bcc('pool@thinking.fish', 'Pool Thinking Fish');
                if( !empty($new_invoice['contact_persons'])  ) {
                    $message->cc($new_invoice['contact_persons']);
                }
                $message->to($new_invoice['email'])->subject('Invoice '.$new_invoice['new_invoice_number']);
            });

            $admin_email = 'andrew.lobel@thinking.fish';
            Mail::send('emails.admin_notify_renewal', ['data' => $data], function ($message) use ($admin_email ,$new_invoice, $data) {
                $message->from('hello@thinking.fish', 'Thinking Fish');
                $message->bcc('pool@thinking.fish', 'Pool Thinking Fish');
                $message->to($admin_email)->subject('Renewal request from '.$data['customer_name']);
            });

            DomainService::importNominet();
            DomainService::importOpensrs();

            return redirect()->route('thank_you_page');

        }
    }

    /**
     * @param Request $request
     */
    public function renewalDirectDebit(Request $request)
    {
        $allData = $request->all();

        $allData = json_decode($allData['data'], true);
        $subtotal = 0;
        foreach ($allData['domains'] as $domain => $info) {
            $domainObject = Domain::where('domain', $domain)->first();
            if( $info['period'] == 'do_not_renew' ) {
                $domainObject->do_not_renew = 1;
                $domainObject->save();
            } else {
                if( $domainObject->do_not_renew == 1 && $info['period'] != 'do_not_renew' ) {
                    $domainObject->do_not_renew = 0;
                    $domainObject->save();
                }
            }
            $tax_type = $domainObject->customer->tax_type;
            $allData['domains'][$domain]['tax_type'] = $tax_type;
            if( $domainObject->registry == 'nominet' ) {
                $price = NominetPrice::where('price', '!=', null)->first();
                $allData['domains'][$domain]['price'] = $price->price*$info['period'];
                $subtotal += $price->price*$info['period'];
            } elseif( $domainObject->registry == 'opensrs' ) {
                $allData['domains'][$domain]['price'] = DomainService::getOpenSrsPrice($domainObject->domain)*$info['period'];
                $subtotal += DomainService::getOpenSrsPrice($domainObject->domain)*$info['period'];
            }
            $allData['domains'][$domain]['expiry_date'] = $domainObject->expiry_date;

            $renewRequest = new RenewRequest();
            $renewRequest->renew_data = $allData;
            $domainObject = Domain::where('domain', $domain)->first();
            $renewRequest->domain_id = $domainObject->id;
            $renewRequest->save();
            $requests[] = $renewRequest->id;
        }
        $xeroInvoice = DomainService::createDirectDebitInvoiceForRenew( $allData );
        foreach ($requests as $key => $id) {
            $requestObject = RenewRequest::find($id);
            if( $xeroInvoice['result'] == false ) {
                $requestObject->error = 'xero';
                $requestObject->error_text = $xeroInvoice['message'];
            } else {
                $requestObject->invoice_id = $xeroInvoice['invoice'];
                $requestObject->invoice_main_id = $xeroInvoice['invoice_id'];
            }
            $requestObject->save();
        }
        if( $xeroInvoice['result'] == false ) {
            $result['status'] = false;
            $result['error'] = $xeroInvoice['message'];
            return back()->withInput($allData)->withErrors([$xeroInvoice['message']]);
        }
        DomainService::renewDomains($requestObject);
        $result['status'] = true;
        echo json_encode($result);
        die();

    }






}
