<?php

namespace App\Http\Controllers;

use App\Mail\PayCompleted;
use App\Models\Cart;
use App\Models\Country;
use App\Models\Paypal;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Str;
use Srmklive\PayPal\Services\PayPal as PayPalService;

class PaypalController extends Controller
{
    public function create(Request $request)
    {
        $type = $request->type ?? 'paypal';
        $items = [];
        $shippingArray = [];
        if ($type === 'form' || $type === 'card') {
            if ($type === 'form') {
                $info = $request->all();
            } else {
                $info = $request->data;
            }

            $shippingArray = [
                'name' =>
                    [
                        'full_name' => $info['name'],
                    ],
                'address' =>
                    [
                        'address_line_1' => $info['street1'],
                        'address_line_2' => $info['street2'] ?? '',
                        'admin_area_2' => $info['city'],
                        'admin_area_1' => $info['state'] ?? '',
                        'postal_code' => $info['postal'],
                        'country_code' => $info['country'],
                    ],
                'email_address' => $info['email'],
                'phone_number' => [
                    'national_number' => $info['phone'],
                ],
            ];
        }

        $paypalService = new PayPalService();
        $currency = $paypalService->getCurrency();
        $subtotal = 0;
        $userId = session()->getId();
        $carts = Cart::query()->with('product')->where('session_id', $userId)->where('is_buy', 0)->get();
        foreach ($carts as $cart) {
            $item = [];
            $quantity = $cart->numbers;
            $name = $cart->product->jianjie1 . ' ' . $cart->product->cs;
            $sku = $cart->product->pcode;
            $description = $cart->product->pcode . "buy($cart->numbers)" . ';';
            $price = $cart->product->price;
            $item['unit_amount'] = [
                'currency_code' => $currency,
                'value' => "$price",
            ];
            $item['tax'] = [
                'currency_code' => $currency,
                'value' => 0.00,
            ];
            $item['name'] = $name;
            $item['quantity'] = $quantity;
            $item['description'] = $description;
            $item['category'] = 'PHYSICAL_GOODS';
            $items[] = $item;
            $unitTotal = $price * $quantity;
            $subtotal = $subtotal + $unitTotal;
        }
        //税费
        $tax = config('paypal.tax') * $subtotal;
        $shipping = 0;
        $total = $subtotal + $tax + $shipping;
        $subtotal = number_format($subtotal, 2, '.', '');
        $total = number_format($total, 2, '.', '');
        $tax = number_format($tax, 2, '.', '');
        $shipping = number_format($shipping, 2, '.', '');
        $amount = [
            'currency_code' => $currency,
            'value' => "$total",
            'breakdown' =>
                [
                    'item_total' => [
                        'currency_code' => $currency,
                        'value' => $subtotal,
                    ],

                    'shipping' => [
                        'currency_code' => $currency,
                        'value' => $shipping
                    ],
                    'handling' => [
                        'currency_code' => $currency,
                        'value' => '0.00'
                    ],
                    'tax_total' => [
                        'currency_code' => $currency,
                        'value' => $tax
                    ],
                    'shipping_discount' => [
                        'currency_code' => $currency,
                        'value' => '0.00'
                    ],
                    'discount' => [
                        'currency_code' => $currency,
                        'value' => '0.00'
                    ]
                ],
        ];
        $body = Paypal::createBody($items, $amount, $shippingArray, $type);
        $paypalService->getAccessToken();
        $response = $paypalService->createOrder($body);
        if ($type === 'form') {
            foreach ($response['links'] as $link) {
                if ($link['rel'] == 'approve') {
                    return redirect($link['href']);
                }
            }
        }
        return response()->json($response, 200);
    }

