<?php

namespace PortalPeople\invoicing\controllers;


use Yii;
use backend\models\{Invoicebe, Invoicesbesearch};
use backend\models\Pagegroupbe;

use PortalPeople\invoicing\models\Invoicesbe;
use PortalPeople\creditnotes\models\CreditNote;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\filters\VerbFilter;

/**
 * Invoice Controller
 *
 * Handles invoice viewing, credit note creation, and related operations.
 */
class InvoiceController extends Controller {
    /**
     * Is this used in this Project, Display in Permissions Force 403 if false
     *
     * @var boolean
     */
    private $used = true;
    /**
     * Sets up permissions from the Permmissions Controller and File.
     *
     * @return void
     */
    public function behaviors(){
        return [
            'access' => [
                'class' => \yii\filters\AccessControl::class,
           		'rules' => \common\models\Permissions::getPermissions(self::class),
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }


    /**
     * Lists all Invoicebe models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new Invoicesbesearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

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

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

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
     /**
     * Lists Deleted Invoicebe models.
     * @return mixed
     */
    public function actionDeleted()
    {
        $searchModel = new Invoicesbesearch();
        $dataProvider = $searchModel->deleted(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single Invoicebe model.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionView($id, $language ='en')
    {
        return $this->render('view', [
            'model' => $this->findModel($id, $language),
        ]);
    }
    /**
     * Displays a single Invoicebe model.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionExcelview($id, $language ='en')
    {
        $model = $this->findModel($id, $language);
        return $model->exporttoexcel();
    }
    /**
     * Displays a single Invoicebe model.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionResend($id, $language ='en')
    {
        $model = $this->findModel($id, $language);
        $model->resendInvoice() ? Yii::$app->session->addFlash('alerts', 'Message Queued to '.$model->email) : Yii::$app->session->addFlash('alerts-d', 'Message Error');
        return $this->redirect(Yii::$app->request->referrer);
    }
    
    public function actionRecreatepdf($id, $language ='en')
    {
        $model = $this->findModel($id, $language);
        $model->save();
        return $this->redirect(Yii::$app->request->referrer);
    }

    
    public function actionInvoiceview($id, $language ='en')
    {
        $page = Pagegroupbe::find()->where(['url' => 'invoice-layout', 'language' => 'en'])->one();
        $model = $this->findModel($id, $language);
        $this->layout = 'pdf';
        if(strtotime(str_replace('/', '-', $model->created_at)) < strtotime('2022-07-13')){
            $single = '_invoice';
        } else {
            $single = '_invoice_2';
        }
        return $this->render('@backend/views/invoice/'.$single, ['model' => $model, 'page' => $page]);
        
    }
    public function actionBulkinvoiceview($id, $language ='en')
    {
        $page = Pagegroupbe::find()->where(['url' => 'invoice-layout', 'language' => 'en'])->one();
        $model = $this->findModel($id, $language);
        $this->layout = 'pdf';
        if(strtotime(str_replace('/', '-', $model->created_at)) < strtotime('2022-07-13')){
            $bulk = '_bulkinvoice';
        } else {
            $bulk = '_bulkinvoice_2';
        }
        return $this->render('@backend/views/invoice/'.$bulk, ['model' => $model, 'page' => $page]);
    }
    public function actionWebview($id, $language ='en')
    {
        $page = Pagegroupbe::find()->where(['url' => 'invoice-layout', 'language' => 'en'])->one();
        $model = $this->findModel($id, $language);
        if(strtotime(str_replace('/', '-', $model->created_at)) < strtotime('2022-07-13')){
            $bulk = '_bulkinvoice';
            $single = '_invoice';
        } else {
            $bulk = '_bulkinvoice_2';
            $single = '_invoice_2';
        }
        if($model->type == 'bulk'){
            return $this->render('@backend/views/invoice/'.$bulk, ['model' => $model, 'page' => $page]);
        } else {
            return $this->render('@backend/views/invoice/'.$single, ['model' => $model, 'page' => $page]);
        }
        
    }
    /**
     * Creates a new Invoicebe model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Invoicebe();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $model = Invoicebe::find()->where(['=', 'created_at', strtotime(str_replace('/', '-', $model->created_at))])->andWhere(['=', 'created_by', $model->created_by])->one();
        
            return $this->redirect(['view', 'id' => $model->id, 'language' => $model->language]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing Invoicebe model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionUpdate($id, $language)
    {
        $model = $this->findModel($id, $language);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id, 'language' => $model->language]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
    /**
     * Updates an existing Invoicebe model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionPaidamount()
    {
        $id = Yii::$app->request->post('id');
        $language = Yii::$app->request->post('language');
        $model = $this->findModel($id, $language);
        return $this->renderAjax('payment', ['model'=> $model]);
    }

    public function actionInvoicepaid(){
        $id = Yii::$app->request->post('Invoicebe')['id'];
        $language = Yii::$app->request->post('Invoicebe')['language'];
        
        $model = $this->findModel($id, $language);
        $model->load(Yii::$app->request->post());

        Yii::$app->response->format = 'json';
        $result = $model->invoicepaid() ? ['status' => 200, 'message' => 'Saved'] :['status' => 100, 'message' => $model->errors];        
        if($result['status'] == 200){
            Yii::$app->session->addFlash('success', 'Amount Paid for Invoice ' . $model->invoiceno);
        } else {
            Yii::$app->session->addFlash('error', 'Error: ' . $model->errors);
        }
        return $result;
    }

    /**
     * Deletes an existing model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
     
    public function actionPurge($id, $language) {
        $model = $this->findModel($id, $language);
        if($model){   
            $model->purge();
        }
        return $this->redirect(['index']);
    }
    /**
     * Deletes an existing  model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @param string $language
     * @return mixed
     */
    public function actionDelete($id, $language) {
        $upload = $this->findModel($id, $language);
        if($upload){   
            $upload->delete();
        }
        return $this->redirect(Yii::$app->request->referrer);
    }

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

    public function actionCredititems($id){

        $model = Invoicebe::findOne(['id' => $id]);
        return $this->renderAjax('creditlist', ['model' => $model]);

    }


    
    public function actionCredit(){

    }


    public function actionCancel($id){
        //$id = Yii::$app->request->post('id');
        $model = $this->findModel($id, 'en');
        if($model !== null){
            /** Changes Carts to TO */
            foreach($model->carts as $key => $cart){
                $cart->invoiceno = null;
                $cart->invoiceid = null;
                $cart->status = 'Booked';
                $cart->billingstatus = 'Pay by Tour Operator';
                foreach($model->payments as $k => $payment){
                    if ($payment->invoiceid == $id) {
                        $payment->delete();
                    }
                }
                $cart->save();
            }
            foreach($model->cartlines as $key => $cartline){
                $cartline->status = 'Cancelled';
                $cartline->save();
            }
            $model->status = 'Cancelled';
            $model->amountout = 0;
            $model->subtotal = 0;
            $model->comission_amount = 0;
            $model->total = 0;
            $model->save();
        }
        return $this->redirect(Yii::$app->request->referrer);
    }

    /**
     * List invoices for a cart
     *
     * @param int $cartId
     * @return string
     */
    public function actionList($cartId)
    {
        $cart = \backend\models\Cartsbe::findOne($cartId);
        if (!$cart) {
            throw new NotFoundHttpException('Cart not found.');
        }

        $invoices = Invoicesbe::find()
            ->where(['source_cart_id' => $cartId])
            ->all();

        return $this->render('list', [
            'cart' => $cart,
            'invoices' => $invoices,
        ]);
    }


    /**
     * List credit notes for invoice
     *
     * @param int $invoiceId
     * @return string
     */
    public function actionCreditNotes($invoiceId)
    {
        $invoice = $this->findInvoice($invoiceId);
        
        $creditNotes = CreditNote::find()
            ->where(['entity_id' => $invoiceId, 'entity_type' => Invoicesbe::class])
            ->orderBy(['created_at' => SORT_DESC])
            ->all();

        return $this->render('credit-notes', [
            'invoice' => $invoice,
            'creditNotes' => $creditNotes,
        ]);
    }

    /**
     * Create new credit note for invoice
     *
     * @param int $invoiceId
     * @return string|\yii\web\Response
     */
    public function actionCreateCreditNote($invoiceId)
    {
        $invoice = $this->findInvoice($invoiceId);

        if (!$invoice->canAddCreditNote()) {
            throw new \yii\web\BadRequestHttpException('Invoice balance is fully credited.');
        }

        $creditNote = new CreditNote([
            'entity_id' => $invoiceId,
            'entity_type' => Invoicesbe::class,
        ]);

        if ($creditNote->load(Yii::$app->request->post()) && $creditNote->validate()) {
            if ($creditNote->save()) {
                Yii::$app->session->setFlash('success', 'Credit note created successfully.');
                return $this->redirect(['credit-notes', 'invoiceId' => $invoiceId]);
            }
        }

        return $this->render('create-credit-note', [
            'invoice' => $invoice,
            'creditNote' => $creditNote,
        ]);
    }

    /**
     * Issue (finalize) a credit note
     *
     * @param int $creditNoteId
     * @return \yii\web\Response
     */
    public function actionIssueCreditNote($creditNoteId)
    {
        $creditNote = CreditNote::findOne($creditNoteId);
        if (!$creditNote) {
            throw new NotFoundHttpException('Credit note not found.');
        }

        if (!Yii::$app->request->validateCsrfToken()) {
            throw new \yii\web\BadRequestHttpException('Invalid CSRF token.');
        }

        if ($creditNote->issue()) {
            Yii::$app->session->setFlash('success', 'Credit note issued successfully.');
        } else {
            Yii::$app->session->setFlash('error', 'Failed to issue credit note.');
        }

        return $this->redirect(['credit-notes', 'invoiceId' => $creditNote->entity_id]);
    }

    /**
     * Find invoice by ID
     *
     * @param int $id
     * @return Invoicesbe
     * @throws NotFoundHttpException
     */
    protected function findInvoice($id)
    {
        $invoice = Invoicesbe::findOne($id);
        if (!$invoice) {
            throw new NotFoundHttpException('Invoice not found.');
        }
        return $invoice;
    }
}
