/**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $i = 0;
     $model1 = new SalesInvoices();
     $model2 = new SalesInfo();
     $receivedModel = new MoneyReceived();
     if (isset($_POST['SalesInvoices'])) {
         $model1->attributes = $_POST['SalesInvoices'];
         $model1->save();
         $sales_invoice_id = $model1->id;
         if (isset($_POST['SalesInfo'])) {
             $testModel = array();
             while ($i <= $_SESSION['sts']) {
                 $testModel[$i] = new SalesInfo();
                 if (isset($_POST['SalesInfo'][$i])) {
                     $testModel[$i]->attributes = $_POST['SalesInfo'][$i];
                     $testModel[$i]->sales_invoice_id = $sales_invoice_id;
                     if (!empty($testModel[$i]->unit_price)) {
                         $testModel[$i]->save();
                         $item = InventoryItems::model()->findByPk($testModel[$i]->item_id);
                         $item->qty -= $testModel[$i]->qty;
                         $item->save();
                     }
                 }
                 $i++;
             }
         }
         if (isset($_POST['MoneyReceived'])) {
             $receivedModel->attributes = $_POST['MoneyReceived'];
             $receivedModel->received_date = $model1->issue_date;
             $receivedModel->sales_invoice_id = $model1->id;
             $receivedModel->customer_id = $model1->customer_id;
             $receivedModel->status = 1;
             if ($receivedModel->save()) {
                 $balance = $receivedModel->amount * 1.0 - $model1->total_amount * 1.0;
                 if ($balance <= 0) {
                     $model1->balance = $balance * -1.0;
                 } else {
                     $model1->balance = 0;
                     $creditModel = new CustomersCredit();
                     $creditModel->amount = $balance;
                     $creditModel->credited_from = $model1->id;
                     $creditModel->customer_id = $model1->customer_id;
                     $creditModel->credited_date = $model1->issue_date;
                     $creditModel->save();
                 }
                 //SalesInvoices::model()->findByPk($model1->id)->delete();
                 $model1->save();
                 //Yii::app()->AutomatedExecution->AutomatedExecutionHandler();
             }
         }
         $this->redirect(array('AutomatedTransaction', 'id' => $model1->id, 'mode' => 'create'));
     }
     $this->render('create', array('model1' => $model1, 'model2' => $model2, 'receivedModel' => $receivedModel));
 }