<?php

use common\logic\Document\DeliveryNote\Module\DeliveryNoteModule;
use common\logic\Document\Invoice\Module\InvoiceModule;
use common\logic\Document\Quotation\Module\QuotationModule;
use yii\db\Migration;
use yii\db\Schema;

/**
 * Class m231018_074957_add_column_document_reference_number
 */
class m231018_074957_add_column_document_reference_number extends Migration
{
    /**
     * {@inheritdoc}
     */
    public function safeUp()
    {
        $this->addColumn('quotation', 'reference_number', Schema::TYPE_INTEGER);
        $this->addColumn('delivery_note', 'reference_number', Schema::TYPE_INTEGER);
        $this->addColumn('invoice', 'reference_number', Schema::TYPE_INTEGER);

        $quotationArray = QuotationModule::getInstance()->getRepository()->findAll();
        $deliveryNoteArray = DeliveryNoteModule::getInstance()->getRepository()->findAll();
        $invoiceArray = InvoiceModule::getInstance()->getRepository()->findAll();

        $this->updateReferenceNumber($quotationArray);
        $this->updateReferenceNumber($deliveryNoteArray);
        $this->updateReferenceNumber($invoiceArray);
    }

    /**
     * {@inheritdoc}
     */
    public function safeDown()
    {
        $this->dropColumn('quotation', 'reference_number');
        $this->dropColumn('delivery_note', 'reference_number');
        $this->dropColumn('invoice', 'reference_number');
    }

    public function updateReferenceNumber(array $documentArray)
    {
        foreach($documentArray as $document) {
            $document->reference_number = $this->getReferenceNumber($document);
            $document->save();
        }
    }

    public function getReferenceNumber($document)
    {
        $referenceDocument = $document->reference;
        $pattern = '#([A-Z]+)?([0-9]+)#';
        preg_match($pattern, $referenceDocument, $matches, PREG_OFFSET_CAPTURE);
        if(isset($matches[2])) {
            return (int) $matches[2][0];
        }

        return null;
    }
}
