<?php
namespace PortalPeople\invoicing\services;

use Yii;

class InvoiceGenerationServiceB2B
{
    /**
     * Generate and send invoice for B2B
     * @param int $cartId
     * @param string $email
     * @return mixed
     */
    public static function generateAndSendInvoice($cartId, $email = null)
    {
        $model = \backend\models\Cartsbe::FindOne(['id' => $cartId]);
        $invoice = new \backend\models\Invoicebe(['id' => \backend\models\Invoicebe::Tempid(), 'language' => 'en']);
        $invoice->attributes = $model->attributes;
        unset($invoice->created_at, $invoice->created_by, $invoice->createdby_name, $invoice->id, $invoice->date);
        $invoice->language = 'en';
        $invoice->status = 'Active';
        $invoice->id = $invoice->tempid();
        $invoice->basketid = $model->id;
        $invoice->orderref = strval($model->orderref);
        $invoice->invoiceno = Date('Y') . str_pad(\backend\models\Settings::invno('40506323-F03F-4561-8860-6FC2CBE73F1B'), 6, "0", STR_PAD_LEFT);
        $invoice->name = date('F Y', strtotime(str_replace('/','-', $model->centrearrddate)));
        $days = is_int($model->agent->payment_data->days) == true && empty($model->agent->payment_data->days) == false ? $model->agent->payment_data->days : 0 ;
        $invduedate = new \DateTime();
        $invduedate->add(new \DateInterval('P'. $days.'D'));
        $invoice->invoiceduedate = $invduedate !== false ? $invduedate->format('Y-m-d') : null;
        $voucherU = $invoice->voucheramountused;
        $voucherC = $invoice->voucheramountcreated;
        foreach($model->dcartlines as $key => $cartline){
            $invoiceline = new \backend\models\Invoicelinesbe();
            $invoiceline->attributes = $cartline->attributes;
            $invoiceline->language = 'en';
            $invoiceline->comissioned = in_array($invoiceline->productid, \backend\models\Categoriesbe::Nocommmisions()) == false && $model->agent ? true : false;
            unset($invoiceline->created_at, $invoiceline->created_by, $invoiceline->createdby_name, $invoiceline->id);
            $invoiceline->invoiceid = $invoice->id;
            $invoiceline->orderref = strval($model->orderref);
            $invoiceline->id = $invoiceline->tempid();
            if ($invoiceline->comissioned == true) {
                $comissionableamount = $invoiceline->linetotal;
                if($voucherU > 0){
                    $poss = $invoiceline->linetotal - $voucherU;
                    $voucherU = $voucherU - $invoiceline->linetotal;
                    $comissionableamount = $poss > 0 ? $poss : 0;
                }
                $comissionP = 0;
                foreach($model->agent->commission_data as $comission) {
                        if ($invoiceline->centerid == $comission->centerid) {
                            $comissionP = $comission->percentage;
                        break;
                    }
                }
                $invoiceline->comission_data = \yii\helpers\Json::encode(['percentage' => $comissionP, 'commissionableamount' => $comissionableamount]);
                $invoiceline->comission_amount = $model->agent && $comissionP > 0 ? $comissionableamount / (100 / $comissionP) : null;
            } else {
                $invoiceline->comission_data = \yii\helpers\Json::encode(['percentage' => 0, 'commissionableamount' => 0]);
                $invoiceline->comission_amount = 0;
            }
            $cartline->updateAttributes(['pricelocked' => true]);
            $invoiceline->save();
            foreach($cartline->addons as $key => $addon){
                $invaddon = new \backend\models\Invoicelinesbe();
                $invaddon->attributes = $addon->attributes;
                $invaddon->language = 'en';
                unset($invaddon->created_at, $invaddon->created_by, $invaddon->createdby_name, $invaddon->id);
                $invaddon->id = $invoiceline->tempid();
                $invaddon->relatedid = $invoiceline->id;
                $invaddon->invoiceid = $invoice->id;
                $invaddon->comissioned = in_array($invaddon->productid, \backend\models\Categoriesbe::Nocommmisions()) == false && $model->agent ? true : false;;
                if ($invaddon->comissioned == true) {
                    $comissionableamount = $invaddon->linetotal;
                    if($voucherU > 0){
                        $poss = $invaddon->linetotal - $voucherU;
                        $voucherU = $voucherU - $invoiceline->linetotal;
                        $comissionableamount = $poss > 0 ? $poss : 0;
                    }
                    $comissionP = 0;
                    foreach($model->agent->commission_data as $comission) {
                            if ($invaddon->centerid == $comission->centerid) {
                                $comissionP = $comission->percentage;
                            break;
                        }
                    }
                    $invaddon->comission_data = \yii\helpers\Json::encode(['percentage' => $comissionP, 'commissionableamount' => $comissionableamount]);
                    $invaddon->comission_amount = $model->agent && $comissionP > 0 ? $comissionableamount / (100 / $comissionP) : null;
                } else {
                    $invaddon->comission_data = \yii\helpers\Json::encode(['percentage' => 0, 'commissionableamount' => 0]);
                    $invaddon->comission_amount = 0;
                }
                $invaddon->save();
                $addon->updateAttributes(['pricelocked' => true]);
            }
        }
        
        if($invoice->save()){
            \Yii::$app->session->addFlash('alerts', 'Invoice ' . $invoice->invoiceno . ' created successfully');
            $payment = new \backend\models\Paymentresponsesbe();
            $payment->basketid = $model->id;
            $payment->invoiceid = $invoice->id;
            $payment->Invoice();
            $payment->save();
            $model->invoiceno =  $invoice->invoiceno;
            $model->billingstatus = 'Invoiced';
            $model->invoiceid = $invoice->id;
            $model->save();   
        } else {
            \backend\models\Invoicelinesbe::deleteAll(['invoiceid' => $invoice->id]);
            $response = \Yii::$app->response;
            $response->statusCode = 422;
            $response->format = 'json';
            return ['status' => 'error', 'message' => 'Invoice could not be created. Please check the data and try again.', 'errors' => $invoice->getErrors()];
        }
        return $invoice;
    }
    
}
