<?php

namespace app\models;

use Yii;
use yii\db\ActiveRecord;
use yii\helpers\FileHelper;
use yii\web\UploadedFile;
use app\models\Bidding;
use app\models\Bills;
use app\models\Auctions;

/**
 * This is the model class for table "lots".
 *
 * @property integer $id
 * @property integer $user_id
 * @property string $name
 * @property string $description
 * @property double $start_price
 * @property string $step
 * @property integer $docs_id
 * @property Files|null $doc
 * @property string $address
 * @property integer $delivery_time
 * @property string $delivery_term
 * @property string $requires
 * @property string $payment_term
 * @property string $payment_order
 * @property integer $category_id
 * @property string $member_require
 * @property string $member_docs
 * @property integer $requisites_id
 * @property integer $type_id
 * @property string $notes
 * @property integer $dogovor_id
 * @property string $date
 * @property integer $auction_date
 * @property integer $status
 * @property string $term_procedure
 * @property string $bidding_date
 * @property string $time_step_down
 * @property Units $unit
 * @property Images[] $images
 * @property Images[] $thumbnails
 */
class Lots extends ActiveRecord
{

    public $price_per_one;
    public $files;

    /**
     * @inheritdoc
     */

    public static function tableName()
    {
        return 'lots';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['aukname','user_id', 'name', 'description', 'start_price', 'step', 'category_id', 'member_docs', 'date'], 'required'],
            [['type_id','dogovor_id','user_id', 'category_id', 'status', 'lot_lock', 'docs_id', 'nds', 'num', 'unitId', 'count'], 'integer'],
            [['start_price', 'step'], 'number'],
            [['serialize_data','type_id','dogovor_id','date', 'auction_date', 'bidding_date', 'address', 'step_down', 'time_step_down', 'notes', 'description'], 'safe'],
            [['name', 'delivery_term', 'delivery_time', 'requires', 'member_docs', 'delivery_time', 'delivery_term', 'requires'], 'string', 'max' => 800],
            [['price_per_one'], 'number', 'integerOnly' => false],
            [['files'], 'image'],
            [['file'],'file'],
            [['file', 'files'],'safe'],
            //[['notes', 'description', 'safe'], 'string', 'max' => 15000]
        ];
    }

    /** ,'dogovor_id', 'payment_term', 'payment_order', 'member_require', 'term_procedure','requisites_id'
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'id'),
            'count' => Yii::t('app', 'Кількість'),
            'UnitId' => Yii::t('app', 'Одиниця виміру'),
            'user_id' => Yii::t('app', 'User ID'),
            'num' => Yii::t('app', 'LotNumber ID'),
            'name' => Yii::t('app', 'Lot ID'),
            'description' => Yii::t('app', 'LotsDescrioption ID'),
            'start_price' => Yii::t('app', 'Price ID'),
            'nds' => Yii::t('app', 'NDS ID'),
            'step' => Yii::t('app', 'Step ID'),
            'docs_id' => Yii::t('app', 'LotFiles ID'),
            'address' => Yii::t('app', 'AddressTo ID'),
            'delivery_time' => Yii::t('app', 'DeliveryTime ID'),
            'delivery_term' => Yii::t('app', 'DeliveryTerm ID'),
            'requires' => Yii::t('app', 'Требования к сроку и объему'),
            'payment_term' => Yii::t('app', 'PaymentTerm ID'), // auclots
            'payment_order' => Yii::t('app', 'Порядок формирования цен договора'), // auclots
            'category_id' => Yii::t('app', 'Категория товара'),
            'member_require' => Yii::t('app', 'MemberRequire ID'), // auclots
            'member_docs' => Yii::t('app', 'Перечень документов'),
            'term_procedure' => Yii::t('app', 'Term_procedure ID'), // auclots
            'requisites_id' => Yii::t('app', 'Requisites ID'), // auclots
            'notes' => Yii::t('app', 'LotsNotes ID'),
            'dogovor_id' => Yii::t('app', 'Проект договора'), // auclots
            'date' => Yii::t('app', 'Date ID'),
            'auction_date' => Yii::t('app', 'AuctionDate ID'),
            'status' => Yii::t('app', 'Status ID'),
            'lot_lock' => Yii::t('app', 'Status ID'),
            'aukname' => Yii::t('app', 'Назва аукціону'),
            'categoryName' => Yii::t('app', 'Category ID'),
            'bidding_date' => Yii::t('app', 'BiddingDate ID'),
            'step_down' => Yii::t('app', 'Circle ID'),
            'time_step_down' => Yii::t('app', 'Time Step'),
            'unitName' => Yii::t('app', 'Одиниця виміру'),
            'price_per_one' => Yii::t('app', 'Ціна за одиницю'),
        ];
    }

    public function save($validate = true, $attr = NULL)
    {
        // echo $this->aukname;
        // echo '<pre>';print_r($this);echo '</pre>';
        
        
        // if (empty($this->bidding_date)) {
        //     $lot = Auclots::findOne(['name' => $this->aukname]);
        //     //var_dump($lot); exit;
        //     //$this->address = $lot->address;
        //     $this->bidding_date = $lot->bidding_date;
        //     $this->auction_date = $lot->auction_date;
        //     $this->payment_term = $lot->payment_term;
        //     $this->payment_order = $lot->payment_order;
        //     $this->member_require = $lot->member_require;
        //     $this->term_procedure = $lot->term_procedure;
        //     $this->requisites_id = $lot->requisites_id;
        //     $this->dogovor_id = $lot->dogovor_id;            
        //     $this->member_docs = "NULL";

        //     //$this->docs_id =

        //     //$this->time_step_down = $lot->time_step_down;
        // }

        //$this->serialize_data
        $this->member_docs = "NULL";

        return parent::save($validate, $attr);
    }

    public function getRequisite()
    {
        return $this->hasOne(Requisites::className(), ['id' => 'requisites_id']);
    }

    public function getAllRequisites()
    {
        $requisites = Requisites::find() -> where(['user_id' => [Yii::$app->user->identity->id]])->all();

        foreach($requisites as $requisite){
            $requisite->title = $requisite->title . ' - ' . $requisite->account . ' / ' .  $requisite->bank;
        }
        return \yii\helpers\ArrayHelper::map($requisites, 'id', 'title');
    }    

    public function getBillPayRegistration() {
        $sql = Yii::$app->db->createCommand("
        SELECT bills.id FROM bills 
        LEFT JOIN bidding ON bills.bid_id = bidding.id
        LEFT JOIN auctions ON bidding.auction_id = auctions.id
        LEFT JOIN lots ON auctions.lot_id = lots.id
        WHERE bills.type = 'registration'
        ");
        $result = $sql->queryScalar();

        return $result;
    }

    public function getBillPayGuarantee() {
        $sql = Yii::$app->db->createCommand("
        SELECT bills.id FROM bills 
        LEFT JOIN bidding ON bills.bid_id = bidding.id
        LEFT JOIN auctions ON bidding.auction_id = auctions.id
        LEFT JOIN lots ON auctions.lot_id = lots.id
        WHERE bills.type = 'guarantee'
        ");
        $result = $sql->queryScalar();

        return $result;
    }

    public function getAuction() {
        return $this->hasOne(Auctions::className(), ['lot_id' => 'id']);
    }


    public function getCategory()
    {
        return $this->hasOne(Category::className(), ['id' => 'category_id']);
    }

    public function getCategoryName()
    {
        return $this->category->name;
    }

    public function getFile()
    {
        return $this->hasOne(Files::className(), ['lot_id' => 'id']);
    }

    public function getImages()
    {
        return $this->hasMany(Images::className(), ['related_id' => 'id'])->andOnCondition(['type' => 'image']);
    }

    public function getThumbnails()
    {
        return $this->hasMany(Images::className(), ['related_id' => 'id'])->andOnCondition(['type' => 'thumbnail']);
    }

    public function getThumbnail()
    {
        return $this->hasOne(Images::className(), ['related_id' => 'id'])->andOnCondition(['type' => 'thumbnail']);
    }

    public function getRarFile()
    {
        return Yii::$app->response->sendFile($this->file->path . $this->file->name);
    }

    public function getUnit()
    {
        return $this->hasOne(Units::className(), ['id' => 'unitId']);
    }

    public function upload()
    {
        $files = UploadedFile::getInstances($this, 'files');
        foreach ($files as $file) {
            (new Images([
                'type' => 'image',
                'related_id' => $this->id,
                '_file' => $file,
            ]))->upload();
        }
    }
}
