<?php

namespace app\controllers;

use app\models\Bills;
use app\models\Images;
use PhpOffice\PhpWord\Shared\ZipArchive;
use Yii;
use app\models\Files;
use app\models\Lots;
use app\models\Messages;
use app\models\LotSearch;
use app\models\Auctions;
use yii\helpers\ArrayHelper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\web\UploadedFile;
use yii\filters\AccessControl;
use app\models\Subscriptions;
use app\models\Eventlog;


/**
 * LotsController implements the CRUD actions for Lots model.
 */
class LotsController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'create', 'view', 'update', 'delete', 'upload', 'download', 'confirm', 'auction'],
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['index', 'create', 'view', 'update', 'delete', 'upload', 'download', 'confirm', 'auction'],
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    /**
     * Lists all Lots models.
     * @return mixed
     */
    public function init()
    {
        if (@!Yii::$app->user->identity->confirmed_at && (@Yii::$app->user->identity->role == 1)) {
            return $this->redirect('/registration/organizer');
        }
        $this->layout = '@app/views/layouts/backend/user';
        parent::init();
    }

    public function actionIndex()
    {
        if (Yii::$app->user->can('org') || Yii::$app->user->can('admin')) {
            $searchModel = new LotSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Displays a single Lots model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $files = new Files();
        $files->uploads = '../uploads/bids/';

        if (Yii::$app->request->isPost && false != ($file = UploadedFile::getInstances($files, 'file'))) {

		$fileName = $files->uploadFile();
            $model = $this->findModel($id);
            // $file->name = $files->transliteration($file->name);
            //$files->name = $file->name;
            // $path = Yii::$app->params['uploadPath'].$file->name;
            if ($fileName) {
                $files->saveFile([
                    'name' => $fileName,
                    'path' => $files->uploads,
                    'user_id' => Yii::$app->user->identity->id,
                    'auction_id' => $model->auction->id,
                    'lot_id' => $model->id,
                    'type' => 'bid',
                ]);
                Yii::$app->session->setFlash('success', Yii::t('app', 'FileUploaded ID'));
            } else {
                Yii::$app->session->setFlash('danger', Yii::t('app', 'Cannot save file'));
            }
        }
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
    {
        $model = new Lots();
        $files = new Files();
        $files->uploads = '../uploads/lots/';
        $fileName = $files->uploadFile();
        // print_r(Yii::$app->request->post());

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if ($fileName) {
                $docs_id = $files->saveFile([
                    'name' => $fileName,
                    'path' => $files->uploads,
                    'user_id' => Yii::$app->user->identity->id,
                    'lot_id' => $model->id,
                    'auction_id' => null,
                    'type' => 'lot',
                ]);
                $model->updateAttributes(['docs_id' => $docs_id]);
                $model->save();
                $model->upload();                
            }

            $dogovor = UploadedFile::getInstance($files, 'project_dogovor');
            if(isset($dogovor))
            {
                $dogovor->name = $files->transliteration($dogovor->name);
                $path = Yii::$app->params['uploadPath'].$dogovor->name;
                $dogovor->saveAs($path);
                $dogovor_id = $files->saveFile([
                    'name'=>$dogovor->name,
                    'path'=>Yii::$app->params['uploadPath'],
                    'user_id'=>Yii::$app->user->identity->id,
                    'auction_id'=>'null',
                    'lot_id'=>$model->id,
                    'type'  =>  'NULL'
                ]);
                $model->updateAttributes(['dogovor_id' => $dogovor_id]);
            }
            
            $data = json_decode($model->serialize_data, true);
            $model->updateAttributes(['serialize_data' => json_encode($data)]);
            
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', ['model' => $model]);
        }
    }

    public function actionConfirm($id, $status)
    {
        if (Yii::$app->user->can('admin') || Yii::$app->user->can('org')) {
            $model = $this->findModel($id);
            Yii::$app->response->format = Response::FORMAT_JSON;
            return
                $model->updateAttributes(['status' => $status,]);
        }else{
            return $this->redirect(['view', 'id' => $id]);
        }
    }

    public function actionCircle_down($id)
    {
        if (Yii::$app->user->can('admin') || Yii::$app->user->can('org')) {
            $model = $this->findModel($id);
            Yii::$app->db->createCommand("UPDATE lots SET step_down=step_down-1 WHERE id=:id")
                ->bindValue(':id', $id)
                ->execute();
        }
        return $this->redirect(['view', 'id' => $id]);
    }

    public function actionCircle_up($id)
    {
        if (Yii::$app->user->can('admin') || Yii::$app->user->can('org')) {

            $model = $this->findModel($id);
            Yii::$app->db->createCommand("UPDATE lots SET step_down=step_down+1 WHERE id=:id")
                ->bindValue(':id', $id)
                ->execute();
        }
        return $this->redirect(['view', 'id' => $id]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $files = new Files();
        $files->uploads = '../uploads/lots/';
        $fileName = $files->uploadFile();

        if ($model->status == 2) {
            Yii::$app->session->setFlash('danger', Yii::t('app', 'LotEditNoSuccess ID'));
            return $this->redirect(['index']);
        } elseif ($model->status == 3) {
            Yii::$app->session->setFlash('danger', Yii::t('app', 'LotEditNoReject ID'));
            return $this->redirect(['index']);
        }

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            if ($fileName) {
                $docs_id = $files->saveFile([
                    'name' => $fileName,
                    'path' => $files->uploads,
                    'user_id' => Yii::$app->user->identity->id,
                    'lot_id' => $model->id,
                    'auction_id' => null,
                    'type' => 'lot',
                ]);
                $model->updateAttributes(['docs_id' => $docs_id]);
                $model->save();
                $model->upload();                
            }

            $dogovor = UploadedFile::getInstance($files, 'project_dogovor');
            if(isset($dogovor))
            {
                $dogovor->name = $files->transliteration($dogovor->name);
                $path = Yii::$app->params['uploadPath'].$dogovor->name;
                $dogovor->saveAs($path);
                $dogovor_id = $files->saveFile([
                    'name'=>$dogovor->name,
                    'path'=>Yii::$app->params['uploadPath'],
                    'user_id'=>Yii::$app->user->identity->id,
                    'auction_id'=>'null',
                    'lot_id'=>$model->id,
                    'type'  =>  'NULL'
                ]);
                $model->updateAttributes(['dogovor_id' => $dogovor_id]);
            }
            
            $data = json_decode($model->serialize_data, true);
            $model->updateAttributes(['serialize_data' => json_encode($data)]);

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    public function actionDelete($id)
    {
        $model = $this->findModel($id);

        if ($model->status == 2) {
            Yii::$app->session->setFlash('danger', Yii::t('app', 'LotEditNoSuccess ID'));
            return $this->redirect(['index']);
        } elseif ($model->status == 3) {
            Yii::$app->session->setFlash('danger', Yii::t('app', 'LotEditNoReject ID'));
            return $this->redirect(['index']);
        }
        if ($model->status == 1) {
            if ($model->auction) {
                $model->auction->delete();
            }
            Yii::createObject(Eventlog::className())->PutLog([
                'user_id' => Yii::$app->user->identity->id,
                'ip' => Yii::$app->request->getRemoteIP(),
                'auk_id' => $model->id,
                'action' => Yii::t('app', 'OrgDeleteAuk ID {action}',
                    ['action' => $model->aukname]),
            ]);
            $model->lot_lock = 0;
            $this->findModel($id)->delete();
            Yii::$app->session->setFlash('danger', Yii::t('app', 'Auction deleted successfully'));
            return $this->redirect(['index']);
        } else {
            return $this->render('/message', [
                'title' => \Yii::t('app', 'Not Permission'),
                'module' => $this->module,
            ]);
        }
    }

    public function actionAuction($id, $type)
    {
        if(Yii::$app->user->can('admin') || Yii::$app->user->can('org'))
        {
            // print_r($_POST);die();

            $model = $this->findModel($id);

            if($model->status==2 && $model->lot_lock==0 || $model->status==4 && $model->lot_lock==0)
            {
                // if(Yii::$app->request->post('date_stop'))
                // {
                //     $date_stop = Yii::$app->request->post('date_stop');
                //     $time_cont = Yii::$app->request->post('time_cont');
                // }
                // else
                // {
                //     $date = strtotime($model->auction_date) + 7200;
                //     $date_stop = date("Y-m-d H:i:s", $date);
                // }
                
                //$date = new \DateTime($model->auction_date);
                
                $setData = json_decode($model->serialize_data);

                $parts = array_pad(explode(':', $setData->time_step_change), 3, 0);
                $timeStepFormat = sprintf(
                    "%02d:%02d:%02d.00000",
                    (int)$parts[0],
                    (int)$parts[1],
                    (int)$parts[2]
                );                
                
                // create auction
                $insert = [
                    'user_id' => $model->user_id,
                    'name'   =>  $model->aukname,
                    'lot_id'    =>  $model->id,
                    'lot_num'   =>  $model->num,
                    'date_start'    =>  $model->auction_date,
                    'bidding_date'  =>  $model->bidding_date,
                    'date_stop' =>  $setData->date_stop,
                    'type_id'   =>  $setData->type,
                    'time_step_down' => $timeStepFormat,
                    'time_cont'=> $setData->time_cont,
                    'step_down'=> $setData->step_change,
                    'temp_step_down'=>$setData->step_change,
                    //'date_stop' =>  $date->modify('+1 day')->format('Y-m-d H:i:s'),
                ];
                // echo '<pre>';
                // print_r(json_decode($model->serialize_data));
                // print_r($insert);
                // echo '</pre>';
                // die();

                $auction = Yii::createObject(Auctions::className())->CreateAuction($insert);
                Subscriptions::createNewsletter($auction);
                /* Узгоджено організатором */
                if($model->status==4)
                {
                    $model->updateAttributes(['lot_lock' => '0']);
                }
                $model->updateAttributes(['lot_lock' => '1']);

                $notes_org = Yii::t('app','AuctionCreatedOnLot ID') .": ". $model->aukname ." / " .
                    Yii::t('app','LotNumber ID'). $model->num . " " . $model->name;
                Yii::createObject(Messages::className())->CreateMessage(['user_id' => $model->user_id, 'notes' => $notes_org]);

                Yii::$app->session->setFlash('success', Yii::t('app', 'AuctionCreated ID'));
                return $this->redirect(['index']);

            } elseif ($model->status == 1 || $model->status == 3) {
                Yii::$app->session->setFlash('warning', Yii::t('app', 'NeedConfirmLot ID'));
                return $this->redirect(['view', 'id' => $model->id]);
            }
            else
            {
                Yii::$app->session->setFlash('warning', Yii::t('app', 'LotInAuction ID'));
                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            Yii::$app->session->setFlash('success', Yii::t('app', 'not permission2'));
            return $this->redirect(['view', 'id' => $model->id]);
        }
    }

    public function actionStepChange()
    {
        $id = Yii::$app->request->post('id');
        $value = Yii::$app->request->post('value');
        $model = Lots::findOne(['id' => $id]);
        $model->step_down = $value;
        if (Yii::$app->request->post() && $model->save()) {
            return $this->redirect(['/lots/view', 'id' => $id]);
        }
    }

    public function actionTimeStepChange()
    {
        $id = Yii::$app->request->post('id');
        $value = Yii::$app->request->post('concat_val');
        $model = Lots::findOne(['id' => $id]);
        $model->time_step_down = $value;
        if (Yii::$app->request->post() && $model->save()) {
            return $this->redirect(['/lots/view', 'id' => $id]);
        }
    }

    public function actionClone($id)
    {
        $model = $this->findModel($id);
        // print_r($model->attributes);
        // exit;
        $attributes = $model->attributes;
        $attributes['id'] = null;
        $attributes['status'] = 1;
        $attributes['lot_lock'] = 0;
        $attributes['docs_id'] = null;
        $clone = new Lots($attributes);
        if ($clone->load(Yii::$app->request->post()) && $clone->save()) {
            if ((Yii::$app->request->post('agreeCopyFile')) && $model->file) {
                $clone->updateAttributes(['docs_id' => $model->file->copy($clone->id)]);
            } else {
                $clone->updateAttributes(['docs_id' => null]);
            }
            if (Yii::$app->request->post('agreeCopyImg')) {
                foreach ($model->images as $image) {
                    $image->copy($clone->id);
                }
                foreach ($model->thumbnails as $thumbnail) {
                    $thumbnail->copy($clone->id);
                }
            }
            return $this->redirect(['view', 'id' => $clone->id]);

        } else {
            return $this->render('clone', [
                'model' => $model,
            ]);
        }
    }

    protected function findModel($id)
    {
        if (($model = Lots::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist . ');
        }
    }
}
