<?php

namespace KupShop\KupShopBundle\Email;

class PaymentSuccessEmail extends OrderEmail
{
    protected static $name = 'Objednávka zaplacena';
    protected static $type = 'PAYMENT_SUCCESS';
    protected static $priority = 2;

    protected $subject = 'Děkujeme za zaplacení objednávky {KOD}';
    protected $template = 'email/payment_success.tpl';

    protected $payment;

    public function setPayment($payment)
    {
        $this->payment = $payment;

        return $this;
    }

    public function renderEmail($template, $data = [], $base_template = 'payment_success.tpl'): array
    {
        if ($this->payment) {
            $data = array_merge($data, ['payment' => $this->payment]);
        }

        $message = parent::renderEmail($template, $data, $base_template);

        return $message;
    }

    public function testEmail(): array
    {
        if (!isset($this->order)) {
            $payment = false;
            if (findModule(\Modules::EET)) {
                $payment = sqlQuery('SELECT * FROM order_payments WHERE id = (SELECT MAX(id_payment) FROM eet_sent_payment)')->fetch();
            }
            if (!$payment) {
                $payment = sqlQuery('SELECT * FROM order_payments WHERE id = (SELECT MAX(id) FROM order_payments)')->fetch();
            }
            $this->setPayment($payment);
            if ($this->payment) {
                $id_order = $this->payment['id_order'];
            } else {
                $id_order = returnSQLResult('SELECT MAX(id) FROM orders');
            }
            $order = new \Order();
            $order->createFromDB($id_order);
            $this->setOrder($order);
        }

        return parent::testEmail();
    }

    public function getMicrodata(): array
    {
        if ($microdata = parent::getMicrodata()) {
            $microdata['orderStatus'] = 'https://schema.org/OrderProcessing';
        }

        return $microdata;
    }
}
