<?php

namespace app\controllers;

use Yii;
use app\models\Bills;
use app\models\BillsSearch;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;

/**
 * BillsController implements the CRUD actions for Bills model.
 */
class BillsController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'actions' => ['payed', 'update', 'download-template'],
                        'roles' => ['admin'],
                    ],
                    [
                        'allow' => true,
                        'actions' => ['index', 'create', 'update', 'view', 'delete', 'download-requisites'],
                        'roles' => ['@'],
                    ],
                ]
            ]
        ];
    }

    /**
     * Lists all Bills models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BillsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Bills model.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new Bills model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Bills();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    /**
     * Updates an existing Bills model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        }
        return $this->render('update', [
            'model' => $model,
        ]);
    }

    /**
     * Deletes an existing Bills model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     * @throws NotFoundHttpException if the model cannot be found
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }

    public function actionPayed($id, $payed)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return $this->findModel($id)->updateAttributes(['payed' => $payed]);
    }

    /**
     * Finds the Bills model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Bills the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Bills::findOne($id)) !== null) {
            return $model;
        }
        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }

    public function actionDownloadTemplate()
    {
        $filename = templater()->process([
            'billID' => 'номер рахунку',
            'auctionID' => 'номер аукціону',
            'date' => date('d-m-Y'),
            'inn' => 'ІПН',
            'zkpo' => 'ЭКПО',
            'uAddress' => 'юр. адреса',
            'bank' => 'банк',
            'payAccount' => 'розрахунковий рахунок',
            'phone' => 'телефон',
            'fax' => 'факс',
            'firmaFull' => 'повна назва фірми',
            'billType' => 'тип рахунку',
            'amountString' => num2str(121.34),
            'amount' => 121.34,
            'amountVat' => 121.34,
        ]);
        return Yii::$app->response->sendFile($filename);
    }

    public function actionDownloadRequisites($id) {
        $model = $this->findModel($id);
        
        $type = $model->type;
        $percent_g = 0.015;
        $percent_r = 0.0015;
        $amount_vat = $amount = $type == 'guarantee'
            ? $percent_g*$model->auction->lot->start_price
            : $percent_r*$model->auction->lot->start_price;
        if ($model->auction->lot->nds) {
            $amount = $amount/1.2*1;
        } else {
            $amount_vat *= 1.2;
        }
        
        $filename = templater()->process(
            [
                'billID' => $model->id,
                'auctionID' => $model->auction->id,
                'date' => date('d-m-Y'),
                'inn' => $model->profile->inn,
                'zkpo' => $model->profile->zkpo,
                'uAddress' => $model->profile->u_address,
                'bank' => $model->requisite->bank,
                'payAccount' => $model->requisite->account,
                'phone' => $model->profile->phone,
                'fax' => $model->profile->fax,
                'firmaFull' => $model->profile->firma_full,
                'billType' => $type == 'guarantee'? 'Гарантійний внесок': 'Регістраційний внесок',
                'amountString' => num2str($amount_vat),
                'amountVat' => $amount_vat,
                'amount' => $amount,
                'vat' => $model->auction->lot->nds ? 'з ПДВ' : 'без ПДВ',
            ],
            $type
        );
        return Yii::$app->response->sendFile($filename);

    }
}
