<?php

namespace Mtc\Shop\Checkout;

use Illuminate\Database\Eloquent\Model;
use Worldpay\Worldpay;
use Mtc\Shop\Order;


class OrderWorldpay extends Model
{

    protected $table = 'order_worldpay';

    protected $fillable = [
        'order_id',
        'order_ref',
        'transId',
        'timestamp',
        'amount_paid',
    ];

    const ORDER_PREFIX = 'HE_PAYMENT_';


    public static function getPrefixedOrderRef($order_id)
    {
        return self::ORDER_PREFIX . $order_id;
    }


    public static function getStrippedOrderRef($prefixed_order_ref)
    {
        return str_replace(self::ORDER_PREFIX, '', $prefixed_order_ref);
    }


    public static function getOrderCompleteURL($order_id)
    {
        $url = HTTPS_SITE_URL . '/shop/checkout/order_complete.php';
        $data = [
            'order_id' => $order_id,
            'payment_gateway' => 'worldpay',
        ];
        $data += $_GET;

        $url .= '?' . http_build_query($data);

        return $url;
    }


    public static function repeatOrder(array $input_data)
    {
        $worldpay = new Worldpay(WORLDPAY_SERVICE_KEY);

        $order_id = (int)$input_data['order_id'];

        $data = [
            'token'                 => $input_data['token'], // e.g. TEST_RU_2ca4d70a-a5f0-4638-a4d3-25113b05c541
            'amount'                => $input_data['amount'] * 100,
            'currencyCode'          => 'GBP',
            'orderType'             => 'RECURRING',
            'orderDescription'      => 'Repeat test',
            'name'                  => 'sss',
            'customerOrderCode'     => $order_id,
        ];

        WorldpayLog::saveResponse(json_encode($data), $order_id, 'recurring_order_create');
        $response = $worldpay->createOrder($data);
        WorldpayLog::saveResponse(json_encode($response), $order_id, 'recurring_order_response');

        return $response;
    }


    public static function getPaymentToken(int $order_id)
    {
        $log_entry = WorldpayLog::query()
            ->where('order_id', $order_id)
            ->whereIn('type', [ 'capture_response', 'recurring_order_response' ])
            ->first()
        ;

        $resp = json_decode($log_entry->response);

        return $resp->token;
    }


    public static function setTestResponseData(int $order_id)
    {
        $data = array (
            'msgType' => 'authResult',
            'installation' => '1276370',
            'country' => 'GB',
            'authCost' => '123.45',
            'routeKey' => 'VISA_CREDIT-SSL',
            'transId' => '3259813033',
            'countryMatch' => 'S',
            'rawAuthMessage' => 'cardbe.msg.authorised',
            'authCurrency' => 'GBP',
            'charenc' => 'UTF-8',
            'compName' => 'PRESCRIPTION POINT LTD',
            'rawAuthCode' => 'A',
            'amountString' => '&#163;123.45',
            'currency' => 'GBP',
            'tel' => '',
            'isMobile' => 'false',
            'fax' => '',
            'lang' => 'en',
            'countryString' => 'United Kingdom',
            'email' => 'bart@mtc.co.uk',
            'transStatus' => 'Y',
            '_SP_charEnc' => 'UTF-8',
            'amount' => '123.45',
            'address' => 'Test Test',
            'transTime' => '1616587181722',
            'cost' => '123.45',
            'town' => 'Test',
            'address3' => '',
            'address2' => '',
            'address1' => 'Test',
            'cartId' => self::getPrefixedOrderRef($order_id),
            'postcode' => '',
            'ipAddress' => '82.132.219.172',
            'cardType' => 'Visa',
            'authAmount' => '123.45',
            'authMode' => 'A',
            'instId' => '1276370',
            'displayAddress' => 'Test Test',
            'AAV' => '00000',
            'testMode' => '100',
            'name' => 'Test',
            'callbackPW' => WORLDPAY_CALLBACK_PASSWORD,
            'region' => '',
            'AVS' => '1111',
            'desc' => '',
            'authAmountString' => '&#163;123.45',
        );

        request()->merge($data);
    }

}
