<?php
/**
 * Created by IntelliJ IDEA.
 * User: rocho
 * Date: 2019.03.19.
 * Time: 18:04
 */

namespace backend\components;


use common\models\Contract;
use common\models\ShoppingCart;
use common\models\Ticket;
use common\models\TicketInstallmentRequest;
use common\models\Transfer;
use yii\web\NotFoundHttpException;

class ContractManager
{

    /**
     * $STATUS_PENDING              nothing to do
     * $STATUS_MARKED_TO_SEND       nothing to do, automatic purchase in progress
     * $STATUS_SENT                 nothing to do , automatic purchase in progress
     * $STATUS_CANCELED             we can  mark it as accepted_manual, and put it back to cart. TODO: put it to pending state
     * $STATUS_REJECTED             automatic purchase was rejected, accept manual
     * $STATUS_ACCEPTED             nothing to do, automatic purchase was ok
     * $STATUS_ACCEPTED_MANUAL      this we can put back to cart
     * @param $id_ticket_installment_request
     * @throws NotFoundHttpException
     * @throws \Throwable
     */
    public function openRequestAndPutItItoCart($id_ticket_installment_request)
    {
        $request = TicketInstallmentRequest::findOne(['id_ticket_installment_request' => $id_ticket_installment_request]);

        if (!isset($request)) {
            throw new NotFoundHttpException("ticket_installment_request not found #" . $id_ticket_installment_request);
        }

        // if status does not support open, return
        if (!(
            $request->status == TicketInstallmentRequest::$STATUS_ACCEPTED_MANUAL
            || $request->status == TicketInstallmentRequest::$STATUS_CANCELED
            || $request->status == TicketInstallmentRequest::$STATUS_REJECTED
        )
        ) {
            $this->info("request can't be opened with status " . TicketInstallmentRequest::toStatusName($request->status));
            return;
        }

        $contract = Contract::findOne($request->id_contract);

        if (!isset($contract)) {
            throw new NotFoundHttpException("contract not found #" . $id_ticket_installment_request);
        }

        $this->openTicketInstallmentRequest($contract, $request);

        $this->putToCart($contract, $request);

    }

    /**
     * If status is
     * TicketInstallmentRequest::$STATUS_ACCEPTED: nothing to do, automatic purchase was successful
     * TicketInstallmentRequest::$STATUS_PENDING: nothing to do, automatic purchase was successful
     * TicketInstallmentRequest::$STATUS_MARKED_TO_SEND: nothing to do, automatic purchase was successful
     * TicketInstallmentRequest::$STATUS_SENT: nothing to do, automatic purchase was successful
     * TicketInstallmentRequest::$STATUS_SENT: nothing to do, automatic purchase was successful
     *
     * @param $contract \common\models\Contract
     * @param $part \common\models\TicketInstallmentRequest
     * @throws \Exception
     * @throws \Throwable
     */
    public function openTicketInstallmentRequest($contract, $part)
    {
        $statusChanged = false;
        if ($part->status == TicketInstallmentRequest::$STATUS_CANCELED) {
            $part->status = TicketInstallmentRequest::$STATUS_PENDING;
            $part->request_processed_at = null;
            $statusChanged = true;
        }

        if ($part->status == TicketInstallmentRequest::$STATUS_REJECTED) {
            $part->status = TicketInstallmentRequest::$STATUS_ACCEPTED_MANUAL;
            $statusChanged = true;
        }


        if ($statusChanged) {
            $part->save(false);
            if (!$contract->isFlagActive()) {
                $contract->flag = Contract::$FLAG_ACTIVE;
                $contract->save(false);
            }
        }

    }

    /**
     * @param $contract
     * @param $part
     * @throws \Exception
     */
    private function putToCart($contract, $part)
    {
        /** @var \common\models\Ticket $ticket */
        $ticket = Ticket::findOne(['id_ticket' => $part->id_ticket]);

        if (isset($ticket)) {
            $this->info("Ticket found: " . $ticket->id_ticket . "/" . $ticket->ticketType->name);

            // inactivate ticket
            if ($ticket->status != Ticket::STATUS_INACTIVE) {
                $ticket->status = Ticket::STATUS_INACTIVE;
                $ticket->save(false);
            }

            // set transfer status to not paid
            /** @var \common\models\Transfer $transfer */
            $transfer = $ticket->transfer;
            if ($transfer->status != Transfer::STATUS_NOT_PAID) {
                // clean up transfer paid status
                $statusOriginal = $transfer->status;
                $transfer->status = Transfer::STATUS_NOT_PAID;
                $transfer->paid_at = null;
                $transfer->paid_by = null;
                $transfer->payment_method = null;
                $transfer->save(false);

                $this->info("Restore transfer: ");
                $this->info($transfer->id_transfer);
                $this->info(Transfer::toStatusName($statusOriginal) . "->" . Ticket::toStatusName($transfer->status));
            }

            // check shopping cart
            $cart = ShoppingCart::findOne(['id_transfer' => $transfer->id_transfer]);
            // put transfer into cart if it is not there
            if (!isset($cart)) {
                $cart = new ShoppingCart();
                $cart->id_customer = $contract->customer->id_customer;
                $cart->id_transfer = $transfer->id_transfer;
                if (!$cart->save(false)) {
                    /** @noinspection SpellCheckingInspection */
                    $E_FAILED_TO_SAVE = "Vendég kosár hozzárendelés sikertelen!";
                    \Yii::error($E_FAILED_TO_SAVE);
                    throw new \Exception($E_FAILED_TO_SAVE);
                }
            }

        }
    }

    private function info($message)
    {
        \Yii::info($message);
    }

}
