<?php

namespace Mtc\Shop\Order;

use Illuminate\Database\Eloquent\Model;

/**
 * Class Protx
 *
 * @package Mtc\Shop\Order
 */
class Protx extends Model
{
    use BelongsToOrder;

    /**
     * @var string
     */
    protected $table = 'order_protx';

    /**
     * @var string[]
     */
    protected $guarded = [
        'id',
    ];

    public $timestamps = false;

    /**
     * Captures Sagepay deferred payment
     *
     * @param $order_id
     * @param $id
     * @param $endpoint
     * @return array
     * @throws \Exception
     */
    public static function capturePayment($order_id, $id, $endpoint)
    {
        $payment = self::query()
            ->whereNull('captured_at')
            ->where('order_id', $order_id)
            ->find($id);

        if (empty($payment)) {
            return [
                'success' => false,
                'message' => 'Could not find payment',
            ];
        }

        $post_values = [
            'VPSProtocol' => (string) SAGEPAY_PROTOCOL,
            'TxType' => 'RELEASE',
            'Vendor' => SAGEPAY_VENDOR,
            'VendorTxCode' => $payment->VendorTxCode,
            'VPSTxId' => $payment->VPSTxId,
            'TxAuthNo' => $payment->TxAuthNo,
            'ReleaseAmount' => $payment->Amount,
            'SecurityKey' => $payment->SecurityKey,
        ];

        $prepared_command = implode('&', array_map(
            function ($value, $key) {
                return "$key=$value";
            },
            $post_values,
            array_keys($post_values),
        ));

        $response = requestPost($endpoint, $prepared_command);

        if ($response['Status'] === 'OK') {
            $payment->captured_at = \Carbon\Carbon::now();
            $payment->save();

            return [
                'success' => true,
                'message' => $response['StatusDetail'],
            ];
        } else {
            return [
                'success' => false,
                'message' => $response['StatusDetail'],
            ];
        }
    }

    /**
     * Bulk capture payments
     *
     * @param $order_ids
     * @param $endpoint
     * @return bool
     * @throws \Exception
     */
    public static function bulkCapturePayments($order_ids, $endpoint)
    {
        if (! is_array($order_ids)) {
            return false;
        }

        $success_orders = [];
        $failed_orders = [];

        foreach ($order_ids as $order_id) {
            $order = new \Order($order_id);
            $result = self::capturePayment($order_id, $order->payment['id'], $endpoint);
            if ($result['success']) {
                $success_orders[] = $order_id;
            } else {
                $failed_orders[] = $order_id;
            }
        }
        if (! empty($success_orders)) {
            $_SESSION['message'] = 'Payment captured on orders: '.implode(', ', $success_orders);
        }
        if (! empty($failed_orders)) {
            $_SESSION['error'] .= 'Orders failed to capture payment: '.implode(', ', $failed_orders);
        }

        return true;
    }
}