    public function capture(Request $request)
    {
        $type = $request->type;
        $orderId = $request->order_id;
        if ($type === 'form') {
            $orderId = $request->token;
        }
        $userId = session()->getId();
        $paypalService = new PayPalService();
        $paypalService->getAccessToken();
        $response = $paypalService->capturePaymentOrder($orderId, ['Prefer' => 'representation']);
        $data = [];
        $carts = Cart::query()->with('product')->where('session_id', $userId)->where('is_buy', 0)
            ->get();
        $description = '';
        $amount = $response['purchase_units'][0]['payments']['captures'][0]['amount'];

        $data['session_id'] = $userId;
        $data['trans_id'] = $response['purchase_units'][0]['payments']['captures'][0]['id'];
        $data['local_id'] = now()->format('Ymd') . Str::random(8);
        $data['payer_id'] = $response['payer']['payer_id'] ?? $type;
        if ($type === 'google') {
            $shippingArray = $request->shippingAddress;
            $data['name'] = $shippingArray['name'];
            $data['phone'] = $shippingArray['phoneNumber'];
            $data['email'] = $request->email;
            $data['postal'] = $shippingArray['postalCode'];
            $data['country'] = $shippingArray['countryCode'];
            $data['state'] = $shippingArray['administrativeArea'];
            $data['city'] = $shippingArray['locality'];
            $data['street1'] = $shippingArray['address1'];
            $data['street2'] = $shippingArray['address2'] ?? '';
        } else {
            $shipping = $response['purchase_units'][0]['shipping'];
            $data['name'] = $shipping['name']['full_name'];
            $data['phone'] = $shipping['phone_number']['national_number'] ?? $response['payment_source']['paypal']['phone_number']['national_number'];
            $data['email'] = $shipping['email_address'] ?? $response['payment_source']['paypal']['email_address'];
            $data['postal'] = $shipping['address']['postal_code'];
            $data['country'] = $shipping['address']['country_code'];
            $data['state'] = $shipping['address']['admin_area_1'] ?? '';
            $data['city'] = $shipping['address']['admin_area_2'];
            $data['street1'] = $shipping['address']['address_line_1'];
            $data['street2'] = $shipping['address']['address_line_2'] ?? '';
        }
//        $data['order_id'] = $response['id'];

        $data['ip'] = request()->ip();
        $data['total'] = $amount['value'];
        $data['currency'] = $amount['currency_code'];
        $data['created_at'] = now();
        if (app()->environment() === 'production') {
            Cart::query()->whereIn('id', $carts->pluck('id')->toArray())->update([
                'is_buy' => 1
            ]);
        }
        $descriptionResponse = $paypalService->showOrderDetails($orderId);
        $items = $descriptionResponse['purchase_units'][0]['items'];
        foreach ($items as $item) {
            $description .= $item['description'];
        }
        $data['des'] = $description;
        try {
            Paypal::query()->create($data);
//            $email = app()->environment() === 'production' ? $data['email'] : 'hp643711690@gmail.com';
            $email = $data['email'];
            Mail::to($email)->send(new PayCompleted($carts, $data));
        } catch (\Exception $exception) {
            error_log($exception->getMessage());
            Log::error($exception->getMessage());
        }
        if ($type === 'form') {
            return redirect()->route('success', ['trans_id' => $data['trans_id']]);
        }
        return response()->json($response, 200);
    }

    public function cancel()
    {
        return view('paypal.fail');
    }


    public function success(Request $request)
    {
        if ($request->isMethod('POST')) {
            $data = $request->only(['name', 'phone', 'email', 'country', 'city', 'state', 'postal', 'street1', 'street2']);
            $transId = $request->trans_id;
            $user = Paypal::query()->where('trans_id', $transId)->first();
            if ($user) {
                Paypal::query()->where('trans_id', $transId)->update($data);
            }
            return response()->json(['status' => 'success']);
        }
        if (app()->environment() === 'local') {
            $user = Paypal::query()->orderBy('id', 'desc')->first();
        } else {
            $transId = $request->trans_id;
            $userId = session()->getId();
            $cart = Cart::query()->where('session_id', $userId)->where('is_buy', 1)->first();
            if ($cart) {
                $user = Paypal::query()->where('session_id', $userId)->first();
            } else {
                $user = Paypal::query()->where('trans_id', $transId)->first();
            }
            if ($user) {
                $hours = now()->diffInHours($user->created_at);
                if ($hours > 24) {
                    $user = null;
                }
            }
        }

        $countriesItem = Country::query()->where('status', 1)->get();
        $countries = [];
        foreach ($countriesItem as $item) {
            $translations = json_decode($item->translations, true)['es'] ?? $item->name;
            $countries [$item->iso2] = $translations;
        }
        return view('paypal.success', compact('user', 'countries'));
    }

    public function fail()
    {
        return view('paypal.fail');
    }

    public function checkout()
    {
        $subtotal = 0;
        $carts = Cart::query()->with('product')->where('session_id', session()->getId())->where('is_buy', 0)->get();
        foreach ($carts as $cart) {

            $unitTotal = round($cart->product->price * $cart->numbers, 2);
            $cart->singletotal = $unitTotal;
            $subtotal += $unitTotal;
        }
        $tax = getenv('PAYPAL_TAX') * $subtotal;
        $total = $subtotal + $tax;
        $shipping = 0;
        $tax = number_format($tax, 2, ',', ',');
        $subtotal = number_format($subtotal, 2, ',', ',');
        $total = number_format($total, 2, ',', ',');
        $countries = Country::query()->where('status', 1)->get();
        return view('paypal.checkout', compact('subtotal', 'total', 'shipping', 'carts', 'countries', 'tax'));
    }
}
