<?php

namespace KupShop\KupShopBundle\Util\Mail;

use KupShop\DaktelaBundle\Utils\DaktelaUpdater;
use KupShop\KupShopBundle\Context\ContextManager;
use KupShop\KupShopBundle\Email\EmailInterface;
use KupShop\TelfaBundle\Exceptions\TelfaDefaultException;
use KupShop\TelfaBundle\Utils\SMSHandler;
use Symfony\Contracts\Service\Attribute\Required;

class SMSSender
{
    /**
     * @var SMSHandler
     */
    private $SMSHandler;

    /**
     * @var DaktelaUpdater
     */
    private $DaktelaUpdater;

    #[Required]
    public ContextManager $contextManager;

    public function __construct(?SMSHandler $SMSHandler = null, ?DaktelaUpdater $DaktelaUpdater = null)
    {
        $this->SMSHandler = $SMSHandler;
        $this->DaktelaUpdater = $DaktelaUpdater;
    }

    public function sendSMS(\Order $order, EmailInterface $email_service, $force_order_history = false)
    {
        return $this->contextManager->activateOrder($order, function () use ($order, $force_order_history, $email_service) {
            if (($service = $this->getBackend()) && !empty($order->invoice_phone)) {
                try {
                    if ($sms = $email_service->getSMSText()) {
                        $sent = $service->sendSMS($order->invoice_phone, strip_tags($sms));
                        if ($sent === true) {
                            if (!$order->isNewOrder() || $force_order_history) {
                                $this->saveSMStoOrder($order->id, 'Na tel. '.$order->invoice_phone.': '.$sms, 2, $order->status);
                            }
                        } else {
                            $order->logHistory('Odeslání SMS bylo neúspěšné.', false);
                        }
                    }
                } catch (TelfaDefaultException $e) {
                    throw $e;
                } catch (Exception $e) {
                    $order->logHistory('Odeslání SMS bylo neúspěšné.', false);
                    $sentry = getRaven();
                    $sentry->captureMessage('SMS error:', [], ['extra' => [
                        'request' => $_REQUEST,
                        'sms' => $sms,
                        'invoice_phone' => $order->invoice_phone,
                        'error_message' => $e->getMessage(),
                        'error_except' => $e,
                    ]]);
                }
            }
        });
    }

    /**
     * @param $notified : 2 -> sent sms, 3 -> incoming sms
     */
    public function saveSMStoOrder($id_order, $message, $notified = 2, $id_status = 0)
    {
        $order = new \Order();
        $order->createFromDB($id_order);
        $order->logHistory($message, $notified);
    }

    public function getBackend(): object|bool
    {
        $dbcfg = \Settings::getDefault();
        if (($dbcfg['daktela']['sms']['active'] ?? false) == 'Y') {
            return $this->DaktelaUpdater;
        }

        if (findModule(\Modules::TELFA)) {
            return $this->SMSHandler;
        }

        return false;
    }
}
