<?php

class InventoryController extends Controller
{

    public function accessRules()
    {

        return array(
            array(
                'allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'error', 'logout'),
                'users' => array('*'),
            ),
            array(
                'allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array(
                    'Index',
                    'Service',
                    'Create',
                    'GetList',
                    'CreateService',
                    'GetServiceList',
                    'Save',
                    'SaveService',
                    'SaveEquipment',
                    'UploadInventoryImage',
                    'DeleteImage',
                    'CheckExistance',
                    'History',
                    'GetHistory',
                    'StockHelper',
                    'PrintSalesPriceListPDF',
                    'DeleteInvItem',
                    'purchaseOrderDetails',
                    'GetDetails',
                    'GetTabDetails',
                    'AddSerialNo',
                    'FetchSerialNoItems',
                    'SaveSerialNo',
                    'RemoveSerialNo',
                    'FetchRemoveSerialNoItems',
                    'SaveRemoveSerialNo',
                    'AddBatchNo',
                    'FetchBatchItems',
                    'SaveAddBatchNo',
                    'SaveRemoveBatchNo',
                    'AddBatchSplitDetails',
                    'editserialno',
                    'updateserialno',
                    'CreateService',
                    'GetRawMaterialList',
                    'RawMaterial',
                    'BatchSplit',
                    'GetProductBatchNo',
                    'fetchBatchNoItems',
                    'saveBatchSplit',
                    'CheckProductInQC',
                    'GetSearchServiceItems',
                    'LoadsalepurchaseHistory',
                    'LoadsalepurchaseHistory',
                    'GetAvaibaleQty',
                    'GetSerialNoList',
                    'ChangeSerialNo',
                    'GetLocationDetails',
                    'GetdemoPartnumber',
                    'GetMachineOnly',
                    'Memo',
                    'GetMemoList',
                    'SaveMemo',
                    'Dummy',
                    'GetDummyList',
                    'SaveDummy',
                    'GetPurchaseHistoryList',
                    'ApproveInventoryItem',
                    'ViewExpiryList',
                    'AllocateMaterials',
                    'SaveAllocateMaterial',
                    'BlockInventoryItem',
                    'DeleteUOMItem',
                    'PrintInventoryBarcode',
                    'GetWarehouseProduct',
                    'selectBarcodeHeading',
                    'Equipment',
                    'GetEquipmentList',
                    'UploadInventoryList',
                    'DownloadInventoryListFormat',
                    'SaveUploadInventoryList',
                    'DownloadErrorCsv',
                    'Uploadinv',
                    'UploadInventory',
                    'DownloadSampleCsv',
                    'DownloadSampleCsv',
                    'SaveInventoryUploadCsv',
                    'UploadInventoryCsv',
                    'DownloadErrorCsv',
                    'GetConsumablesList',
                    'GetComponentsList',
                    'GetOthersList',
                    'ComponentsIndex',
                    'ConsumablesIndex',
                    'OthersIndex'
                ),
                'expression' => '$user->isMember()',
            ),
            array(
                'deny', // deny all users$model
                'users' => array('*'),
            ),
        );
    }

    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function actionIndex()
    {

        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['inventory_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['stock_view']) &&
                Yii::app()->user->havePermissionOn['inventory_menu_view'] &&
                Yii::app()->user->havePermissionOn['stock_view']
            )
        ) {
            $this->render('service_index');
        } else {
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end(); // Prevent further execution
        }
    }
    public function actionComponentsIndex()
    {

        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['inventory_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['stock_view']) &&
                Yii::app()->user->havePermissionOn['inventory_menu_view'] &&
                Yii::app()->user->havePermissionOn['stock_view']
            )
        ) {
            $this->render('components_index');
        } else {
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end(); // Prevent further execution
        }
    }
    public function actionConsumablesIndex()
    {

        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['inventory_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['stock_view']) &&
                Yii::app()->user->havePermissionOn['inventory_menu_view'] &&
                Yii::app()->user->havePermissionOn['stock_view']
            )
        ) {
            $this->render('consumables_index');
        } else {
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end(); // Prevent further execution
        }
    }
    public function actionOthersIndex()
    {

        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['inventory_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['stock_view']) &&
                Yii::app()->user->havePermissionOn['inventory_menu_view'] &&
                Yii::app()->user->havePermissionOn['stock_view']
            )
        ) {
            $this->render('others_index');
        } else {
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end(); // Prevent further execution
        }
    }

    public function actionService()
    {
        $this->render('service_index');
    }

    public function actionEquipment()
    {
        $this->render('equipment_index');
    }

    public function actionGetList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $display_type = $_POST['display_type'];
        $brand_id = $_POST['brand_id'];
        //$approved = $_POST['approved'];
        $warehouse_id = (int) $_POST['warehouse_id'];
        $item_type = (int) $_POST['item_type'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'product_id',
            1 => 'part_number',
            2 => 'description',
            3 => 'bar_code',
            4 => 'brand',
            5 => 'quantity',
            6 => 'rate',
            7 => 'selling_price_1',
            8 => 'isActive',
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;

        //$condition = 'inventory_item_type=1';
         $condition = '1=1';
        // $condition = 'inventory_item_type IN (1,2)';

        // /* if($approved=='N'){
        //   $condition.=' AND isActive="N"';
        //   }
        //   else{
        //   $condition.=' AND isActive="Y"';
        //   } */

        // if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
        //     $searchString = trim($_POST['search']['value']);
        //     $condition = " (product_id LIKE '%" . $searchString . "%' OR part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' OR bar_code LIKE '%" . $searchString . "%' OR brand LIKE '%" . $searchString . "%') ";
        // }

        // if ((int) $brand_id > 0)
        //     $condition .= ' AND brand_id = ' . (int) $brand_id;
        // $qtycondition = '';
        // if ($display_type == 1) {
        //     $qtycondition = ' WHERE quantity >0 ';
        // }
        // if ((int) $warehouse_id > 0) {
        //     $condition .= ' AND (warehouse_id = ' . (int) $warehouse_id . ' OR warehouse_id=0)';
        // }
        // if ((int) $item_type > 0) {
        //     $condition .= ' AND (inventory_item_type = ' . (int) $item_type . ')';
        // }
        // $query = 'SELECT * FROM (SELECT product_id,generic_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
        //     FROM view_warehousewise_stock
        //     WHERE ' . $condition . '
        //     GROUP BY product_id
        //     )A' . $qtycondition . '
        //     ORDER BY ' . $orderBy . ' LIMIT ' . $limit . ' OFFSET ' . $offset . ' ';
        // // echo $query;
        // $countquery = 'SELECT COUNT(product_id) FROM (SELECT product_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
        //     FROM view_warehousewise_stock
        //     WHERE ' . $condition . '
        //     GROUP BY product_id
        //     )A' . $qtycondition . '
        //     ORDER BY ' . $orderBy;

        // //$query = 'SELECT * FROM view_all_stock_items WHERE '.$condition.' ORDER BY '.$orderBy.' LIMIT '.$limit.' OFFSET '.$offset.' ';
        // //echo $query;
        // $count = Yii::app()->db->createCommand($countquery)->queryScalar();
        // //$count = Yii::app()->db->createCommand('SELECT COUNT(id) FROM view_all_stock_items WHERE '.$condition.' ')->queryScalar();
        // $model = Yii::app()->db->createCommand($query)->queryAll();

        $count = $model->count(array('condition'=>$condition));
          $model = $model->findAll(array('condition'=>$condition)); 



        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        $gross_weight = 0;
        $type_array = array('1' => "stock item", '2' => "service item", '3' => "raw material", '4' => "Equipments");
        foreach ($model as $row) {
            $arr_product_UOM = new UnitOfMeasurement();

            $arr_product_UOM = $arr_product_UOM->find(array('condition' => 'product_id=' . $row['product_id'], 'limit' => 4));
            //$quantity = number_format($availble_qty,2);
            $unit = $arr_product_UOM->name;

            // $modelMasGeneric = new MasGeneric();
            // $modelMasGeneric = $modelMasGeneric->findByPk($row['generic_id']);
            // $generic_name = $modelMasGeneric->generic_name;

            //$rowData[]=array($row['id'],$m, $part_no, $row['generic_name'], '<span class="info-btn" title="'.$row['description'].'">'.$row['description'].'</span> ', $row['brand'], (float) $row['quantity'], $row['unit'],$row['have_serial_no'],$row['machine_type'],$row['isActive'],$purchase_from,(int) Yii::app()->user->havePermissionOn["inv_detail_pohis_view"]);
            $rowData[] = array(
                $m,
                $row['part_number'],
                '<span class="info-btn" title="' . $row['description'] . '">' . $row['description'] . '</span> ',
                $generic_name,
                $row['brand'],
                $row['quantity'] . " " . $unit,
                number_format($row['rate'], 2),
                $row['item_type'],
                $row['product_id'],
                $row['isActive'],
            );
            $m++;
        }

        $data['data'] = $rowData;
        $data['q'] = $query;
        echo json_encode($data);
    }
    public function actionGetComponentsList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $display_type = $_POST['display_type'];
        $brand_id = $_POST['brand_id'];
        //$approved = $_POST['approved'];
        $warehouse_id = (int) $_POST['warehouse_id'];
        $item_type = (int) $_POST['item_type'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'product_id',
            1 => 'part_number',
            2 => 'description',
            3 => 'bar_code',
            4 => 'brand',
            5 => 'quantity',
            6 => 'rate',
            7 => 'selling_price_1',
            8 => 'isActive',
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;

        $condition = 'inventory_item_type = 3';
        // var_dump($condition) ;

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = " (product_id LIKE '%" . $searchString . "%' OR part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' OR bar_code LIKE '%" . $searchString . "%' OR brand LIKE '%" . $searchString . "%') ";
        }

        if ((int) $brand_id > 0)
            $condition .= ' AND brand_id = ' . (int) $brand_id;
        $qtycondition = '';
        if ($display_type == 1) {
            $qtycondition = ' WHERE quantity >0 ';
        }
        if ((int) $warehouse_id > 0) {
            $condition .= ' AND (warehouse_id = ' . (int) $warehouse_id . ' OR warehouse_id=0)';
        }
        if ((int) $item_type > 0) {
            $condition .= ' AND (inventory_item_type = ' . (int) $item_type . ')';
        }
        $query = 'SELECT * FROM (SELECT product_id,generic_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
            FROM view_warehousewise_stock
            WHERE ' . $condition . '
            GROUP BY product_id
            )A' . $qtycondition . '
            ORDER BY ' . $orderBy . ' LIMIT ' . $limit . ' OFFSET ' . $offset . ' ';
        // echo $query;
        $countquery = 'SELECT COUNT(product_id) FROM (SELECT product_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
            FROM view_warehousewise_stock
            WHERE ' . $condition . '
            GROUP BY product_id
            )A' . $qtycondition . '
            ORDER BY ' . $orderBy;

        //$query = 'SELECT * FROM view_all_stock_items WHERE '.$condition.' ORDER BY '.$orderBy.' LIMIT '.$limit.' OFFSET '.$offset.' ';
        //echo $query;
        $count = Yii::app()->db->createCommand($countquery)->queryScalar();
        //$count = Yii::app()->db->createCommand('SELECT COUNT(id) FROM view_all_stock_items WHERE '.$condition.' ')->queryScalar();
        $model = Yii::app()->db->createCommand($query)->queryAll();

        /* $count = $model->count(array('condition'=>$condition));
          $model = $model->findAll(array('condition'=>$condition)); */



        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        $gross_weight = 0;
        $type_array = array('1' => "stock item", '2' => "service item", '3' => "raw material", '4' => "Equipments");
        foreach ($model as $row) {
            $arr_product_UOM = new UnitOfMeasurement();

            $arr_product_UOM = $arr_product_UOM->find(array('condition' => 'product_id=' . $row['product_id'], 'limit' => 4));
            //$quantity = number_format($availble_qty,2);
            $unit = $arr_product_UOM->name;

            $modelMasGeneric = new MasGeneric();
            $modelMasGeneric = $modelMasGeneric->findByPk($row['generic_id']);
            $generic_name = $modelMasGeneric->generic_name;

            //$rowData[]=array($row['id'],$m, $part_no, $row['generic_name'], '<span class="info-btn" title="'.$row['description'].'">'.$row['description'].'</span> ', $row['brand'], (float) $row['quantity'], $row['unit'],$row['have_serial_no'],$row['machine_type'],$row['isActive'],$purchase_from,(int) Yii::app()->user->havePermissionOn["inv_detail_pohis_view"]);
            $rowData[] = array(
                $m,
                $row['part_number'],
                '<span class="info-btn" title="' . $row['description'] . '">' . $row['description'] . '</span> ',
                $generic_name,
                $row['brand'],
                $row['quantity'] . " " . $unit,
                number_format($row['rate'], 2),
                $row['item_type'],
                $row['product_id'],
                $row['isActive'],
            );
            $m++;
        }

        $data['data'] = $rowData;
        $data['q'] = $query;
        echo json_encode($data);
    }
    public function actionGetConsumablesList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $display_type = $_POST['display_type'];
        $brand_id = $_POST['brand_id'];
        //$approved = $_POST['approved'];
        $warehouse_id = (int) $_POST['warehouse_id'];
        $item_type = (int) $_POST['item_type'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'product_id',
            1 => 'part_number',
            2 => 'description',
            3 => 'bar_code',
            4 => 'brand',
            5 => 'quantity',
            6 => 'rate',
            7 => 'selling_price_1',
            8 => 'isActive',
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;

        $condition = 'inventory_item_type = 4';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = " (product_id LIKE '%" . $searchString . "%' OR part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' OR bar_code LIKE '%" . $searchString . "%' OR brand LIKE '%" . $searchString . "%') ";
        }

        if ((int) $brand_id > 0)
            $condition .= ' AND brand_id = ' . (int) $brand_id;
        $qtycondition = '';
        if ($display_type == 1) {
            $qtycondition = ' WHERE quantity >0 ';
        }
        if ((int) $warehouse_id > 0) {
            $condition .= ' AND (warehouse_id = ' . (int) $warehouse_id . ' OR warehouse_id=0)';
        }
        if ((int) $item_type > 0) {
            $condition .= ' AND (inventory_item_type = ' . (int) $item_type . ')';
        }
        $query = 'SELECT * FROM (SELECT product_id,generic_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
            FROM view_warehousewise_stock
            WHERE ' . $condition . '
            GROUP BY product_id
            )A' . $qtycondition . '
            ORDER BY ' . $orderBy . ' LIMIT ' . $limit . ' OFFSET ' . $offset . ' ';
        // echo $query;
        $countquery = 'SELECT COUNT(product_id) FROM (SELECT product_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
            FROM view_warehousewise_stock
            WHERE ' . $condition . '
            GROUP BY product_id
            )A' . $qtycondition . '
            ORDER BY ' . $orderBy;

        //$query = 'SELECT * FROM view_all_stock_items WHERE '.$condition.' ORDER BY '.$orderBy.' LIMIT '.$limit.' OFFSET '.$offset.' ';
        //echo $query;
        $count = Yii::app()->db->createCommand($countquery)->queryScalar();
        //$count = Yii::app()->db->createCommand('SELECT COUNT(id) FROM view_all_stock_items WHERE '.$condition.' ')->queryScalar();
        $model = Yii::app()->db->createCommand($query)->queryAll();

        /* $count = $model->count(array('condition'=>$condition));
          $model = $model->findAll(array('condition'=>$condition)); */



        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        $gross_weight = 0;
        $type_array = array('1' => "stock item", '2' => "service item", '3' => "raw material", '4' => "Equipments");
        foreach ($model as $row) {
            $arr_product_UOM = new UnitOfMeasurement();

            $arr_product_UOM = $arr_product_UOM->find(array('condition' => 'product_id=' . $row['product_id'], 'limit' => 4));
            //$quantity = number_format($availble_qty,2);
            $unit = $arr_product_UOM->name;

            $modelMasGeneric = new MasGeneric();
            $modelMasGeneric = $modelMasGeneric->findByPk($row['generic_id']);
            $generic_name = $modelMasGeneric->generic_name;

            //$rowData[]=array($row['id'],$m, $part_no, $row['generic_name'], '<span class="info-btn" title="'.$row['description'].'">'.$row['description'].'</span> ', $row['brand'], (float) $row['quantity'], $row['unit'],$row['have_serial_no'],$row['machine_type'],$row['isActive'],$purchase_from,(int) Yii::app()->user->havePermissionOn["inv_detail_pohis_view"]);
            $rowData[] = array(
                $m,
                $row['part_number'],
                '<span class="info-btn" title="' . $row['description'] . '">' . $row['description'] . '</span> ',
                $generic_name,
                $row['brand'],
                $row['quantity'] . " " . $unit,
                number_format($row['rate'], 2),
                $row['item_type'],
                $row['product_id'],
                $row['isActive'],
            );
            $m++;
        }

        $data['data'] = $rowData;
        $data['q'] = $query;
        echo json_encode($data);
    }
    public function actionGetOthersList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $display_type = $_POST['display_type'];
        $brand_id = $_POST['brand_id'];
        //$approved = $_POST['approved'];
        $warehouse_id = (int) $_POST['warehouse_id'];
        $item_type = (int) $_POST['item_type'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'product_id',
            1 => 'part_number',
            2 => 'description',
            3 => 'bar_code',
            4 => 'brand',
            5 => 'quantity',
            6 => 'rate',
            7 => 'selling_price_1',
            8 => 'isActive',
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;

        $condition = 'inventory_item_type = 5';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = " (product_id LIKE '%" . $searchString . "%' OR part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' OR bar_code LIKE '%" . $searchString . "%' OR brand LIKE '%" . $searchString . "%') ";
        }

        if ((int) $brand_id > 0)
            $condition .= ' AND brand_id = ' . (int) $brand_id;
        $qtycondition = '';
        if ($display_type == 1) {
            $qtycondition = ' WHERE quantity >0 ';
        }
        if ((int) $warehouse_id > 0) {
            $condition .= ' AND (warehouse_id = ' . (int) $warehouse_id . ' OR warehouse_id=0)';
        }
        if ((int) $item_type > 0) {
            $condition .= ' AND (inventory_item_type = ' . (int) $item_type . ')';
        }
        $query = 'SELECT * FROM (SELECT product_id,generic_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
            FROM view_warehousewise_stock
            WHERE ' . $condition . '
            GROUP BY product_id
            )A' . $qtycondition . '
            ORDER BY ' . $orderBy . ' LIMIT ' . $limit . ' OFFSET ' . $offset . ' ';
        // echo $query;
        $countquery = 'SELECT COUNT(product_id) FROM (SELECT product_id,part_number,description,bar_code,brand_id,brand,SUM(quantity) AS quantity,isActive,inventory_item_type,rate,selling_price_1,item_type
            FROM view_warehousewise_stock
            WHERE ' . $condition . '
            GROUP BY product_id
            )A' . $qtycondition . '
            ORDER BY ' . $orderBy;

        //$query = 'SELECT * FROM view_all_stock_items WHERE '.$condition.' ORDER BY '.$orderBy.' LIMIT '.$limit.' OFFSET '.$offset.' ';
        //echo $query;
        $count = Yii::app()->db->createCommand($countquery)->queryScalar();
        //$count = Yii::app()->db->createCommand('SELECT COUNT(id) FROM view_all_stock_items WHERE '.$condition.' ')->queryScalar();
        $model = Yii::app()->db->createCommand($query)->queryAll();

        /* $count = $model->count(array('condition'=>$condition));
          $model = $model->findAll(array('condition'=>$condition)); */



        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        $gross_weight = 0;
        $type_array = array('1' => "stock item", '2' => "service item", '3' => "raw material", '4' => "Equipments");
        foreach ($model as $row) {
            $arr_product_UOM = new UnitOfMeasurement();

            $arr_product_UOM = $arr_product_UOM->find(array('condition' => 'product_id=' . $row['product_id'], 'limit' => 4));
            //$quantity = number_format($availble_qty,2);
            $unit = $arr_product_UOM->name;

            $modelMasGeneric = new MasGeneric();
            $modelMasGeneric = $modelMasGeneric->findByPk($row['generic_id']);
            $generic_name = $modelMasGeneric->generic_name;

            //$rowData[]=array($row['id'],$m, $part_no, $row['generic_name'], '<span class="info-btn" title="'.$row['description'].'">'.$row['description'].'</span> ', $row['brand'], (float) $row['quantity'], $row['unit'],$row['have_serial_no'],$row['machine_type'],$row['isActive'],$purchase_from,(int) Yii::app()->user->havePermissionOn["inv_detail_pohis_view"]);
            $rowData[] = array(
                $m,
                $row['part_number'],
                '<span class="info-btn" title="' . $row['description'] . '">' . $row['description'] . '</span> ',
                $generic_name,
                $row['brand'],
                $row['quantity'] . " " . $unit,
                number_format($row['rate'], 2),
                $row['item_type'],
                $row['product_id'],
                $row['isActive'],
            );
            $m++;
        }

        $data['data'] = $rowData;
        $data['q'] = $query;
        echo json_encode($data);
    }

    public function actionGetListOld()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $display_type = $_POST['display_type'];
        $brand_id = $_POST['brand_id'];
        $machine_type = $_POST['machine_type'];
        $approved = $_POST['approved'];
        $warehouse_id = (int) $_POST['warehouse_id'];

        //$machine_id = $_POST['machine_id'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'id',
            1 => 'part_number',
            2 => 'description',
            3 => 'capacity',
            4 => 'packing',
            5 => 'quantity',
            6 => 'quantity',
            7 => 'rate',
            8 => 'selling_price_1',
            9 => 'selling_price_2',
            10 => 'cbm',
            11 => 'weight',
            12 => 'id',
            13 => 'isActive',
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;

        $condition = 'type=1';

        if ($approved == 'N') {
            $condition .= ' AND isActive="N"';
        } else {
            $condition .= ' AND isActive="Y"';
        }

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = "type=1 AND (id LIKE '%" . $searchString . "%' OR part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' OR capacity LIKE '%" . $searchString . "%' OR oem_number LIKE '%" . $searchString . "%' OR brand LIKE '%" . $searchString . "%' OR unit LIKE '%" . $searchString . "%' OR generic_name LIKE '%" . $searchString . "%') ";
        }

        if ($brand_id > 0)
            $condition .= ' AND brand_id = ' . $brand_id;

        if ($display_type == 1) {
            $condition .= ' AND quantity >0';
        }
        /* if($warehouse_id>0){
          $condition .= ' AND ('.$warehouse_id. ' IN (item_warehouse) OR )';
          } */

        $query = 'SELECT * FROM view_all_stock_items WHERE ' . $condition . ' ORDER BY ' . $orderBy . ' LIMIT ' . $limit . ' OFFSET ' . $offset . ' ';
        //echo $query;
        $count = Yii::app()->db->createCommand('SELECT COUNT(id) FROM view_all_stock_items WHERE ' . $condition . ' ')->queryScalar();
        $model = Yii::app()->db->createCommand($query)->queryAll();

        /* $count = $model->count(array('condition'=>$condition));
          $model = $model->findAll(array('condition'=>$condition)); */



        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        $gross_weight = 0;
        foreach ($model as $row) {

            $storeModel = new store();
            $storeModel = $storeModel->findbyPk($row['id']);

            $second_unit_factor = $row['second_unit_factor'];
            if ((int) $second_unit_factor == 0) {
                $second_unit_factor = 1;
            }

            if ((int) $row['weight'] > 0) {
                $weight = $row['weight'];
            } else {
                $weight = 0;
            }

            $gross_weight = (($row['quantity'] / $second_unit_factor) * $weight);

            $part_no = $row['part_number'];
            $arr_price_list = SalesPriceGroup::model()->find(array('condition' => 'product_id=' . (int) $row['id']));
            $sales_price = $arr_price_list->sales_price;
            $sales_price1 = '';

            $modelMasInventoryWarehouse = new MasInventoryWarehouse();

            $damage_warehouse_id = $modelMasInventoryWarehouse->find(array('condition' => 'warehouse_code="DAM"'))->id;

            $SQL = "SELECT SUM(quantity * unit_factor) AS damage_quantity FROM erp_stock_ledger WHERE product_id=" . (int) $row['id'] . ' AND warehouse_id=' . $damage_warehouse_id;
            //echo $SQL;
            $total_damage_qty = (float) Yii::app()->db->createCommand($SQL)->queryScalar();

            $total_qty = $row['quantity'] - $total_damage_qty;

            // -----------------------------
            //  $availble_qty = Yii::app()->db->createCommand('SELECT IFNULL(SUM(quantity*unit_factor),0) as availble_qty FROM `erp_stock_ledger` WHERE product_id='.$row['id'].' AND warehouse_id='.(int)$warehouse_id)->queryScalar();


            $sql_data = 'SELECT IFNULL(SUM(quantity*unit_factor),0) as availble_qty FROM `erp_stock_ledger` WHERE product_id=' . $row['id'] . '';
            if ($warehouse_id > 0) {
                //$warehouse_id = (int)Yii::app()->user->getState('user_warehouse_id');
                $sql_data .= ' AND warehouse_id=' . $warehouse_id;
            }


            //echo $sql_data;
            $availble_qty = Yii::app()->db->createCommand($sql_data)->queryScalar();

            // -----------------------------


            $arr_product_UOM = new UnitOfMeasurement();

            $arr_product_UOM = $arr_product_UOM->find(array('condition' => 'product_id=' . $row['id'], 'limit' => 4));
            $quantity = number_format($availble_qty, 2);
            $unit = $arr_product_UOM->name;

            //$rowData[]=array($row['id'],$m, $part_no, $row['generic_name'], '<span class="info-btn" title="'.$row['description'].'">'.$row['description'].'</span> ', $row['brand'], (float) $row['quantity'], $row['unit'],$row['have_serial_no'],$row['machine_type'],$row['isActive'],$purchase_from,(int) Yii::app()->user->havePermissionOn["inv_detail_pohis_view"]);
            $rowData[] = array(
                $m,
                $part_no,
                '<span class="info-btn" title="' . $row['description'] . '">' . $row['description'] . '</span> ',
                $storeModel->bar_code,
                $row['brand'],
                $quantity . " " . $unit,
                $row['id'],
                $row['isActive']
            );
            $m++;
        }

        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionGetServiceList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'id',
            1 => 'part_number', 
            2 => 'description',
            3 => 'notes',
            4 => 'id',
           
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.isActive="Y" AND inventory_item_type=2';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = "inventory_item_type=2 AND ( part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' )";
        }

        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        foreach ($model as $m => $row) {

            $rowData[] = array($m + 1, $row['part_number'], $row['description'], $row['notes'], $row['id'],'');
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionGetEquipmentList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'part_number',
            1 => 'generic_name',
            2 => 'description',
            3 => 'brand_class_id',
            4 => 'default_warehouse_id',
            5 => 'inventory_item_type'
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.isActive="Y" AND inventory_item_type=4';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = "inventory_item_type=2 AND ( part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' )";
        }

        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        foreach ($model as $m => $row) {

            $rowData[] = array($m + 1, $row['part_number'], $row['description'], $row->genericdetails->generic_name, $row['id'], $row['default_service_item']);
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionCreate()
    {
        $edit_flag = 0;
        $model = new Store();
        $id = (int) Yii::app()->request->getParam('id');
        $view = Yii::app()->request->getParam('view');
        $approved = Yii::app()->request->getParam('approved');
        if ($id > 0) {
            $model = $model->findByPk($id);
            //$mod_his=StockLedger::model()->findAll(array('condition'=>'product_id='.(int)$id.' AND transaction_from!="OPENING_STOCK"'));
            $mod_his = StockLedger::model()->findAll(array('condition' => 'product_id=' . (int) $id . ' '));
            //echo '<pre>';print_r($mod_his);
            if (!empty($mod_his)) {
                $edit_flag = 1;
            }
        }



        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render($view, array('model' => $model, 'approved' => $approved, 'edit_flag' => $edit_flag), false, false);
    }

    /* public function ChanageDB($database = MasCompany::DB_ACE){
      Yii::app()->db->setActive(false);
      Yii::app()->db->connectionString = 'mysql:host=localhost;dbname=' . $database;
      Yii::app()->db->tablePrefix = 'erp_';
      Yii::app()->db->setActive(true);
      } */

    public function actionSave()
    {
        $model = new Store();
        $scenario = '';
        $other_error = [];
        if ((int) $_POST['Store']['id'] > 0) {

            $id = $_POST['Store']['id'];

            $model = $model->findByPk($id);
            $model->updated_by = Yii::app()->user->id;
            $model->updated_date_time = date('Y-m-d h:i:s');
            $scenario = 'update';
            $audit_type = 'UPDATED';
        } else {
            $scenario = 'add';
            $audit_type = 'CREATED';
            $model->created_by = Yii::app()->user->id;
            $model->created_date_time = date('Y-m-d H:i:s');
            $model->scenario = 'add';
        }


        
        $model->attributes = $_POST['Store'];
        $model->part_number = $_POST['Store']['part_number'];
        $model->notes = $_POST['Store']['notes'];
        $model->inventory_item_type = 2;//$_POST['Store']['inventory_item_type'];


         

        $valid = $model->validate();
         
        
        
         
        /* echo $uom_secondary_flag;
          echo '<pre>';
          print_r($arr_second_unit);exit; */

        if ($valid) {
            $model->save();  
            $jsonData['status'] = 'success';
            echo CJSON::encode($jsonData);
 
            // end audit log


            
        } else {
            $error2 = array();
            $error3 = array();
            $error4 = array();
            $error5 = array();
            $error1 = json_decode(CActiveForm::validate($model, '', false), true);
            
            $error = CJSON::encode(array_merge_recursive($error1, $error2, $error3, $error4, $error5));
            if ($error != '[]')
                echo $error;
        }
    }

    /* public function actionSave()
      {
      $model = new Store();
      $part_number_new='';
      $scenario='';
      if ( (int) $_POST['Store']['id'] > 0){

      $id = $_POST['Store']['id'];

      $model=$model->findByPk($id);
      $model->updated_by = Yii::app()->user->id;
      $model->updated_date_time = date('Y-m-d h:i:s');
      $edit_flag=1;
      $scenario='update';
      $audit_type = 'UPDATED';
      }else{
      $scenario='add';
      $audit_type = 'CREATED';
      $model->created_by = Yii::app()->user->id;
      $model->created_date_time = date('Y-m-d h:i:s');
      $model->scenario = 'add';
      $edit_flag=0;
      $model_max_partnumber= Store::model()->find(array('select' => 'max(id) as id','condition'=>'inventory_item_type="1" and brand_class_id="'.$_POST['Store']['brand_class_id'].'"'));
      if($model_max_partnumber->id!=''){
      $model_existing_part_no = Store::model()->findByPk($model_max_partnumber->id);
      $existing_part_no=  explode('-', $model_existing_part_no->part_number);
      $part_number_new=$existing_part_no[2]+1;
      if($part_number_new<=99999){
      $part_number_new= str_pad($part_number_new,5, "0", STR_PAD_LEFT);
      }
      }else{
      $part_number_new='00001';
      }
      $model_brand_class = ProductClass::model()->findByPk($_POST['Store']['brand_class_id']);
      $part_no='';
      $machine_type=$_POST['Store']['machine_type'];
      if($model_brand_class->id>0){
      $value_machine_type = ($machine_type=='M')? '02': '04';
      $brand_class_auto_generated_no=0;
      if(count($model_brand_class->auto_generated_no)==1){
      $brand_class_auto_generated_no= str_pad($model_brand_class->auto_generated_no,2, "0", STR_PAD_LEFT);
      } else {
      $brand_class_auto_generated_no=$model_brand_class->auto_generated_no;
      }
      $part_no=$brand_class_auto_generated_no.'-'.$value_machine_type.'-'.$part_number_new;
      }

      }
      $model->attributes=$_POST['Store'];
      $model->machine_id = $_POST['Store']['machine_id'];
      $model->html_description = $_POST['html_description'];
      $model->service_product_type ='NL';
      if( (float) $_POST['Store']['rate'] > 0 )
      $model->rate = $_POST['Store']['rate'];

      if(!$model->id>0){
      $model->part_number =$part_no;
      $part_number      = explode('-',$model->part_number);
      $mc_spare=$part_number[1];
      $value_machine_type = ($mc_spare=='02')? '01': '03';
      $model->hiring_part_number =$part_number[0].'-'.$value_machine_type.'-'.$part_number[2];
      }
      if($model->hiring_part_number==''){
      $part_number      = explode('-',$model->part_number);
      $mc_spare=$part_number[1];
      $value_machine_type = ($mc_spare=='01')? '02': '04';
      $model->hiring_part_number =$part_number[0].'-'.$value_machine_type.'-'.$part_number[2];
      }
      if($_POST['Store']['bar_code']==''){
      $model->bar_code=$model->part_number;
      }
      if($_POST['Store']['oem_number']==''){
      $model->oem_number=$model->part_number;
      }
      if(is_array($_POST['UnitOfMeasurement'])){
      foreach ($_POST['UnitOfMeasurement'] as $i => $each){
      if($each['name'] != ''){
      $UOM[$i] = new UnitOfMeasurement;
      if((int) $each['id'] > 0)
      $UOM[$i] = $UOM[$i]->findBypk($each['id']);
      $UOM[$i]->attributes = $each;
      $UOM[$i]->product_id = 0;
      if($each['isBase'] == "Y"){
      $UOM[$i]->name =  Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
      }
      $UOM[$i]->base_unit  = $_POST['Store']['unit_id'];
      $UOM[$i]->created_by = Yii::app()->user->id;
      $UOM[$i]->created_date_time = date('Y-m-d H:i:s');
      $valid = $UOM[$i]->validate() && $valid;
      }
      }
      }

      if ( $model->validate() ){
      $jsonData['status'] = 'success';
      echo CJSON::encode($jsonData);
      $model->save();

      // inserting to audit log
      switch ($_POST['Store']['inventory_item_type']) {
      case '1':
      AuditLog::saveAuditLogs(
      'FINISHED_PRODUCTS',
      Yii::app()->user->id,
      $audit_type,
      " with FP No: - {$model->id} & Part No: - {$_POST['Store']['part_number']}  "
      );
      break;
      case '3':
      AuditLog::saveAuditLogs(
      'RAW_MATERIAL',
      Yii::app()->user->id,
      $audit_type,
      " with RM No: - {$model->id} & Part No: - {$_POST['Store']['part_number']}  "
      );
      break;
      default:
      # code...
      break;
      }

      // end audit log


      if($scenario=='add'){
      $model_mail_setting=Notification::model()->find(array('condition' => 'event_id="19"'));
      Yii::import('application.controllers.front.MasternotificationController');
      if($model_mail_setting->mail_required=='Y'){
      // MasternotificationController::sendmail(19,$model->id);
      }
      if($model_mail_setting->notification_required=='Y'){
      // MasternotificationController::sendnotification(19,$model->id);
      }
      if($model_mail_setting->sms_required=='Y'){
      // MasternotificationController::sendsms(19,$model->id);
      }
      }
      if(!empty($UOM)){
      foreach($UOM as $each){
      $each->product_id = $model->id;
      $each->save();
      }
      }
      if($edit_flag==0){
      $default = new UnitOfMeasurement;
      $default->product_id = $model->id;
      $default->base_unit  = $_POST['Store']['unit_id'];
      $default->name =  Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
      $default->factor = 1;
      $default->isBase = "Y";
      $default->created_by = Yii::app()->user->id;
      $default->created_date_time = date('Y-m-d H:i:s');
      $default->save(false);
      }
      if($edit_flag==0)
      {
      $this->ChanageDB(MasCompany::DB_ARK);
      $arkProduct = new Store;
      $arkProduct->id=$model->id;
      $arkProduct->attributes = $model->attributes;
      $arkProduct->save(false);
      $this->ChanageDB(MasCompany::DB_ACE);
      }
      else {
      $this->ChanageDB(MasCompany::DB_ARK);
      $arkProduct = Store::model()->findByPk($model->id);
      $arkProduct->attributes = $model->attributes;
      $arkProduct->save(false);
      $this->ChanageDB(MasCompany::DB_ACE);
      }
      // ACE ARK
      $this->ChanageDB(MasCompany::DB_ARK);
      $UOM=array();
      if(is_array($_POST['UnitOfMeasurement'])){
      foreach ($_POST['UnitOfMeasurement'] as $i => $each){
      if($each['name'] != ''){
      $UOM[$i] = new UnitOfMeasurement;
      if((int) $each['id'] > 0)
      $UOM[$i] = $UOM[$i]->findBypk($each['id']);
      $UOM[$i]->attributes = $each;
      $UOM[$i]->product_id = 0;
      if($each['isBase'] == "Y"){
      $UOM[$i]->name =  Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
      }
      $UOM[$i]->base_unit  = $_POST['Store']['unit_id'];
      $UOM[$i]->created_by = Yii::app()->user->id;
      $UOM[$i]->created_date_time = date('Y-m-d H:i:s');
      }
      }
      }
      if(!empty($UOM)){
      foreach($UOM as $each){
      $each->product_id = $model->id;
      $each->save();
      }
      }
      if($edit_flag==0){
      $default = new UnitOfMeasurement;
      $default->product_id = $model->id;
      $default->base_unit  = $_POST['Store']['unit_id'];
      $default->name =  Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
      $default->factor = 1;
      $default->isBase = "Y";
      $default->created_by = Yii::app()->user->id;
      $default->created_date_time = date('Y-m-d H:i:s');
      $default->save(false);
      }
      $this->ChanageDB(MasCompany::DB_ACE);

      }else{
      $error2 = array();
      $error1 = json_decode(CActiveForm::validate($model, '', false), true);
      if($UOM[0]->name > 0)
      $error2 = json_decode(CActiveForm::validateTabular($UOM, '', false), true);
      $error = CJSON::encode(array_merge_recursive($error1, $error2));
      if ($error != '[]')
      echo $error;
      }
      } */

    public function actionUploadInventoryImage($folder = null, $filename = null)
    {
        Yii::import("ext.EAjaxUpload.qqFileUploader");
        $field_id = "";
        if (isset($_GET['field_id'])) {
            $field_id = Yii::app()->request->getParam('field_id');
        }
        if (empty($filename)) {
            $filename = 'inventory_' . date('YmdHis');
        }

        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
        // make the directory to store the pic:
        if (!is_dir($folder)) {
            mkdir($folder, 0777, TRUE);
        }
        $allowedExtensions = array("jpg", "jpeg", "gif", "png"); //array("jpg","jpeg","gif","exe","mov" and etc...
        $sizeLimit = 2 * 1024 * 1024; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder, FALSE, $filename);
        //$result = $uploader->handleUpload($folder);
        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
        $result['field_id'] = $field_id;
        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        $fileName = $result['filename']; //GETTING FILE NAME
        $imagename = Yii::app()->basePath . '/../uploads/inventoryimages/' . $fileName;
        $imagename_thumb = Yii::app()->basePath . '/../uploads/inventoryimages/thumbs/' . $fileName;
        Yii::import("ext.EPhpThumb.EPhpThumb");
        $thumb = new EPhpThumb();
        $thumb->init(); //this is needed
        //chain functions
        $thumb->create($imagename)->resize(120, 120)->save($imagename_thumb);
        echo $return; // it's array
    }

    public function actionDeleteImage()
    {
        $id = (int) $_POST['id'];
        $model = Store::model()->findByPk($id);
        if ($model->item_image != '') {
            $path = Yii::getPathOfAlias('webroot') . "/uploads/inventoryimages/" . $model->item_image;
            if (file_exists($path)) {
                unlink($path);
            }
        }

        $model->item_image = '';
        $model->save(false);
        echo "success";
    }

    public function actionCheckExistance()
    {
        $terms = $_POST['item'];
        $term = ltrim($terms);
        $status = array();
        if ($term != '') {
            $store = Store::model()->findAll(array('condition' => 'part_number = "' . $term . '"'));
            if (!empty($store)) {
                $status['status'] = 'exist';
            } else {
                $status['status'] = 'not_exist';
            }
        }
        echo CJSON::encode($status);
    }

    public function actionStockHelper()
    {
        $product_id = (int) $_POST['id'];
        $this->renderPartial('stock_helper', array('id' => $product_id), false, true);
    }

    public function actionPrintSalesPriceListPDF()
    {
        $model = new Store();
        $id = (int) Yii::app()->request->getParam('id');
        if ($id > 0)
            $model = new Store();

        $mpdf = Yii::app()->ePdf->mpdf('', 'A4');
        $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/pdf_style.css');
        $mpdf->WriteHTML($stylesheet, 1);
        $mpdf->WriteHTML($this->renderPartial('application.views.front.pdf.inventory_price_list_individual', array('model' => $model, 'id' => $id, 'title' => $title), true));
        $mpdf->Output("PriceList.pdf", 'I');
    }

    public function actionpurchaseOrderDetails()
    {
        $product_id = (int) $_POST['id'];
        $this->renderPartial('purchase_order_helper', array('id' => $product_id), false, true);
    }

    public function actionGetDetails()
    {
        $product_id = (int) Yii::app()->request->getParam('product_id');
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->renderPartial('get_details', array('product_id' => $product_id), false, true);
    }

    public function actionGetTabDetails()
    {
        $id = (int) Yii::app()->request->getParam('id');
        $product_id = (int) Yii::app()->request->getParam('product_id');
        if ($id == 1) {
            $this->renderPartial('get_stock_helper_details', array('product_id' => $product_id), false, true);
        }
        if ($id == 2) {
            $this->renderPartial('get_allocation_details', array('product_id' => $product_id), false, true);
        }
        if ($id == 3) {
            $this->renderPartial('get_po_details', array('product_id' => $product_id), false, true);
        }
        if ($id == 4) {
            $this->renderPartial('get_so_details', array('product_id' => $product_id), false, true);
        }
        if ($id == 5) {
            $this->renderPartial('get_price_helper', array('id' => $product_id), false, true);
        }
        if ($id == 6) {
            $this->renderPartial('get_so_history', array('product_id' => $product_id), false, true);
        }
        if ($id == 7) {
            $this->renderPartial('get_po_history', array('product_id' => $product_id), false, true);
        }
        if ($id == 8) {
            $this->renderPartial('get_quote_rate', array('product_id' => $product_id), false, true);
        }
    }

    public function actionAddSerialNo()
    {
        $pid = (int) Yii::app()->request->getParam('pid');
        $total_qty_ace = Yii::app()->request->getParam('total_qty_ace');
        $total_qty_ark = Yii::app()->request->getParam('total_qty_ark');
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('serial_no_form', array('pid' => $pid, 'total_qty_ace' => $total_qty_ace, 'total_qty_ark' => $total_qty_ark), false, false);
    }

    public function actionRemoveSerialNo()
    {
        $pid = (int) Yii::app()->request->getParam('pid');
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('serial_no_form_remove', array('pid' => $pid), false, false);
    }

    public function actionFetchSerialNoItems()
    {
        $prefix = $_POST['prefix'];
        $product_id = $_POST['product_id'];
        $startfrom = $_POST['startfrom'];
        $increment = $_POST['increment'];

        $condition = 't.product_id ="' . $product_id . '" AND quantity > 0 AND t.isActive="Y"';
        $stock_details = array(new StockLedger);
        $ark_stock_details = array(new StockLedger);
        if ((int) $product_id > 0) {
            $stock_details = StockLedger::model()->findAll(array('condition' => $condition, 'order' => 'id ASC'));

            //code added by mereena on 26/03/2020
            $this->ChanageDB(MasCompany::DB_ARK);
            $ark_stock_details = StockLedger::model()->findAll(array('condition' => $condition, 'order' => 'id ASC'));
            $this->ChanageDB(MasCompany::DB_ACE);
            //end
        }
        $data['table'] = '';
        $data['table'] .= '<table class="table table-hover table-bordered personal-task" id="serialno_items_table" style="margin-top : 10px;">
                            <tr>
                                <th>Sno</th>
                                <th>Serial No</th>
                            </tr>';
        if ($stock_details[0]->id > 0) {
            $sno = 1;
            $length = 0;
            foreach ($stock_details as $s => $rowitem) {
                $each_qty = $rowitem->quantity;
                if ($each_qty > 0) {
                    for ($s = 1; $s <= $each_qty; $s++) {
                        $data['table'] .= '<tr class="">
                                            <td>' . ($length + 1) . '</td>
                                            <td>' . CHtml::activeTextfield($rowitem, "[" . $length . "]serial_no", array('class' => 'form-control addserialno', 'onkeyup' => '', 'onkeypress' => '', 'value' => $prefix . "" . $startfrom))
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_id")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_item_id")
                            //.CHtml::activeHiddenfield($rowitem, "[" . $length . "]material_receipt_date")
                            //.CHtml::activeHiddenfield($rowitem, "[" . $length . "]stock_affect_date")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bill_of_entry")
                            //.CHtml::activeHiddenfield($rowitem, "[" . $length . "]bill_exit")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]warehouse_id")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rack_id")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bin_id")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]batch_no")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]manufacturing_date")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]expiry_date")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]transaction_type")
                            . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rowno", array('value' => $rowitem->id))
                            . '</td>
                                        </tr>';
                        $startfrom = $startfrom + $increment;
                        $length++;
                    }
                }
            }
        } else {
            if ($length == 0)
                $data['table'] .= '<tr class="no-data-tr"><td colspan="11" class="text-center"> No Data </td></tr>';
        }
        $data['table'] .= '</table>';

        //code added by mereena on 26/03/2020

        $data['arktable'] = '';
        $data['arktable'] .= '<table class="table table-hover table-bordered personal-task" id="serialno_items_table_ark" style="margin-top : 10px;">
                            <tr>
                                <th>Sno</th>
                                <th>Serial No</th>
                            </tr>';
        if ($ark_stock_details[0]->id > 0) {
            $sno = 0;
            foreach ($ark_stock_details as $s => $rowarkitem) {
                $each_qty = $rowarkitem->quantity;
                if ($each_qty > 0) {
                    for ($s = 1; $s <= $each_qty; $s++) {
                        $data['arktable'] .= '<tr class="">
                                                                <td>' . ($sno + 1) . '</td>
                                                                <td>' . CHtml::activeTextfield($rowarkitem, "[" . $length . "]serial_no", array('class' => 'form-control addserialno', 'onkeyup' => '', 'onkeypress' => '', 'value' => $prefix . "" . $startfrom))
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]header_id")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]header_item_id")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]bill_of_entry")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]warehouse_id")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]rack_id")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]bin_id")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]batch_no")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]manufacturing_date")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]expiry_date")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]transaction_type")
                            . CHtml::activeHiddenfield($rowarkitem, "[" . $length . "]rowno", array('value' => $rowarkitem->id))
                            . '</td>
                                                            </tr>';
                        $startfrom = $startfrom + $increment;
                        $length++;
                        $sno++;
                    }
                }
            }
        } else {
            if ($length == 0)
                $data['arktable'] .= '<tr class="no-data-tr"><td colspan="11" class="text-center"> No Data </td></tr>';
        }
        $data['arktable'] .= '</table>';

        //end


        echo CJSON::encode($data);
    }

    public function actionFetchRemoveSerialNoItems()
    {
        $product_id = $_POST['product_id'];
        $condition = 't.product_id ="' . $product_id . '" AND quantity > 0 AND t.isActive="Y"';
        $stock_details = array(new StockLedger);
        $ace_total_item_qty = 0;
        $ark_total_item_qty = 0;
        if ((int) $product_id > 0)
            $stock_details = StockLedger::model()->findAll(array(
                'select' => '*, SUM(quantity) as quantity',
                'condition' => $condition,
                'order' => 'id ASC',
                'group' => 'warehouse_id,rack_id,bin_id'
            ));



        $data['table'] = '';
        $data['table'] .= '<table class="table table-hover table-bordered personal-task" id="serialno_remove_items_table" style="margin-top : 10px;">
                            <tr style="background-color: rgb(31,103,178);"><td colspan="11" style="color:white"><b>ACE</b></td></tr>
                            <tr>
                                <th>Sno</th>
                                <th>Warehoue</th>
                                <th>Rack</th>
                                <th>Bin</th>
                                <th>Qty</th>
                            </tr>';
        if ($stock_details[0]->id > 0) {
            $sno = 1;
            $length = 0;
            foreach ($stock_details as $rowitem) {
                $model_wh = MasInventoryWarehouse::model()->findBypk($rowitem->warehouse_id);
                $model_rack = MasInvRack::model()->findBypk($rowitem->rack_id);
                $model_bin = MasInvBin::model()->findBypk($rowitem->bin_id);
                $data['table'] .= '<tr class="">
                                        <td>' . ($length + 1) . '</td>
                                        <td>' . $model_wh->warehouse_name
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_item_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bill_of_entry")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]warehouse_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rack_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bin_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]batch_no")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]manufacturing_date")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]expiry_date")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]quantity", array('value' => $rowitem->quantity))
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]transaction_type")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rowno", array('value' => $rowitem->id))
                    . '</td>
                                        <td>' . $model_rack->name . '</td>
                                        <td>' . $model_bin->name . '</td>
                                        <td>' . $rowitem->quantity . '</td>
                                    </tr>';
                $length++;
                $ace_total_item_qty++;
            }
        } else {
            if ($length == 0)
                $data['table'] .= '<tr class="no-data-tr"><td colspan="11" class="text-center"> No Data </td></tr>';
        }
        $data['table'] .= '</table>';
        //code added by mereena on 26/03/2020

        $this->ChanageDB(MasCompany::DB_ARK);
        $ark_stock_details = StockLedger::model()->findAll(array(
            'select' => '*, SUM(quantity) as quantity',
            'condition' => $condition,
            'order' => 'id ASC',
            'group' => 'warehouse_id,rack_id,bin_id'
        ));
        $data['arktable'] = '';
        $data['arktable'] .= '<table class="table table-hover table-bordered personal-task" id="serialno_remove_items_table_ark" style="margin-top : 10px;">
                            <tr style="background-color: rgb(31,103,178);"><td colspan="11" style="color:white"><b>ARK</b></td></tr>
                            <tr>
                                <th>Sno</th>
                                <th>Warehoue</th>
                                <th>Rack</th>
                                <th>Bin</th>
                                <th>Qty</th>
                            </tr>';
        if ($ark_stock_details[0]->id > 0) {
            $sno = 0;
            foreach ($ark_stock_details as $rowitem) {
                $this->ChanageDB(MasCompany::DB_ARK);
                $model_wh = MasInventoryWarehouse::model()->findBypk($rowitem->warehouse_id);
                $model_rack = MasInvRack::model()->findBypk($rowitem->rack_id);
                $model_bin = MasInvBin::model()->findBypk($rowitem->bin_id);
                $data['arktable'] .= '<tr class="">
                                        <td>' . ($sno + 1) . '</td>
                                        <td>' . $model_wh->warehouse_name
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_item_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bill_of_entry")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]warehouse_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rack_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bin_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]batch_no")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]manufacturing_date")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]expiry_date")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]quantity", array('value' => $rowitem->quantity))
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]transaction_type")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rowno", array('value' => $rowitem->id))
                    . '</td>
                                        <td>' . $model_rack->name . '</td>
                                        <td>' . $model_bin->name . '</td>
                                        <td>' . $rowitem->quantity . '</td>
                                    </tr>';
                $length++;
                $sno++;
                $ark_total_item_qty++;
            }
        } else {
            if ($ark_total_item_qty == 0)
                $data['arktable'] .= '<tr class="no-data-tr"><td colspan="11" class="text-center"> No Data </td></tr>';
        }
        $data['arktable'] .= '</table>';
        $this->ChanageDB(MasCompany::DB_ACE);
        //end
        $data['ace_total_item_qty'] = $ace_total_item_qty;
        $data['ark_total_item_qty'] = $ark_total_item_qty;

        echo CJSON::encode($data);
    }

    public function actionSaveSerialNo()
    {
        $product_id = $_POST['product_id'];
        //code added by mereena on 26/03/2020
        $total_qty_ace = $_POST['total_qty_ace'];
        $total_qty_ark = $_POST['total_qty_ark'];
        //end
        if (!empty($_POST['StockLedger'])) {
            $k = 0;
            foreach ($_POST['StockLedger'] as $i => $item) {
                if (!empty($item['serial_no'])) {

                    if ($i < $total_qty_ace) {
                        $modelProLocDetails[$i] = new StockLedger;
                        $modelProLocDetails[$i]->attributes = $_POST['StockLedger'][$i];
                        $modelProLocDetails[$i]->header_id = $item['header_id'];
                        $modelProLocDetails[$i]->header_item_id = $item['header_item_id'];
                        $modelProLocDetails[$i]->product_id = $product_id;
                        $modelProLocDetails[$i]->bill_of_entry = $item['bill_of_entry'];
                        $modelProLocDetails[$i]->warehouse_id = $item['warehouse_id'];
                        $modelProLocDetails[$i]->rack_id = $item['rack_id'];
                        $modelProLocDetails[$i]->bin_id = $item['bin_id'];
                        $modelProLocDetails[$i]->batch_no = $item['batch_no'];
                        $modelProLocDetails[$i]->serial_no = $item['serial_no'];
                        $modelProLocDetails[$i]->quantity = 1;
                        $modelProLocDetails[$i]->transaction_type = $item['transaction_type'];
                        $modelProLocDetails[$i]->created_by = Yii::app()->user->id;
                        $modelProLocDetails[$i]->created_date = date('Y-m-d');
                        $modelProLocDetails[$i]->isActive = "Y";
                        $modelProLocDetails[$i]->manufacturing_date = $item['manufacturing_date'];
                        $modelProLocDetails[$i]->expiry_date = $item['expiry_date'];
                        $modelProLocDetails[$i]->rowno = $item['rowno'];
                        $valid = $modelProLocDetails[$i]->validate();
                    } else {
                        $modelArkProLocDetails[$k] = new StockLedger;
                        $modelArkProLocDetails[$k]->attributes = $_POST['StockLedger'][$i];
                        $modelArkProLocDetails[$k]->header_id = $item['header_id'];
                        $modelArkProLocDetails[$k]->header_item_id = $item['header_item_id'];
                        $modelArkProLocDetails[$k]->product_id = $product_id;
                        $modelArkProLocDetails[$k]->bill_of_entry = $item['bill_of_entry'];
                        $modelArkProLocDetails[$k]->warehouse_id = $item['warehouse_id'];
                        $modelArkProLocDetails[$k]->rack_id = $item['rack_id'];
                        $modelArkProLocDetails[$k]->bin_id = $item['bin_id'];
                        $modelArkProLocDetails[$k]->batch_no = $item['batch_no'];
                        $modelArkProLocDetails[$k]->serial_no = $item['serial_no'];
                        $modelArkProLocDetails[$k]->quantity = 1;
                        $modelArkProLocDetails[$k]->transaction_type = $item['transaction_type'];
                        $modelArkProLocDetails[$k]->created_by = Yii::app()->user->id;
                        $modelArkProLocDetails[$k]->created_date = date('Y-m-d');
                        $modelArkProLocDetails[$k]->isActive = "Y";
                        $modelArkProLocDetails[$k]->manufacturing_date = $item['manufacturing_date'];
                        $modelArkProLocDetails[$k]->expiry_date = $item['expiry_date'];
                        $modelArkProLocDetails[$k]->rowno = $item['rowno'];
                        $k++;

                        //$valid = $valid & $modelArkProLocDetails[$k]->validate();
                    }
                }
            }
        }
        /* echo '<pre>';
          print_r($modelProLocDetails);

          print_r($modelArkProLocDetails);
          exit; */
        if ($valid) {


            if (!empty($modelProLocDetails)) {

                $history = new SerialnoChangeHistory();
                $history->product_id = $product_id;
                $history->change_from = "N";
                $history->change_to = "Y";
                $history->created_by = Yii::app()->user->id;
                $history->created_datetime = date('Y-m-d h:i:s');
                $history->save(false);

                Store::model()->updateByPK($product_id, array('have_serial_no' => 'Y'));
                $this->ChanageDB(MasCompany::DB_ARK);
                //update serial no yes in ARK
                Store::model()->updateByPK($product_id, array('have_serial_no' => 'Y'));
                $this->ChanageDB(MasCompany::DB_ACE);
                $model_pl = StockLedger::model()->findAll(array('condition' => 'product_id="' . $product_id . '" AND quantity>0'));
                if (!empty($model_pl)) {
                    foreach ($model_pl as $each_mr) {

                        /*                         * ***************** Stock Ledger ****************************** */
                        $modelStore = Store::model()->findBypk($each_item['product_id']);
                        if ($each_mr->id > 0) {
                            $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $each_mr->id));
                            $cost_price = $modelStockLedger->cost_price;
                        }
                        $stockLedger = new StockLedger;
                        $stockLedger->header_id = $each_mr['header_id'];
                        $stockLedger->header_item_id = $each_mr['header_item_id'];
                        $stockLedger->transaction_date = $modelInvoice->invoice_date;
                        $stockLedger->transaction_type = "CHANGE_SERIALNO";
                        $stockLedger->product_id = $each_mr['product_id'];
                        $stockLedger->quantity = -1 * $each_mr->quantity;
                        $stockLedger->product_location_id = $each_mr->id;
                        $stockLedger->unit_id = $modelStore['unit_id'];
                        $stockLedger->warehouse_id = $each_mr['warehouse_id'];
                        $stockLedger->rack_id = $each_mr['rack_id'];
                        $stockLedger->bin_id = $each_mr['bin_id'];
                        $stockLedger->created_by = Yii::app()->user->id;
                        $stockLedger->created_date = date('Y-m-d h:i:s');
                        $stockLedger->cost_price = $cost_price;
                        $stockLedger->save(false);
                        /*                         * ***************** End Stock Ledger ****************************** */
                        /*                         * ***************   history  ******************** */
                        $modelHistory = new SerialnoChangeHistoryDetails();
                        $modelHistory->history_id = $history->id;
                        $modelHistory->product_location = $each_mr->id;
                        //$modelHistory->old_stock_ledger_ids = $modelStockLedger->id;
                        $modelHistory->stock_ledger_id = $stockLedger->id;
                        $modelHistory->qty = $each_mr->quantity;
                        $modelHistory->action = "U";
                        $modelHistory->save(false);
                        /*                         * ***************** End History ****************************** */
                    }
                    StockLedger::model()->updateAll(array('quantity' => '0', 'isActive' => 'N'), 'product_id =' . $product_id);
                }

                $new_product_location_id = array();
                foreach ($modelProLocDetails as $each_item) {
                    $id = $each_item['rowno'];
                    $each_item->save(false);
                    $new_product_location_id[] = $each_item->id;

                    $modelStore = Store::model()->findBypk($each_item['product_id']);

                    if ($id > 0) {
                        $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $id));
                        $cost_price = $modelStockLedger->cost_price;
                    }
                    $stockLedger = new StockLedger;
                    $stockLedger->header_id = $each_item['header_id'];
                    $stockLedger->header_item_id = $each_item['header_item_id'];
                    $stockLedger->transaction_date = $modelInvoice->invoice_date;
                    $stockLedger->transaction_type = "CHANGE_SERIALNO";
                    $stockLedger->product_id = $each_item['product_id'];
                    $stockLedger->quantity = 1;
                    $stockLedger->product_location_id = $each_item->id;
                    $stockLedger->unit_id = $modelStore['unit_id'];
                    $stockLedger->warehouse_id = $each_item['warehouse_id'];
                    $stockLedger->rack_id = $each_item['rack_id'];
                    $stockLedger->bin_id = $each_item['bin_id'];
                    $stockLedger->created_by = Yii::app()->user->id;
                    $stockLedger->created_date = date('Y-m-d h:i:s');
                    $stockLedger->cost_price = $cost_price;
                    $stockLedger->save(false);

                    /*                     * ***************   history  ******************** */
                    $modelHistory = new SerialnoChangeHistoryDetails();
                    $modelHistory->history_id = $history->id;
                    $modelHistory->product_location = $each_item->id;
                    //$modelHistory->old_stock_ledger_ids = $modelStockLedger->id;
                    $modelHistory->stock_ledger_id = $stockLedger->id;
                    $modelHistory->qty = 1;
                    $modelHistory->action = "A";
                    $modelHistory->save(false);
                    /*                     * ***************** End History ****************************** */
                }
            }

            //code added by mereena on 26/03/2020




            if (!empty($modelArkProLocDetails)) {

                //code added by mereena on 26/03/2020
                $this->ChanageDB(MasCompany::DB_ARK);

                $history = new SerialnoChangeHistory();
                $history->product_id = $product_id;
                $history->change_from = "N";
                $history->change_to = "Y";
                $history->created_by = Yii::app()->user->id;
                $history->created_datetime = date('Y-m-d h:i:s');
                $history->save(false);

                $model_pl = StockLedger::model()->findAll(array('condition' => 'product_id="' . $product_id . '" AND quantity>0'));
                if (!empty($model_pl)) {
                    foreach ($model_pl as $each_mr) {

                        /*                         * ***************** Stock Ledger ****************************** */
                        $modelStore = Store::model()->findBypk($each_item['product_id']);
                        if ($each_mr->id > 0) {
                            $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $each_mr->id));
                            $cost_price = $modelStockLedger->cost_price;
                        }
                        $stockLedger = new StockLedger;
                        $stockLedger->header_id = $each_mr['header_id'];
                        $stockLedger->header_item_id = $each_mr['header_item_id'];
                        $stockLedger->transaction_date = $modelInvoice->invoice_date;
                        $stockLedger->transaction_type = "CHANGE_SERIALNO";
                        $stockLedger->product_id = $each_mr['product_id'];
                        $stockLedger->quantity = -1 * $each_mr->quantity;
                        $stockLedger->product_location_id = $each_mr->id;
                        $stockLedger->unit_id = $modelStore['unit_id'];
                        $stockLedger->warehouse_id = $each_mr['warehouse_id'];
                        $stockLedger->rack_id = $each_mr['rack_id'];
                        $stockLedger->bin_id = $each_mr['bin_id'];
                        $stockLedger->created_by = Yii::app()->user->id;
                        $stockLedger->created_date = date('Y-m-d h:i:s');
                        $stockLedger->cost_price = $cost_price;
                        $stockLedger->save(false);
                        /*                         * ***************** End Stock Ledger ****************************** */
                        /*                         * ***************   history  ******************** */
                        $modelHistory = new SerialnoChangeHistoryDetails();
                        $modelHistory->history_id = $history->id;
                        $modelHistory->product_location = $each_mr->id;
                        //$modelHistory->old_stock_ledger_ids = $modelStockLedger->id;
                        $modelHistory->stock_ledger_id = $stockLedger->id;
                        $modelHistory->qty = $each_mr->quantity;
                        $modelHistory->action = "U";
                        $modelHistory->save(false);
                        /*                         * ***************** End History ****************************** */
                    }
                    StockLedger::model()->updateAll(array('quantity' => '0', 'isActive' => 'N'), 'product_id =' . $product_id);
                }

                $new_product_location_id = array();
                foreach ($modelArkProLocDetails as $each_item) {
                    $id = $each_item['rowno'];
                    $each_item->save(false);
                    $new_product_location_id[] = $each_item->id;

                    $modelStore = Store::model()->findBypk($each_item['product_id']);

                    if ($id > 0) {
                        $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $id));
                        $cost_price = $modelStockLedger->cost_price;
                    }
                    $stockLedger = new StockLedger;
                    $stockLedger->header_id = $each_item['header_id'];
                    $stockLedger->header_item_id = $each_item['header_item_id'];
                    $stockLedger->transaction_date = date('Y-m-d');
                    $stockLedger->transaction_type = "CHANGE_SERIALNO";
                    $stockLedger->product_id = $each_item['product_id'];
                    $stockLedger->quantity = 1;
                    $stockLedger->product_location_id = $each_item->id;
                    $stockLedger->unit_id = $modelStore['unit_id'];
                    $stockLedger->warehouse_id = $each_item['warehouse_id'];
                    $stockLedger->rack_id = $each_item['rack_id'];
                    $stockLedger->bin_id = $each_item['bin_id'];
                    $stockLedger->created_by = Yii::app()->user->id;
                    $stockLedger->created_date = date('Y-m-d h:i:s');
                    $stockLedger->cost_price = $cost_price;
                    $stockLedger->save(false);

                    /*                     * ***************   history  ******************** */
                    $modelHistory = new SerialnoChangeHistoryDetails();
                    $modelHistory->history_id = $history->id;
                    $modelHistory->product_location = $each_item->id;
                    //$modelHistory->old_stock_ledger_ids = $modelStockLedger->id;
                    $modelHistory->stock_ledger_id = $stockLedger->id;
                    $modelHistory->qty = 1;
                    $modelHistory->action = "A";
                    $modelHistory->save(false);
                    /*                     * ***************** End History ****************************** */
                }

                $this->ChanageDB(MasCompany::DB_ACE);
                //end
            }
            //end
            $jsonData['status'] = 'success';
            $product = Store::model()->findBypk($product_id);
            $jsonData['pid'] = $product_id;
            $jsonData['pname'] = $product->part_number;
            echo CJSON::encode($jsonData);
        } else {
            $error1 = array();
            if (!empty($modelProLocDetails)) {
                $error1 = json_decode(CActiveForm::validate($modelProLocDetails, '', false), true);
            }
            $error = CJSON::encode(array_merge_recursive($error1));
            if ($error != '[]')
                echo $error;
        }
    }

    public function actionSaveRemoveSerialNo()
    {

        $product_id = $_POST['productid'];
        $ace_total_item_qty = $_POST['ace_total_item_qty'];
        $ark_total_item_qty = $_POST['ark_total_item_qty'];

        if (!empty($_POST['StockLedger'])) {

            $k = 0;
            foreach ($_POST['StockLedger'] as $i => $item) {
                if ($item['quantity'] > 0) {

                    if ($i < $ace_total_item_qty) {
                        $modelProLocDetails[$i] = new StockLedger;
                        $modelProLocDetails[$i]->attributes = $_POST['StockLedger'][$i];
                        $modelProLocDetails[$i]->header_id = $item['header_id'];
                        $modelProLocDetails[$i]->header_item_id = $item['header_item_id'];
                        $modelProLocDetails[$i]->product_id = $product_id;
                        $modelProLocDetails[$i]->bill_of_entry = $item['bill_of_entry'];
                        $modelProLocDetails[$i]->warehouse_id = $item['warehouse_id'];
                        $modelProLocDetails[$i]->rack_id = $item['rack_id'];
                        $modelProLocDetails[$i]->bin_id = $item['bin_id'];
                        $modelProLocDetails[$i]->batch_no = $item['batch_no'];
                        $modelProLocDetails[$i]->quantity = $item['quantity'];
                        $modelProLocDetails[$i]->transaction_type = $item['transaction_type'];
                        $modelProLocDetails[$i]->created_by = Yii::app()->user->id;
                        $modelProLocDetails[$i]->created_date = date('Y-m-d');
                        $modelProLocDetails[$i]->isActive = "Y";
                        $modelProLocDetails[$i]->manufacturing_date = $item['manufacturing_date'];
                        $modelProLocDetails[$i]->expiry_date = $item['expiry_date'];
                        $modelProLocDetails[$i]->rowno = $item['rowno'];
                        $valid = $modelProLocDetails[$i]->validate();
                    } else {
                        $modelArkProLocDetails[$k] = new StockLedger;
                        $modelArkProLocDetails[$k]->attributes = $_POST['StockLedger'][$i];
                        $modelArkProLocDetails[$k]->header_id = $item['header_id'];
                        $modelArkProLocDetails[$k]->header_item_id = $item['header_item_id'];
                        $modelArkProLocDetails[$k]->product_id = $product_id;
                        $modelArkProLocDetails[$k]->bill_of_entry = $item['bill_of_entry'];
                        $modelArkProLocDetails[$k]->warehouse_id = $item['warehouse_id'];
                        $modelArkProLocDetails[$k]->rack_id = $item['rack_id'];
                        $modelArkProLocDetails[$k]->bin_id = $item['bin_id'];
                        $modelArkProLocDetails[$k]->batch_no = $item['batch_no'];
                        $modelArkProLocDetails[$k]->quantity = $item['quantity'];
                        $modelArkProLocDetails[$k]->transaction_type = $item['transaction_type'];
                        $modelArkProLocDetails[$k]->created_by = Yii::app()->user->id;
                        $modelArkProLocDetails[$k]->created_date = date('Y-m-d');
                        $modelArkProLocDetails[$k]->isActive = "Y";
                        $modelArkProLocDetails[$k]->manufacturing_date = $item['manufacturing_date'];
                        $modelArkProLocDetails[$k]->expiry_date = $item['expiry_date'];
                        $modelArkProLocDetails[$k]->rowno = $item['rowno'];
                        $k++;

                        //$valid = $valid & $modelArkProLocDetails[$k]->validate();
                    }





                    //$valid = $modelProLocDetails[$i]->validate();
                }
            }
        }



        if ($valid) {
            if (!empty($modelProLocDetails)) {


                $history = new SerialnoChangeHistory();
                $history->product_id = $product_id;
                $history->change_from = "Y";
                $history->change_to = "N";
                $history->created_by = Yii::app()->user->id;
                $history->created_datetime = date('Y-m-d h:i:s');
                $history->save(false);

                Store::model()->updateByPK($product_id, array('have_serial_no' => 'N'));
                $model_pl = StockLedger::model()->findAll(array('condition' => 'product_id="' . $product_id . '" AND quantity>0'));
                if (!empty($model_pl)) {
                    foreach ($model_pl as $each_mr) {

                        /*                         * ***************** Stock Ledger ****************************** */
                        $modelStore = Store::model()->findBypk($each_item['product_id']);
                        if ($each_mr->id > 0) {
                            $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $each_mr->id));
                            $cost_price = $modelStockLedger->cost_price;
                        }
                        $stockLedger = new StockLedger;
                        $stockLedger->header_id = $each_mr['header_id'];
                        $stockLedger->header_item_id = $each_mr['header_item_id'];
                        $stockLedger->transaction_date = $modelInvoice->invoice_date;
                        $stockLedger->transaction_type = "CHANGE_SERIALNO";
                        $stockLedger->product_id = $each_mr['product_id'];
                        $stockLedger->quantity = -1 * $each_mr->quantity;
                        $stockLedger->product_location_id = $each_mr->id;
                        $stockLedger->unit_id = $modelStore['unit_id'];
                        $stockLedger->warehouse_id = $each_mr['warehouse_id'];
                        $stockLedger->rack_id = $each_mr['rack_id'];
                        $stockLedger->bin_id = $each_mr['bin_id'];
                        $stockLedger->created_by = Yii::app()->user->id;
                        $stockLedger->created_date = date('Y-m-d h:i:s');
                        $stockLedger->cost_price = $cost_price;
                        $stockLedger->save(false);
                        /*                         * ***************** End Stock Ledger ****************************** */
                        /*                         * ***************   history  ******************** */
                        $modelHistory = new SerialnoChangeHistoryDetails();
                        $modelHistory->history_id = $history->id;
                        $modelHistory->product_location = $each_mr->id;
                        //$modelHistory->old_stock_ledger_ids = "";
                        $modelHistory->stock_ledger_id = $stockLedger->id;
                        $modelHistory->qty = $each_mr->quantity;

                        $modelHistory->action = "U";
                        $modelHistory->created_by = Yii::app()->user->id;
                        ;
                        $modelHistory->created_date_time = date('Y-m-d H:i:s');
                        $modelHistory->save(false);
                        /*                         * ***************** End History ****************************** */
                    }
                    StockLedger::model()->updateAll(array('quantity' => '0', 'serial_no' => '', 'isActive' => 'N'), 'product_id =' . $product_id);
                }

                $new_product_location_id = array();
                foreach ($modelProLocDetails as $each_item) {

                    $id = $each_item['rowno'];
                    $qty = $each_item['quantity'];
                    $each_item->save(false);
                    $new_product_location_id[] = $each_item->id;

                    $modelStore = Store::model()->findBypk($each_item['product_id']);

                    if ($id > 0) {
                        $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $id));
                        $cost_price = $modelStockLedger->cost_price;
                    }
                    $stockLedger = new StockLedger;
                    $stockLedger->header_id = $each_item['header_id'];
                    $stockLedger->header_item_id = $each_item['header_item_id'];
                    $stockLedger->transaction_date = $modelInvoice->invoice_date;
                    $stockLedger->transaction_type = "CHANGE_SERIALNO";
                    $stockLedger->product_id = $each_item['product_id'];
                    $stockLedger->quantity = $each_item['quantity'];
                    $stockLedger->product_location_id = $each_item->id;
                    $stockLedger->unit_id = $modelStore['unit_id'];
                    $stockLedger->warehouse_id = $each_item['warehouse_id'];
                    $stockLedger->rack_id = $each_item['rack_id'];
                    $stockLedger->bin_id = $each_item['bin_id'];
                    $stockLedger->created_by = Yii::app()->user->id;
                    $stockLedger->created_date = date('Y-m-d h:i:s');
                    $stockLedger->cost_price = $cost_price;
                    $stockLedger->save(false);

                    /*                     * ***************   history  ******************* */
                    $modelHistory = new SerialnoChangeHistoryDetails();
                    $modelHistory->history_id = $history->id;
                    $modelHistory->product_location = $each_item->id;
                    //$modelHistory->old_stock_ledger_ids = $modelStockLedger->id;
                    $modelHistory->stock_ledger_id = $stockLedger->id;
                    $modelHistory->qty = $qty;
                    $modelHistory->action = "A";
                    $modelHistory->created_by = Yii::app()->user->id;
                    ;
                    $modelHistory->created_date_time = date('Y-m-d H:i:s');
                    $modelHistory->save(false);

                    /*                     * ***************  End history  ******************* */
                }
                if (is_array($new_product_location_id)) {
                    //$arr_new_product_location_id = implode(",",array_filter($new_product_location_id));
                }
            }


            //code added by mereena on 26/03/2020
            if (!empty($modelArkProLocDetails)) {

                $this->ChanageDB(MasCompany::DB_ARK);
                $history = new SerialnoChangeHistory();
                $history->product_id = $product_id;
                $history->change_from = "Y";
                $history->change_to = "N";
                $history->created_by = Yii::app()->user->id;
                $history->created_datetime = date('Y-m-d h:i:s');
                $history->save(false);

                Store::model()->updateByPK($product_id, array('have_serial_no' => 'N'));
                $model_pl = StockLedger::model()->findAll(array('condition' => 'product_id="' . $product_id . '" AND quantity>0'));
                if (!empty($model_pl)) {
                    foreach ($model_pl as $each_mr) {

                        /*                         * ***************** Stock Ledger ****************************** */
                        $modelStore = Store::model()->findBypk($each_item['product_id']);
                        if ($each_mr->id > 0) {
                            $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $each_mr->id));
                            $cost_price = $modelStockLedger->cost_price;
                        }
                        $stockLedger = new StockLedger;
                        $stockLedger->header_id = $each_mr['header_id'];
                        $stockLedger->header_item_id = $each_mr['header_item_id'];
                        $stockLedger->transaction_date = $modelInvoice->invoice_date;
                        $stockLedger->transaction_type = "CHANGE_SERIALNO";
                        $stockLedger->product_id = $each_mr['product_id'];
                        $stockLedger->quantity = -1 * $each_mr->quantity;
                        $stockLedger->product_location_id = $each_mr->id;
                        $stockLedger->unit_id = $modelStore['unit_id'];
                        $stockLedger->warehouse_id = $each_mr['warehouse_id'];
                        $stockLedger->rack_id = $each_mr['rack_id'];
                        $stockLedger->bin_id = $each_mr['bin_id'];
                        $stockLedger->created_by = Yii::app()->user->id;
                        $stockLedger->created_date = date('Y-m-d h:i:s');
                        $stockLedger->cost_price = $cost_price;
                        $stockLedger->save(false);
                        /*                         * ***************** End Stock Ledger ****************************** */
                        /*                         * ***************   history  ******************** */
                        $modelHistory = new SerialnoChangeHistoryDetails();
                        $modelHistory->history_id = $history->id;
                        $modelHistory->product_location = $each_mr->id;
                        //$modelHistory->old_stock_ledger_ids = "";
                        $modelHistory->stock_ledger_id = $stockLedger->id;
                        $modelHistory->qty = $each_mr->quantity;

                        $modelHistory->action = "U";
                        $modelHistory->created_by = Yii::app()->user->id;
                        ;
                        $modelHistory->created_date_time = date('Y-m-d H:i:s');
                        $modelHistory->save(false);
                        /*                         * ***************** End History ****************************** */
                    }
                    StockLedger::model()->updateAll(array('quantity' => '0', 'serial_no' => '', 'isActive' => 'N'), 'product_id =' . $product_id);
                }

                $new_product_location_id = array();
                foreach ($modelArkProLocDetails as $each_item) {

                    $id = $each_item['rowno'];
                    $qty = $each_item['quantity'];
                    $each_item->save(false);
                    $new_product_location_id[] = $each_item->id;

                    $modelStore = Store::model()->findBypk($each_item['product_id']);

                    if ($id > 0) {
                        $modelStockLedger = StockLedger::model()->find(array('condition' => 'product_location_id=' . $id));
                        $cost_price = $modelStockLedger->cost_price;
                    }
                    $stockLedger = new StockLedger;
                    $stockLedger->header_id = $each_item['header_id'];
                    $stockLedger->header_item_id = $each_item['header_item_id'];
                    $stockLedger->transaction_date = $modelInvoice->invoice_date;
                    $stockLedger->transaction_type = "CHANGE_SERIALNO";
                    $stockLedger->product_id = $each_item['product_id'];
                    $stockLedger->quantity = $each_item['quantity'];
                    $stockLedger->product_location_id = $each_item->id;
                    $stockLedger->unit_id = $modelStore['unit_id'];
                    $stockLedger->warehouse_id = $each_item['warehouse_id'];
                    $stockLedger->rack_id = $each_item['rack_id'];
                    $stockLedger->bin_id = $each_item['bin_id'];
                    $stockLedger->created_by = Yii::app()->user->id;
                    $stockLedger->created_date = date('Y-m-d h:i:s');
                    $stockLedger->cost_price = $cost_price;
                    $stockLedger->save(false);

                    /*                     * ***************   history  ******************* */
                    $modelHistory = new SerialnoChangeHistoryDetails();
                    $modelHistory->history_id = $history->id;
                    $modelHistory->product_location = $each_item->id;
                    //$modelHistory->old_stock_ledger_ids = $modelStockLedger->id;
                    $modelHistory->stock_ledger_id = $stockLedger->id;
                    $modelHistory->qty = $qty;
                    $modelHistory->action = "A";
                    $modelHistory->created_by = Yii::app()->user->id;
                    ;
                    $modelHistory->created_date_time = date('Y-m-d H:i:s');
                    $modelHistory->save(false);

                    /*                     * ***************  End history  ******************* */
                }
                if (is_array($new_product_location_id)) {
                    //$arr_new_product_location_id = implode(",",array_filter($new_product_location_id));
                }

                $this->ChanageDB(MasCompany::DB_ACE);
            }
            //end
            $jsonData['status'] = 'success';
            $product = Store::model()->findBypk($product_id);
            $jsonData['pid'] = $product_id;
            $jsonData['pname'] = $product->part_number;
            echo CJSON::encode($jsonData);
        } else {
            $error1 = array();

            if (!empty($modelProLocDetails)) {
                $error1 = json_decode(CActiveForm::validate($modelProLocDetails, '', false), true);
            }
            $error = CJSON::encode(array_merge_recursive($error1));
            if ($error != '[]')
                echo $error;
        }
    }

    public function actionAddBatchNo()
    {
        $pid = (int) Yii::app()->request->getParam('pid');
        $type = Yii::app()->request->getParam('type');
        $total_qty_ace = Yii::app()->request->getParam('total_qty_ace');
        $total_qty_ark = Yii::app()->request->getParam('total_qty_ark');
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('batch_no_form', array('pid' => $pid, 'total_qty_ace' => $total_qty_ace, 'total_qty_ark' => $total_qty_ark), false, false);
    }

    public function actionFetchBatchItems()
    {
        $product_id = $_POST['product_id'];
        $condition = 't.product_id ="' . $product_id . '" AND quantity > 0';
        $stock_details = array(new StockLedger);
        if ((int) $product_id > 0) {
            $stock_details = StockLedger::model()->findAll(array('condition' => $condition, 'order' => 'id ASC'));
            /* //code added by mereena on 26/03/2020
              $this->ChanageDB(MasCompany::DB_ARK);
              $ark_stock_details = StockLedger::model()->findAll(array('condition' => $condition,'order'=>'id ASC'));
              $this->ChanageDB(MasCompany::DB_ACE);
              //end */
        }
        $ace_total_item_qty = 0;
        /* $ark_total_item_qty=0; */
        $data['table'] = '';
        $data['table'] .= '<table class="table table-hover table-bordered personal-task" id="batchno_items_table" style="margin-top : 10px;">
                            <thead><tr>
                                <th>Warehoue</th>
                                <th>Rack</th>
                                <th>Bin</th>
                                <th>Qty</th>
                                <th>Batch No</th>
                                <th>Expiry Date</th>
                            </tr></thead><tbody id="tbody_material">';
        if ($stock_details[0]->id > 0) {

            $sno = 1;
            $length = 0;
            foreach ($stock_details as $rowitem) {
                $model_wh = MasInventoryWarehouse::model()->findBypk($rowitem->warehouse_id);
                $model_rack = MasInvRack::model()->findBypk($rowitem->rack_id);
                $model_bin = MasInvBin::model()->findBypk($rowitem->bin_id);

                if ($rowitem->expiry_date == '0000-00-00' or $rowitem->expiry_date == '1970-01-01') {
                    $expiry_date = "";
                } else {
                    $expiry_date = date("d/m/Y", strtotime($rowitem->expiry_date));
                }
                $actual_qty = $rowitem->quantity;

                $data['table'] .= '<tr class="">
                                                <td>' . $model_wh->warehouse_name
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]id") . '</td>
                                                <td>' . $model_rack->name . '</td>
                                                <td>' . $model_bin->name . '</td>
                                                <td>' . CHtml::activeTextfield($rowitem, "[" . $length . "]quantity", array('class' => 'form-control', 'readonly' => true)) . '</td>
                                                <td>' . CHtml::activeTextfield($rowitem, "[" . $length . "]batch_no", array('class' => 'form-control')) . '</td>
                                                <td>' . CHtml::activeTextfield($rowitem, "[" . $length . "]expiry_date", array('class' => 'form-control datepicker', 'value' => $expiry_date))
                    . '</td>
                                           </tr>';
                $length++;
                $ace_total_item_qty++;
            }
        } else {
            if ($length == 0)
                $data['table'] .= '<tr class="no-data-tr"><td colspan="11" class="text-center"> No Data </td></tr>';
        }
        $data['table'] .= '</tbody></table>';

        /* //code added by mereena on 30/03/2020
          $this->ChanageDB(MasCompany::DB_ARK);
          if((int) $product_id > 0){
          //code added by mereena on 26/03/2020
          $ark_stock_details = StockLedger::model()->findAll(array('condition' => $condition,'order'=>'id ASC'));
          //end
          }
          $data['arktable']  = '';
          $data['arktable'] .= '<table class="table table-hover table-bordered personal-task" id="batchno_items_table_ark" style="margin-top : 10px;">
          <thead><tr>
          <th>Warehoue</th>
          <th>Rack</th>
          <th>Bin</th>
          <th>Qty</th>
          <th>Batch No</th>
          <th>Expiry Date</th>
          </tr></thead><tbody id="tbody_material">';
          if($ark_stock_details[0]->id > 0){

          $sno  = 1;
          foreach($ark_stock_details as $rowitem){
          $model_wh   = MasInventoryWarehouse::model()->findBypk($rowitem->warehouse_id);
          $model_rack = MasInvRack::model()->findBypk($rowitem->rack_id);
          $model_bin  = MasInvBin::model()->findBypk($rowitem->bin_id);

          if($rowitem->expiry_date =='0000-00-00' OR $rowitem->expiry_date =='1970-01-01'){
          $expiry_date  = "";
          }
          else{
          $expiry_date  = date("d/m/Y",strtotime($rowitem->expiry_date));
          }
          $actual_qty   = $rowitem->quantity;

          $data['arktable'] .= '<tr class="">
          <td>'.$model_wh->warehouse_name
          .CHtml::activeHiddenfield($rowitem, "[" . $length . "]id").'</td>
          <td>'.$model_rack->name.'</td>
          <td>'.$model_bin->name.'</td>
          <td>'.CHtml::activeTextfield($rowitem, "[" . $length . "]quantity",array('class' => 'form-control','readonly'=>true)).'</td>
          <td>'.CHtml::activeTextfield($rowitem, "[" . $length . "]batch_no",array('class' => 'form-control')).'</td>
          <td>'.CHtml::activeTextfield($rowitem, "[" . $length . "]expiry_date",array('class' => 'form-control datepicker','value'=>$expiry_date))
          .'</td>
          </tr>';
          $length++;
          $ark_total_item_qty++;
          }
          }
          else{
          if($ark_total_item_qty == 0)
          $data['arktable'] .= '<tr class="no-data-tr"><td colspan="11" class="text-center"> No Data </td></tr>';
          }
          $data['arktable'] .= '</tbody></table>';
          //end */
        $data['ace_total_item_qty'] = $ace_total_item_qty;
        /* $data['ark_total_item_qty']= $ark_total_item_qty;
          $this->ChanageDB(MasCompany::DB_ACE); */
        echo CJSON::encode($data);
    }

    public function actionSaveAddBatchNo()
    {

        $product_id = $_POST['productid'];
        $status = $_POST['expirydate_status']; //code added by mereena on 26/03/2020
        $total_qty_ace = $_POST['total_qty_ace'];
        /* $total_qty_ark   = $_POST['total_qty_ark']; */
        //end
        if (!empty($_POST['StockLedger'])) {
            $k = 0;
            Store::model()->updateByPK($product_id, array('have_expiry_date' => 'Y'));
            //code added by mereena on 26/03/2020
            /* $this->ChanageDB(MasCompany::DB_ARK);
              Store::model()->updateByPK($product_id, array('have_expiry_date' => 'Y'));
              $this->ChanageDB(MasCompany::DB_ACE); */
            //end

            foreach ($_POST['StockLedger'] as $i => $item) {
                $modelProLocDetails = new StockLedger();
                $update_id = $item['id'];
                if ($update_id > 0) {

                    if ($i < $total_qty_ace) {
                        $modelProLocDetails = $modelProLocDetails->findByPk($update_id);
                        $modelProLocDetails->batch_no = $item['batch_no'];
                        if ($item['expiry_date'] != '00/00/0000' and $item['expiry_date'] != '01/01/1970') {
                            $expiry_date = str_replace('/', '-', $item['expiry_date']);
                            $expiry_date = date("Y-m-d", strtotime($expiry_date));
                        }
                        $modelProLocDetails->expiry_date = $expiry_date;
                        $modelProLocDetails->save(false);
                    }
                    /* else{
                      //code added by mereena on 26/03/2020
                      $this->ChanageDB(MasCompany::DB_ARK);
                      $modelArkProLocDetails  = new StockLedger();
                      $modelArkProLocDetails               = $modelArkProLocDetails->findByPk($update_id);
                      $modelArkProLocDetails->batch_no  = $item['batch_no'];
                      if($item['expiry_date'] !='00/00/0000' AND $item['expiry_date'] !='01/01/1970'){
                      $expiry_date = str_replace('/', '-', $item['expiry_date']);
                      $expiry_date = date("Y-m-d", strtotime($expiry_date));
                      }
                      $modelArkProLocDetails->expiry_date  = $expiry_date;
                      $modelArkProLocDetails->save(false);
                      $this->ChanageDB(MasCompany::DB_ACE);
                      } */
                }
            }
            $jsonData['status'] = 'success';
            $product = Store::model()->findBypk($product_id);
            $jsonData['pid'] = $product_id;
            $jsonData['pname'] = $product->part_number;
            echo CJSON::encode($jsonData);
        }
    }

    public function actionSaveRemoveBatchNo()
    {

        $product_id = $_POST['product_id'];

        Store::model()->updateByPK($product_id, array('have_expiry_date' => 'N'));
        StockLedger::model()->updateAll(array('batch_no' => '', 'expiry_date' => '0000-00-00'), 'product_id ="' . $product_id . '" AND quantity > 0');
        //code added by mereena on 26/03/2020
        /* $this->ChanageDB(MasCompany::DB_ARK);
          Store::model()->updateByPK($product_id, array('have_expiry_date' => 'N'));
          StockLedger::model()->updateAll(array('batch_no' => '','expiry_date'=>'0000-00-00'),'product_id ="'.$product_id.'" AND quantity > 0 ');
          $this->ChanageDB(MasCompany::DB_ACE); */
        //end
        $jsonData['status'] = 'success';
        $product = Store::model()->findBypk($product_id);
        $jsonData['pid'] = $product_id;
        $jsonData['pname'] = $product->part_number;
        echo CJSON::encode($jsonData);
    }

    public function actionAddBatchSplitDetails()
    {

        $product_id = filter_var($_POST['product_id'], FILTER_VALIDATE_INT);
        $order_id = filter_var($_POST['order_id'], FILTER_VALIDATE_INT);
        //$quantity      = filter_var($_POST['quantity'], FILTER_VALIDATE_INT);
        $quantity = number_format((float) $_POST['quantity'], 2, '.', '');
        //$quantity      = $_POST['quantity'];
        $totalquantity = $_POST['totalquantity'];
        $newId = filter_var($_POST['newId'], FILTER_VALIDATE_INT);
        //$field_id      = filter_var($_POST['field_id'], FILTER_VALIDATE_INT);
        //$model_material_stock=new MaterialReceiptStockDetails();
        $model_product = Store::model()->findbyPK($product_id);
        $batch_mandty = 0;
        $serial_mandty = 0;
        $color_mandatory = "";
        $color_mandatory_1 = "";
        if ($model_product->have_expiry_date == "Y") {
            $batch_mandty = 1;
            $color_mandatory = "bg-danger";
        }
        if ($model_product->have_serial_no == "Y") {
            $serial_mandty = 1;
            $color_mandatory_1 = "bg-danger";
        }



        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('batch_no_MR_details', array('model_material_stock' => $model_material_stock, 'product_id' => $product_id, 'quantity' => $quantity, 'newId' => $newId, 'batch_mandty' => $batch_mandty, 'serial_mandty' => $serial_mandty, 'color_mandatory' => $color_mandatory, 'color_mandatory_1' => $color_mandatory_1, 'totalquantity' => $totalquantity, 'field_id' => $field_id, 'order_id' => $order_id));
        /* if($model_product->have_serial_no=="Y"){
          $this->render('batch_no_MR_serial_details', array('model_material_stock' => $model_material_stock,'product_id' => $product_id,'quantity' => $quantity,'newId' => $newId,'batch_mandty' => $batch_mandty,'serial_mandty' => $serial_mandty,'color_mandatory'=>$color_mandatory,'color_mandatory_1'=>$color_mandatory_1,'totalquantity'=>$totalquantity,'field_id'=>$field_id,'order_id'=>$order_id));
          }else{
          //$this->render('batch_no_MR_details', array('model_material_stock' => $model_material_stock,'product_id' => $product_id,'quantity' => $quantity,'newId' => $newId,'batch_mandty' => $batch_mandty,'serial_mandty' => $serial_mandty,'color_mandatory'=>$color_mandatory,'color_mandatory_1'=>$color_mandatory_1,'totalquantity'=>$totalquantity,'field_id'=>$field_id,'mr_id'=>$mr_id));
          $this->render('batch_no_MR_details', array('model_material_stock' => $model_material_stock,'product_id' => $product_id,'quantity' => $quantity,'newId' => $newId,'batch_mandty' => $batch_mandty,'serial_mandty' => $serial_mandty,'color_mandatory'=>$color_mandatory,'color_mandatory_1'=>$color_mandatory_1,'totalquantity'=>$totalquantity,'field_id'=>$field_id,'order_id'=>$order_id));
          } */
    }

    public function actionEditserialno()
    {
        $model = new StockLedger();
        $id = (int) Yii::app()->request->getParam('id');
        if ($id > 0) {
            $model = $model->findByPk($id);
        }
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->renderPartial('serial_no_edit_form', array('model' => $model), false, true);
    }

    public function actionUpdateserialno()
    {
        $model = new StockLedger();
        if (isset($_POST['StockLedger'])) {

            $product_id = $_POST['serialno_product_id'];
            $serial_no = $_POST['StockLedger']['serial_no'];
            $id = (int) @$_POST['StockLedger']['id'];

            $check_serialno = StockLedger::model()->find(array(
                'condition' => '
                                                                                product_id="' . $product_id . '"
                                                                                AND serial_no="' . $serial_no . '"
                                                                                AND id !="' . $id . '"'
            ));

            if (empty($check_serialno)) {

                $model = $model->findByPk($id);
                $model->serial_no = $_POST['StockLedger']['serial_no'];
                $model->save(false);
                $jsonData['status'] = 'success';
            } else {
                $jsonData['status'] = 'fail';
            }
            echo CJSON::encode($jsonData);
        }
    }

    public function actionSaveService()
    {
        $model = new Store();
        $scenario = '';
        if ((int) $_POST['Store']['id'] > 0) {
            $id = $_POST['Store']['id'];
            $model = $model->findByPk($id);
            $model->updated_by = Yii::app()->user->id;
            $model->updated_date_time = date('Y-m-d h:i:s');
            $scenario = 'update';
            $audit_type = 'UPDATED';
            $edit_flag = 1;
        } else {
            $model->created_by = Yii::app()->user->id;
            $model->created_date_time = date('Y-m-d h:i:s');
            $model->scenario = 'add';
            $scenario = 'add';
            $audit_type = 'CREATED';
        }
        $model->attributes = $_POST['Store'];
        $model->service_product_type = $_POST['Store']['service_product_type'];
        $model->ledger_id = $_POST['Store']['ledger_id'];

        $model->inventory_item_type = 2;  //Service
        //defaullt section sadded

        if ($_POST['Store']['default_service_item'] == "Y") {
            $sql = "UPDATE `erp_store` SET `default_service_item`='N'  WHERE default_service_item='Y' AND inventory_item_type='2' ";
            Yii::app()->db->createCommand($sql)->execute();
        }
        $model->default_service_item = $_POST['Store']['default_service_item'];
        if ($model->validate()) {
            $jsonData['stasstus'] = 'success';
            echo CJSON::encode($jsonData);
            $model->save();

            if (!empty($_POST['Store']['unit_id']) && (int) $_POST['Store']['id'] == 0) {
                $modelUnitMeasurement = new UnitOfMeasurement();
                $modelUnitMeasurement->product_id = $model->id;
                $modelUnitMeasurement->factor = 1;
                $modelUnitMeasurement->isBase = "Y";
                $modelUnitMeasurement->name = Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
                $modelUnitMeasurement->base_unit = $_POST['Store']['unit_id'];
                $modelUnitMeasurement->created_by = Yii::app()->user->id;
                $modelUnitMeasurement->created_date_time = date('Y-m-d H:i:s');
                $modelUnitMeasurement->save(false);
            } else if (!empty($_POST['Store']['unit_id']) && (int) $_POST['Store']['id'] > 0) {
                $uomservice = UnitOfMeasurement::model()->find(array('condition' => 'product_id=' . $_POST['Store']['id']));
                $modelUnitMeasurement = UnitOfMeasurement::model()->findByPk((int) $uomservice->id);
                if (!empty($modelUnitMeasurement)) { //condition add to solve the erroro empty product id
                    $modelUnitMeasurement->product_id = $model->id;
                    $modelUnitMeasurement->factor = 1;
                    $modelUnitMeasurement->isBase = "Y";
                    $modelUnitMeasurement->name = Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
                    $modelUnitMeasurement->base_unit = $_POST['Store']['unit_id'];
                    $modelUnitMeasurement->created_by = Yii::app()->user->id;
                    $modelUnitMeasurement->created_date_time = date('Y-m-d H:i:s');
                    $modelUnitMeasurement->save(false);
                }
            }

            // inserting to audit log
            AuditLog::saveAuditLogs(
                'SERVICE',
                Yii::app()->user->id,
                $audit_type,
                " with No: - {$model->id} & Part No: - {$_POST['Store']['part_number']}  "
            );
            // end audit log
            // $model->save_ledger();
        } else {
            $error1 = json_decode(CActiveForm::validate($model, '', false), true);
            $error = CJSON::encode($error1);
            if ($error != '[]')
                echo $error;
        }
    }

    public function actionSaveEquipment()
    {
        $model = new Store();
        $scenario = '';
        if ((int) $_POST['Store']['id'] > 0) {
            $id = $_POST['Store']['id'];
            $model = $model->findByPk($id);
            $model->updated_by = Yii::app()->user->id;
            $model->updated_date_time = date('Y-m-d h:i:s');
            $scenario = 'update';
            $audit_type = 'UPDATED';
            $edit_flag = 1;
        } else {
            $model->created_by = Yii::app()->user->id;
            $model->created_date_time = date('Y-m-d h:i:s');
            $model->scenario = 'add';
            $scenario = 'add';
            $audit_type = 'CREATED';
        }
        $model->attributes = $_POST['Store'];
        $model->service_product_type = $_POST['Store']['service_product_type'];
        $model->ledger_id = $_POST['Store']['ledger_id'];

        $model->inventory_item_type = 4;  //Equipment
        //defaullt section sadded

        if ($_POST['Store']['default_service_item'] == "Y") {
            $sql = "UPDATE `erp_store` SET `default_service_item`='N'  WHERE default_service_item='Y' AND inventory_item_type='4' ";
            Yii::app()->db->createCommand($sql)->execute();
        }
        $model->default_service_item = $_POST['Store']['default_service_item'];
        if ($model->validate()) {
            $jsonData['stasstus'] = 'success';
            echo CJSON::encode($jsonData);
            $model->save();

            if (!empty($_POST['Store']['unit_id']) && (int) $_POST['Store']['id'] == 0) {
                $modelUnitMeasurement = new UnitOfMeasurement();
                $modelUnitMeasurement->product_id = $model->id;
                $modelUnitMeasurement->factor = 1;
                $modelUnitMeasurement->isBase = "Y";
                $modelUnitMeasurement->name = Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
                $modelUnitMeasurement->base_unit = $_POST['Store']['unit_id'];
                $modelUnitMeasurement->created_by = Yii::app()->user->id;
                $modelUnitMeasurement->created_date_time = date('Y-m-d H:i:s');
                $modelUnitMeasurement->save(false);
            } else if (!empty($_POST['Store']['unit_id']) && (int) $_POST['Store']['id'] > 0) {
                $uomservice = UnitOfMeasurement::model()->find(array('condition' => 'product_id=' . $_POST['Store']['id']));
                $modelUnitMeasurement = UnitOfMeasurement::model()->findByPk((int) $uomservice->id);
                if (!empty($modelUnitMeasurement)) { //condition add to solve the erroro empty product id
                    $modelUnitMeasurement->product_id = $model->id;
                    $modelUnitMeasurement->factor = 1;
                    $modelUnitMeasurement->isBase = "Y";
                    $modelUnitMeasurement->name = Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
                    $modelUnitMeasurement->base_unit = $_POST['Store']['unit_id'];
                    $modelUnitMeasurement->created_by = Yii::app()->user->id;
                    $modelUnitMeasurement->created_date_time = date('Y-m-d H:i:s');
                    $modelUnitMeasurement->save(false);
                }
            }

            // inserting to audit log
            AuditLog::saveAuditLogs(
                'SERVICE',
                Yii::app()->user->id,
                $audit_type,
                " with No: - {$model->id} & Part No: - {$_POST['Store']['part_number']}  "
            );
            // end audit log
            // $model->save_ledger();
        } else {
            $error1 = json_decode(CActiveForm::validate($model, '', false), true);
            $error = CJSON::encode($error1);
            if ($error != '[]')
                echo $error;
        }
    }

    public function actionRawMaterial()
    {
        $this->render('raw_material_index');
    }

    public function actionGetRawMaterialList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $display_type = $_POST['display_type'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'part_number',
            1 => 'generic_name',
            2 => 'description',
            3 => 'brand_class_id',
            4 => 'default_warehouse_id',
            5 => 'inventory_item_type',
        );

        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 'isActive="Y" AND type=3';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = "type=3 AND (id LIKE '%" . $searchString . "%' OR part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' OR alias_name LIKE '%" . $searchString . "%') ";
        }

        if ($display_type == 1)
            $condition .= ' AND quantity > 0';

        $query = 'SELECT * FROM view_all_stock_items WHERE ' . $condition . ' LIMIT ' . $limit . ' OFFSET ' . $offset . ' ';
        $count = Yii::app()->db->createCommand('SELECT COUNT(id) FROM view_all_stock_items WHERE ' . $condition . ' ')->queryScalar();
        $model = Yii::app()->db->createCommand($query)->queryAll();

        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();

        foreach ($model as $row) {
            $part_no = $row['part_number'];
            $rowData[] = array($row['id'], $part_no, $row['description'], $row['brand'], (float) $row['quantity'], $row['unit']);
        }

        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionBatchSplit()
    {
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('batch_split_form', array(), false, false);
    }

    public function actionGetProductBatchNo()
    {
        $from = $_GET['frm'];
        $searchTerm = $_GET['term'];
        $productid = $_GET['product_id'];
        $condition = 'product_id="' . $productid . '" AND quantity>0 AND t.batch_no LIKE "%' . $searchTerm . '%"';
        $model = new StockLedger();
        $model = $model->findAll(array('condition' => $condition, 'group' => 'batch_no'));
        $i = 0;
        foreach ($model as $eachModel) {
            $data[$i]['value'] = $eachModel->batch_no;
            $i++;
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }

    public function actionFetchBatchNoItems()
    {
        $product_id = $_POST['product_id'];
        $batchno = $_POST['batchno'];

        $modelStore = Store::model()->findByPk($product_id);
        if ($modelStore->have_serial_no == 'Y') {
            $readonly = true;
        } else {
            $readonly = false;
        }
        $condition = 't.product_id ="' . $product_id . '" AND quantity > 0 AND batch_no="' . $batchno . '"';
        $stock_details = array(new StockLedger);
        if ((int) $product_id > 0) {
            $stock_details = StockLedger::model()->findAll(array('condition' => $condition, 'order' => 'id ASC'));
        }

        $data['table'] = '';
        $data['table'] .= '<table class="table table-hover table-bordered personal-task" id="batchno_split_items_table" style="margin-top : 10px;">
                            <thead>
                                <tr>
                                    <th>Warehoue</th>
                                    <th>Rack</th>
                                    <th>Bin</th>
                                    <th>Qty</th>
                                    <th>Batch</th>
                                    <th>Expiry Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                                <tbody id="tbody_material">';
        if ($stock_details[0]->id > 0) {

            $sno = 1;
            $length = 0;
            $total_qty = 0;
            foreach ($stock_details as $rowitem) {
                $model_wh = MasInventoryWarehouse::model()->findBypk($rowitem->warehouse_id);
                $model_rack = MasInvRack::model()->findBypk($rowitem->rack_id);
                $model_bin = MasInvBin::model()->findBypk($rowitem->bin_id);

                if ($rowitem->expiry_date == '0000-00-00' or $rowitem->expiry_date == '1970-01-01') {
                    $expiry_date = "";
                } else {
                    $expiry_date = date("d/m/Y", strtotime($rowitem->expiry_date));
                }
                $actual_qty = $rowitem->quantity;

                $expiry_date = '';
                if ($rowitem->expiry_date != '0000-00-00' and $rowitem->expiry_date != '1970-01-01') {
                    $expiry_date = date("d/m/Y", strtotime($rowitem->expiry_date));
                }

                //date("d/m/Y",strtotime($row['qtn_start_date']))
                //.CHtml::activeHiddenfield($rowitem, "[" . $length . "]bill_of_entry").
                $data['table'] .= '<tr class="">
                                                <td>' . $model_wh->warehouse_name
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]file_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]header_item_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]customer_vendor_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]customer_vendor_name")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]product_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]product_name")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]product_description")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]brand_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]brand_name")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]warehouse_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]warehouse_name")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rack_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]rack_name")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bin_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]bin_name")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]unit_id")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]unit_name")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]unit_factor")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]available_status")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]serial_no")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]manufacturing_date")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]cost_price")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]sales_price")
                    . CHtml::activeHiddenfield($rowitem, "[" . $length . "]master_stock_ledger_id")
                    . '</td>
                                                <td>' . $model_rack->name . '</td>
                                                <td>' . $model_bin->name . '</td>
                                                <td>' . CHtml::activeTextfield($rowitem, "[" . $length . "]quantity", array('class' => 'form-control', 'readonly' => $readonly)) . '</td>
                                                <td>' . CHtml::activeTextfield($rowitem, "[" . $length . "]batch_no", array('class' => 'form-control')) . '</td>
                                                <td>' . CHtml::activeTextfield($rowitem, "[" . $length . "]expiry_date", array('class' => 'form-control datepicker', 'value' => $expiry_date)) . '</td>
                                                <td>' . CHtml::link('<i class="fa fa-paper-plane-o"></i>', 'javascript:void(0);', array('class' => 'btn btn-sm btn-danger', 'title' => 'Create Next Row', 'onclick' => 'rowSplit($("#batchno_split_items_table"), this,this.id);', 'id' => 'batchsplit_' . $length)) . '</td>
                                           </tr>';
                $length++;
                $total_qty += $rowitem->quantity;
            }
        } else {
            if ($length == 0)
                $data['table'] .= '<tr class="no-data-tr"><td colspan="11" class="text-center"> No Data </td></tr>';
        }
        $data['table'] .= '</tbody></table>';
        $data['total_qty'] = $total_qty;
        echo CJSON::encode($data);
    }

    public function actionSaveBatchSplit()
    {

        $product_id = $_POST['product_id'];
        $batchno = $_POST['batchno'];

        if (!empty($_POST['StockLedger'])) {

            $history = new InventoryBatchSplitHistory();
            $history->product_id = $product_id;
            $history->batch_name = $batchno;
            $history->created_by = Yii::app()->user->id;
            ;
            $history->created_datetime = date('Y-m-d H:i:s');
            $history->save(false);

            // inserting to audit log
            AuditLog::saveAuditLogs(
                'BATCH_SPLIT',
                Yii::app()->user->id,
                'CREATED',
                " with PRDT ID: - {$product_id} - and Batch: - {$batchno}"
            );
            // end audit log

            $condition = 't.product_id ="' . $product_id . '" AND quantity > 0 AND batch_no="' . $batchno . '"';
            $stock_details = StockLedger::model()->findAll(array('condition' => $condition, 'order' => 'id ASC'));
            if (!empty($stock_details)) {
                foreach ($stock_details as $i => $stock_details) {
                    $modelHistory = new InventoryBatchSplitHistoryDetail();
                    $modelHistory->batch_split_history_id = $history->id;
                    $modelHistory->status = "O_UPD";
                    $modelHistory->batch_name = $stock_details->batch_no;
                    $modelHistory->product_location_id = $stock_details->id;
                    $modelHistory->quantity = $stock_details->quantity;
                    $modelHistory->save(false);
                }
            }

            foreach ($_POST['StockLedger'] as $i => $item) {
                $modelStockLedger = new StockLedger;
                if ($item['id'] > 0) {
                    $modelStockLedger = StockLedger::model()->findByPk($item['id']);
                } else {

                    $modelStockLedger->attributes = $_POST['StockLedger'];

                    $modelStockLedger->file_id = $item['file_id'];
                    $modelStockLedger->header_id = $history->id;
                    $modelStockLedger->header_item_id = 0;
                    $modelStockLedger->customer_vendor_id = $item['customer_vendor_id'];
                    $modelStockLedger->customer_vendor_name = $item['customer_vendor_name'];
                    $modelStockLedger->product_id = $item['product_id'];
                    $modelStockLedger->product_name = $item['product_name'];
                    $modelStockLedger->product_description = $item['product_description'];
                    $modelStockLedger->brand_id = $item['brand_id'];
                    $modelStockLedger->brand_name = $item['brand_name'];
                    $modelStockLedger->warehouse_id = $item['warehouse_id'];
                    $modelStockLedger->warehouse_name = $item['warehouse_name'];
                    $modelStockLedger->rack_id = $item['rack_id'];
                    $modelStockLedger->rack_name = $item['rack_name'];
                    $modelStockLedger->bin_id = $item['bin_id'];
                    $modelStockLedger->bin_name = $item['bin_name'];
                    $modelStockLedger->serial_no = trim($item['serial_no']);
                    $modelStockLedger->unit_name = $item['unit_name'];
                    $modelStockLedger->unit_id = $item['unit_id'];
                    $modelStockLedger->cost_price = $item['cost_price'];
                    $modelStockLedger->sales_price = $item['sales_price'];
                    $modelStockLedger->transaction_date = date('Y-m-d');
                    $modelStockLedger->transaction_from = "BATCH_SPLIT";
                    $modelStockLedger->transaction_type = "IN";
                    $modelStockLedger->master_stock_ledger_id = $item['master_stock_ledger_id'];
                    $modelStockLedger->created_by = Yii::app()->user->id;
                    $modelStockLedger->created_date = date('Y-m-d h:i:s');
                    $modelStockLedger->stock_updated = "Y";
                }

                if ($item['expiry_date'] != '00/00/0000' and $item['expiry_date'] != '01/01/1970') {
                    $expiry_date = str_replace('/', '-', $item['expiry_date']);
                    $expiry_date = date("Y-m-d", strtotime($expiry_date));
                }
                $modelStockLedger->quantity = $item['quantity'];
                $modelStockLedger->batch_no = $item['batch_no'];
                $modelStockLedger->expiry_date = $expiry_date;
                $modelStockLedger->save(false);

                $modelHistory = new InventoryBatchSplitHistoryDetail();
                $modelHistory->batch_split_history_id = $history->id;
                $modelHistory->status = "N_ADD";
                $modelHistory->batch_name = $item['batch_no'];
                $modelHistory->product_location_id = $modelStockLedger->id;
                $modelHistory->quantity = $item['quantity'];
                $modelHistory->save(false);
            }


            $jsonData['status'] = 'success';
            echo CJSON::encode($jsonData);
        }
    }

    public function actionCheckProductInQC()
    {
        $from = $_GET['frm'];

        $product_id = $_POST['product_id'];
        if ($product_id > 0) {

            $sql = "SELECT
                      COUNT(*)
                    FROM
                      erp_purchasing_material_receipt_item AS MRI
                    LEFT JOIN
                      erp_purchasing_material_receipt AS MR ON MR.`id` = MRI.`purchasing_materialreceipt_id`
                    LEFT JOIN
                      erp_master_file AS FILE ON FILE.`id` = MR.`file_id`
                    WHERE
                      MRI.product_id = " . $product_id . " AND(
                        FILE.current_process_status = 'Q_C' OR FILE.current_process_status = 'M_R'
                      )";

            $command = Yii::app()->db->createCommand($sql);

            $count = $command->queryScalar();
            $jsonData['status'] = 'success';
            $jsonData['count'] = $count;
        } else {
            $jsonData['status'] = 'error';
        }
        echo CJSON::encode($jsonData);
    }

    public function actionGetSearchServiceItems()
    {
        $from = $_GET['frm'];
        $searchTerm = $_GET['term'];
        $condition = '(part_number LIKE "%' . $searchTerm . '%" OR description LIKE "%' . $searchTerm . '%") AND inventory_item_type=2';
        $model = new Store();
        $model = $model->with('tax')->findAll(array('select' => 'id,part_number,description,unit_id,inventory_item_type', 'condition' => $condition, 'limit' => 200));
        $i = 0;
        foreach ($model as $eachModel) {
            $data[$i]['value'] = $eachModel->id;
            $data[$i]['label'] = $eachModel->part_number . ' : ' . $eachModel->description;
            $data[$i]['part_number'] = $eachModel->part_number;
            $data[$i]['description'] = $eachModel->description;
            $data[$i]['unit_id'] = $eachModel->unit->id;
            $data[$i]['unit_name'] = $eachModel->unit->symbol;
            $data[$i]['tax_code'] = $eachModel->tax;
            $data[$i]['part_no'] = $eachModel->part_number;
            $data[$i]['other'] = $eachModel->inventory_item_type;
            $i++;
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }

    public function actionLoadsalepurchaseHistory()
    {
        $type = (int) Yii::app()->request->getParam('type');
        $product_id = (int) Yii::app()->request->getParam('product_id');
        $customer_vendor_id = (int) Yii::app()->request->getParam('customer_vendor_id');
        if ($type == 1) {
            $this->renderPartial('get_sale_history', array('product_id' => $product_id, 'customer_id' => $customer_vendor_id), false, true);
        } else if ($type == 2) {
            $this->renderPartial('get_purchase_history', array('product_id' => $product_id, 'vendor_id' => $customer_vendor_id), false, true);
        } else if ($type == 3) {
            $this->renderPartial('get_quote_rate_details', array('product_id' => $product_id, 'customer_id' => $customer_vendor_id), false, true);
        }
    }

    public function actionGetAvaibaleQty()
    {
        $product_id = (int) $_POST['id'];
        $type = $_POST['type'];
        $availble_qty = 0;
        $availble_qty = Yii::app()->db->createCommand('SELECT SUM(quantity) as availble_qty FROM `view_all_stock_items` WHERE id=' . $product_id . ' GROUP BY id')->queryScalar();
        echo "<span style='color:red;'><b>" . Yii::app()->numberFormatter->formatCurrency($availble_qty, "") . "</b></span>";
        //echo "<span class='sh-close' onclick='$(\"#stockhelper\").hide();'><i class='fa fa-times'></i></span><b>Available Qty: <span style='color:red;'>".Yii::app()->numberFormatter->formatCurrency($availble_qty,"")."</span></b>";
        Yii::app()->end();
    }

    public function actionGetSerialNoList()
    {
        $model = new StockLedger();
        $id = (int) Yii::app()->request->getParam('id');

        if ($id > 0) {
            $condition = 'product_id =    "' . $id . '" AND quantity>0 AND available_status="A" AND stock_updated="Y"';
            $model = StockLedger::model()->with('warehouse')->findAll(array('condition' => $condition));
        }

        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('edit_serial_no', array('model' => $model, 'product_id' => $id), false, false);
    }

    public function actionChangeSerialNo()
    {
        $db_flag = 0;

        if (is_array($_POST['StockLedger'])) {
            $arr_serial_exist_product = array();
            foreach ($_POST['StockLedger'] as $i => $item) {
                //echo "id=".$item['id']."=>".$item['serial_no']."<br>";
                if ($item['id'] > 0) {
                    $condition = "product_location_id=" . $item['id'];
                    $arr_serial_no_exist = StockLedger::model()->find(array('condition' => 'serial_no="' . trim($item['serial_no'] . '" AND product_id=' . trim($item['product_id']) . ' AND id<>' . $item['id'])));
                    if (count($arr_serial_no_exist) == 0) {
                        StockLedger::model()->updateByPk($item['id'], array('serial_no' => trim($item['serial_no'])));
                    } else {
                        $arr_serial_exist_product[] = $item['serial_no'];
                    }
                }
            }
            if (count($arr_serial_exist_product) > 0) {
                $jsonData['status'] = 'error';
                $jsonData['serial_no'] = implode(',', $arr_serial_exist_product);
            } else {
                $jsonData['status'] = 'success';
            }

            echo CJSON::encode($jsonData);
        }
    }

    public function actionGetLocationDetails()
    {
        $product_id = (int) $_POST['id'];
        $this->renderPartial('location_details', array('id' => $product_id), false, true);
    }

    public function actionGetdemoPartnumber()
    {
        $brand_id = (int) $_POST['brand_id'];
        $machine_type = $_POST['mc_type'];
        $part_no = '-';
        if ($brand_id > 0) {
            $model_max_partnumber = Store::model()->find(array('select' => 'max(id) as id', 'condition' => 'inventory_item_type="1" and brand_class_id="' . $brand_id . '"'));
            if ($model_max_partnumber->id != '') {
                $model_existing_part_no = Store::model()->findByPk($model_max_partnumber->id);
                $existing_part_no = explode('-', $model_existing_part_no->part_number);
                $part_number_new = $existing_part_no[2] + 1;
                if ($part_number_new <= 99999) {
                    $part_number_new = str_pad($part_number_new, 5, "0", STR_PAD_LEFT);
                }
            } else {
                $part_number_new = '00001';
            }
            $model_brand_class = MasInvBrand::model()->findByPk($brand_id);
            $part_no = '';
            if ($model_brand_class->id > 0) {
                $value_machine_type = ($machine_type == 'M') ? '02' : '04';
                $brand_class_auto_generated_no = 0;
                if (count($model_brand_class->auto_generated_no) == 1) {
                    $brand_class_auto_generated_no = str_pad($model_brand_class->auto_generated_no, 2, "0", STR_PAD_LEFT);
                } else {
                    $brand_class_auto_generated_no = $model_brand_class->auto_generated_no;
                }
                $part_no = $brand_class_auto_generated_no . '-' . $value_machine_type . '-' . $part_number_new;
            }
        }
        $jsonData['part_number'] = $part_no;
        $jsonData['status'] = 'success';
        echo CJSON::encode($jsonData);
    }

    public function actionGetMachineOnly()
    {
        $searchTerm = $_GET['term'];
        $condition = '(t.part_number LIKE "%' . $searchTerm . '%" OR t.description LIKE "%' . $searchTerm . '%") AND t.machine_type="M"';
        $model = Store::model()->findAll(array('select' => 'id,hiring_part_number,description', 'condition' => $condition, 'limit' => 200));
        $data = array();
        foreach ($model as $i => $eachModel) {
            $data[$i]['value'] = $eachModel->id;
            $data[$i]['label'] = $eachModel->description;
            $i++;
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }

    public function actionMemo()
    {
        $this->render('memo_index');
    }

    public function actionGetMemoList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'part_number',
            1 => 'description',
            2 => 'inventory_item_type'
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.isActive="Y" AND inventory_item_type=3';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = "inventory_item_type=3 AND ( part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' )";
        }

        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        foreach ($model as $m => $row) {
            $rowData[] = array($m + 1, $row['part_number'], $row['description'], $row['id']);
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionSaveMemo()
    {
        $model = new Store();
        $scenario = '';
        if ((int) $_POST['Store']['id'] > 0) {
            $id = $_POST['Store']['id'];
            $model = $model->findByPk($id);
            $model->updated_by = Yii::app()->user->id;
            $model->updated_date_time = date('Y-m-d h:i:s');
            $scenario = 'update';
            $audit_type = 'UPDATED';
            $edit_flag = 1;
        } else {
            $model->created_by = Yii::app()->user->id;
            $model->created_date_time = date('Y-m-d h:i:s');
            $model->scenario = 'add';
            $scenario = 'add';
            $audit_type = 'CREATED';
        }
        $model->attributes = $_POST['Store'];
        $model->inventory_item_type = 3;  //Memo
        $model->purchase_from = "L";
        $model->tax_code = 0;
        $model->unit_id = 0;
        if ($model->validate()) {
            $jsonData['status'] = 'success';
            echo CJSON::encode($jsonData);
            $model->save();

            // inserting to audit log
            AuditLog::saveAuditLogs(
                'SERVICE',
                Yii::app()->user->id,
                $audit_type,
                " with No: - {$model->id} & Part No: - {$_POST['Store']['part_number']}  "
            );
            // end audit log
        } else {
            $error1 = json_decode(CActiveForm::validate($model, '', false), true);
            $error = CJSON::encode($error1);
            if ($error != '[]')
                echo $error;
        }
    }

    public function actionDummy()
    {
        $this->render('dummy_index');
    }

    public function actionGetDummyList()
    {
        $model = new Store();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'part_number',
            1 => 'description',
            2 => 'inventory_item_type'
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.isActive="Y" AND inventory_item_type=4';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = trim($_POST['search']['value']);
            $condition = "inventory_item_type=4 AND ( part_number LIKE '%" . $searchString . "%' OR description LIKE '%" . $searchString . "%' )";
        }

        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $orderBy));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        foreach ($model as $m => $row) {
            $rowData[] = array($m + 1, $row['part_number'], $row['description'], $row['id']);
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionSaveDummy()
    {
        $model = new Store();
        $scenario = '';
        if ((int) $_POST['Store']['id'] > 0) {
            $id = $_POST['Store']['id'];
            $model = $model->findByPk($id);
            $model->updated_by = Yii::app()->user->id;
            $model->updated_date_time = date('Y-m-d h:i:s');
            $scenario = 'update';
            $audit_type = 'UPDATED';
            $edit_flag = 1;
        } else {
            $model->created_by = Yii::app()->user->id;
            $model->created_date_time = date('Y-m-d h:i:s');
            $model->scenario = 'add';
            $scenario = 'add';
            $audit_type = 'CREATED';
        }
        $model->attributes = $_POST['Store'];
        $model->inventory_item_type = 4;  //Dummy
        $model->purchase_from = "L";
        if ($model->validate()) {
            $jsonData['status'] = 'success';
            echo CJSON::encode($jsonData);
            $model->save();
            if (!empty($_POST['Store']['unit_id']) && (int) $_POST['Store']['id'] == 0) {
                $modelUnitMeasurement = new UnitOfMeasurement();
                $modelUnitMeasurement->product_id = $model->id;
                $modelUnitMeasurement->factor = 1;
                $modelUnitMeasurement->isBase = "Y";
                $modelUnitMeasurement->name = Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
                $modelUnitMeasurement->base_unit = $_POST['Store']['unit_id'];
                $modelUnitMeasurement->created_by = Yii::app()->user->id;
                $modelUnitMeasurement->created_date_time = date('Y-m-d H:i:s');
                $modelUnitMeasurement->save(false);
            } else if (!empty($_POST['Store']['unit_id']) && (int) $_POST['Store']['id'] > 0) {
                $uomservice = UnitOfMeasurement::model()->find(array('condition' => 'product_id=' . $_POST['Store']['id']));
                if (empty($uomservice)) {
                    $modelUnitMeasurement = new UnitOfMeasurement();
                } else
                    $modelUnitMeasurement = UnitOfMeasurement::model()->findByPk($uomservice->id);
                $modelUnitMeasurement->product_id = $model->id;
                $modelUnitMeasurement->factor = 1;
                $modelUnitMeasurement->isBase = "Y";
                $modelUnitMeasurement->name = Unit::model()->findByPk($_POST['Store']['unit_id'])->symbol;
                $modelUnitMeasurement->base_unit = $_POST['Store']['unit_id'];
                $modelUnitMeasurement->created_by = Yii::app()->user->id;
                $modelUnitMeasurement->created_date_time = date('Y-m-d H:i:s');
                $modelUnitMeasurement->save(false);
            }


            // inserting to audit log
            AuditLog::saveAuditLogs(
                'DUMMY',
                Yii::app()->user->id,
                $audit_type,
                " with No: - {$model->id} & Part No: - {$_POST['Store']['part_number']}  "
            );
            // end audit log
        } else {
            $error1 = json_decode(CActiveForm::validate($model, '', false), true);
            $error = CJSON::encode($error1);
            if ($error != '[]')
                echo $error;
        }
    }

    public function actionGetPurchaseHistoryList()
    {
        $product_id = (int) Yii::app()->request->getParam('id');

        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->renderPartial('get_purchase_history_list', array('product_id' => $product_id), false, true);
    }

    public function actionApproveInventoryItem()
    {
        $product_id = (int) Yii::app()->request->getParam('id');
        if ($product_id > 0) {
            Store::model()->updateByPK($product_id, array('isActive' => 'Y'));
            $data['status'] = 'success';
        } else {
            $data['status'] = 'failed';
        }

        echo json_encode($data);
    }

    public function actionViewExpiryList()
    {
        $product_id = (int) Yii::app()->request->getParam('id');
        $condition = 't.product_id ="' . $product_id . '" AND quantity > 0';
        $stock_details = array(new StockLedger);
        if ((int) $product_id > 0) {
            $stock_details = StockLedger::model()->findAll(array('condition' => $condition, 'order' => 'expiry_date ASC'));
        }

        $this->render('view_expiry_list', array('arr_stock_details' => $stock_details));
    }

    public function actionAllocateMaterials()
    {
        $allocated_from = Yii::app()->request->getParam('frm');
        $header_id = (int) Yii::app()->request->getParam('id');
        $file_id = (int) Yii::app()->request->getParam('file_id');

        $modelAllocatedMaterial = new AllocatedMaterial();

        $SQL = 'SELECT GROUP_CONCAT(product_id) as product_ids FROM `erp_allocated_materials` WHERE header_id=' . $header_id;
        //echo $query;
        $allocate_products = Yii::app()->db->createCommand($SQL)->queryRow();

        $arr_product_ids = explode(",", $allocate_products['product_ids']);

        $cnt_allocated = (int) Yii::app()->db->createCommand('SELECT COUNT(id) FROM erp_allocated_materials  WHERE header_id=' . $header_id)->queryScalar();

        $arr_product_details = array();
        //echo $header_id;
        if ($allocated_from == 'Q') {
            $modelQuotesItem = new QuotesItem();
            $modelQuotesItem = $modelQuotesItem->findAll(array('condition' => 'quotes_id=' . $header_id, 'order' => 't.id'));

            $i = 0;
            foreach ($modelQuotesItem as $eachItem) {
                if ($eachItem->product->inventory_item_type == 1) {
                    $arr_product_details[$i]['product_id'] = $eachItem->product_id;
                    $arr_product_details[$i]['part_number'] = $eachItem->product->part_number;
                    $arr_product_details[$i]['description'] = $eachItem->description;
                    $arr_product_details[$i]['file_id'] = $eachItem->quotes->file_id;
                    $arr_product_details[$i]['header_id'] = $header_id;
                    $arr_product_details[$i]['warehouse_id'] = 0;
                    $arr_product_details[$i]['quantity'] = $eachItem->quantity;
                    $arr_product_details[$i]['allocation_start_date'] = date('d/m/Y');
                    $arr_product_details[$i]['allocation_end_date'] = date('d/m/Y', strtotime($eachItem->quotes->qtn_validity));
                    if (in_array($eachItem->product_id, $arr_product_ids)) {
                        $arr_product_details[$i]['checked'] = 1;
                    } else {
                        $arr_product_details[$i]['checked'] = 0;
                    }
                    $i++;
                }
            }
        } else {
            $modelOrderItem = new OrderItem();
            $modelOrderItem = $modelOrderItem->findAll(array('condition' => 'order_id=' . $header_id, 'order' => 't.id'));
            $i = 0;
            foreach ($modelOrderItem as $eachItem) {
                if ($eachItem->product->inventory_item_type == 1) {
                    $arr_product_details[$i]['product_id'] = $eachItem->product_id;
                    $arr_product_details[$i]['part_number'] = $eachItem->product->part_number;
                    $arr_product_details[$i]['description'] = $eachItem->description;
                    $arr_product_details[$i]['file_id'] = $eachItem->order->file_id;
                    $arr_product_details[$i]['header_id'] = $header_id;
                    $arr_product_details[$i]['warehouse_id'] = 0;
                    $arr_product_details[$i]['quantity'] = $eachItem->quantity;
                    $arr_product_details[$i]['allocation_start_date'] = date('d/m/Y');
                    $arr_product_details[$i]['allocation_end_date'] = date('d/m/Y', strtotime($eachItem->order->delivery_date));
                    if (in_array($eachItem->product_id, $arr_product_ids)) {
                        $arr_product_details[$i]['checked'] = 1;
                    } else {
                        $arr_product_details[$i]['checked'] = 0;
                    }
                    $i++;
                }
            }
        }

        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('view_allocation_details', array('allocated_from' => $allocated_from, 'header_id' => $header_id, 'arr_product_details' => $arr_product_details, 'file_id' => $file_id, 'cnt_allocated' => $cnt_allocated));
    }

    public function actionSaveAllocateMaterial()
    {

        AllocatedMaterial::model()->deleteAll('header_id=:refer_id', array(':refer_id' => $_POST['header_id']));

        foreach ($_POST['AllocatedMaterial'] as $i => $eachItem) {

            if (isset($_POST['checkproducts_' . $i]) && $_POST['checkproducts_' . $i] != "") {
                $allocation_start_date = "0000-00-00";
                if ($eachItem['allocation_date'] != '') {
                    $allocation_start_date = str_replace('/', '-', $eachItem['allocation_date']);
                    $allocation_start_date = date("Y-m-d", strtotime($allocation_start_date));
                }
                $allocation_end_date = "0000-00-00";
                if ($eachItem['allocation_end_date'] != '') {
                    $allocation_end_date = str_replace('/', '-', $eachItem['allocation_end_date']);
                    $allocation_end_date = date("Y-m-d", strtotime($allocation_end_date));
                }

                if ($eachItem['quantity'] > 0) {
                    $modelAllocatedMaterial = new AllocatedMaterial();
                    $modelAllocatedMaterial->product_id = $eachItem['product_id'];
                    $modelAllocatedMaterial->file_id = $eachItem['file_id'];
                    $modelAllocatedMaterial->header_id = $eachItem['header_id'];
                    $modelAllocatedMaterial->quantity = $eachItem['quantity'];
                    $modelAllocatedMaterial->allocation_date = $allocation_start_date;
                    $modelAllocatedMaterial->allocation_end_date = $allocation_end_date;
                    $modelAllocatedMaterial->allocated_from = Yii::app()->user->id;
                    $modelAllocatedMaterial->created_by = Yii::app()->user->id;
                    $modelAllocatedMaterial->created_datetime = date('Y-m-d H:i:s');

                    $modelAllocatedMaterial->save(false);
                }
            }
        }
        $jsonData['status'] = 'success';
        echo CJSON::encode($jsonData);

        //
    }

    /* Created By Jisha on 10/05/2022 for blocking inventory items */

    public function actionBlockInventoryItem()
    {
        $product_id = (int) Yii::app()->request->getParam('id');
        if ($product_id > 0) {
            Store::model()->updateByPK($product_id, array('isActive' => 'N'));
            $data['status'] = 'success';
        } else {
            $data['status'] = 'failed';
        }

        echo json_encode($data);
    }

    public function actionDeleteUOMItem()
    {
        $uom_id = (int) Yii::app()->request->getParam('id');
        $sales_price_group_id = (int) Yii::app()->request->getParam('sales_price_group_id');
        $qtn_count = (int) QuotesItem::model()->count(array('condition' => 'unit_id=' . $uom_id));
        $order_count = (int) OrderItem::model()->count(array('condition' => 'unit_id=' . $uom_id));
        $delivery_count = (int) DeliveryNoteItem::model()->count(array('condition' => 'unit=' . $uom_id));
        $invoice_count = (int) InvoiceItem::model()->count(array('condition' => 'unit_id=' . $uom_id));

        $enquiry_count = (int) PurchasingEnquiryStockItem::model()->count(array('condition' => 'stock_item_unit=' . $uom_id));
        $po_count = (int) PurchasingOrderStockItem::model()->count(array('condition' => 'stock_item_unit=' . $uom_id));
        $mr_count = (int) PurchasingMaterialreceiptItem::model()->count(array('condition' => 'unit_id=' . $uom_id));
        $po_invoice_count = (int) PurchasingInvoiceItem::model()->count(array('condition' => 'unit=' . $uom_id));

        $stock_ledger_count = (int) StockLedger::model()->count(array('condition' => 'unit_id=' . $uom_id));

        if ($qtn_count == 0 && $order_count == 0 && $delivery_count == 0 && $invoice_count == 0 && $enquiry_count == 0 && $po_count == 0 && $mr_count == 0 && $po_invoice_count == 0 && $stock_ledger_count == 0) {
            if ($uom_id > 0) {
                $modelUnitOfMeasurement = new UnitOfMeasurement();
                $modelUnitOfMeasurement->deleteByPk($uom_id);
            }
            if ($sales_price_group_id > 0) {
                $modelSalesPriceGroup = new SalesPriceGroup();
                $modelSalesPriceGroup->deleteByPk($sales_price_group_id);
            }

            $data['status'] = 'success';
        } else {
            $data['status'] = 'failed';
        }
        echo json_encode($data);
    }

    public function actionPrintInventoryBarcode()
    {
        $product_id = (int) Yii::app()->request->getParam('id');
        $head_id = (int) Yii::app()->request->getParam('head_id');
        $model = new Store();
        $model = $model->findByPk($product_id);
        $barcode = $model->bar_code;
        $mPDF1 = Yii::app()->ePdf->mpdf('', 'A11');

        /* $stylesheet = file_get_contents(Yii::getPathOfAlias('webroot.css') . '/pdf_style.css');
          $mPDF1->WriteHTML($stylesheet, 1); */
        $mPDF1->WriteHTML($this->renderPartial('application.views.front.pdf.inventory_barcode', array('model' => $model, 'id' => $product_id, 'barcode' => $barcode, 'head_id' => $head_id, 'mpdf' => $mPDF1), true));

        $mPDF1->Output("INVENTORY_" . $product_id . ".pdf", 'I');
    }

    public function actionGetWarehouseProduct()
    {
        $warehouse_id = (int) Yii::app()->request->getParam('warehouse_id');
        $from = $_GET['frm'];
        $searchTerm = $_GET['term'];
        $condition = 'isActive="Y" AND (part_number LIKE "%' . $searchTerm . '%" OR description LIKE "%' . $searchTerm . '%")';
        $model = new Store();
        $model = $model->findAll(array('select' => 'id, part_number, description', 'condition' => $condition, 'limit' => 200));
        $i = 0;
        foreach ($model as $eachModel) {
            $availble_qty = Yii::app()->db->createCommand('SELECT IFNULL(SUM(quantity*unit_factor),0) as availble_qty FROM `erp_stock_ledger` WHERE product_id=' . $eachModel->id . ' AND warehouse_id=' . (int) $warehouse_id)->queryScalar();
            $data[$i]['value'] = $eachModel->part_number;
            $data[$i]['label'] = $eachModel->part_number . ' : ' . $eachModel->description;
            $data[$i]['product_id'] = $eachModel->id;
            $data[$i]['quantity'] = $availble_qty;
            $i++;
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }

    public function actionSelectBarcodeHeading()
    {
        $product_id = (int) Yii::app()->request->getParam('id');
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('select_barcode_heading', array('product_id' => $product_id), false, false);
    }
    public function actionUploadInventoryList()
    {
        $model = new Store();
        $inventory_item_type = (int) Yii::app()->request->getParam('inventory_item_type');
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->render('upload_inventory_list', array('model' => $model, 'inventory_item_type' => $inventory_item_type), false, false);
    }

    public function actionDownloadInventoryListFormat()
    {
        $filename = 'inventory_list.csv';
        header("Content-type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
        //  echo "Part No,Bar Code,Description,Brand,Category,Unit,Secondary Unit,Secondary Unit Factor,Kitchen Location,Sales Price\n";
        echo "Part No,Bar Code,Description,Brand,Category,Unit1,Sales Price1,Unit2,Unit Factor2,Sales Price2,Unit3,Unit Factor3,Sales Price3\n";
        Yii::app()->end();
    }

    public function actionSaveUploadInventoryList()
    {
        $file_name = Yii::app()->request->getParam('filename');
        $inventory_item_type = Yii::app()->request->getParam('inventory_item_type');

        $url = Yii::app()->basePath . '/../uploads/inventorylist_csv/' . $file_name;
        $error_url = Yii::app()->basePath . '/../uploads/inventorylist_csv/error/' . $file_name;
        $file = fopen($url, "r");
        $data = fgetcsv($file);
        $validate = TRUE;
        $partno_error = array();
        $check_list[] = array();
        $partno_list = array();

        $inventory_list = $this->readInventoryListCSV("uploads/inventorylist_csv/" . $file_name);

        foreach (array_slice($inventory_list, 1) as $i => $data) {
            $partno_list[$i] = trim($data[0]);
        }
        $conflictingBarcodes[] = array();
        $conflictingPartNumber[] = array();
        $conflictinggroupname[] = array();

        foreach (array_slice($inventory_list, 1) as $i => $data) {
            if (!empty($data)) {

                $partNumber = $this->sanitizeData($data[0]);
                $BarCode = $this->sanitizeData($data[1]);
                $description = $this->sanitizeData($data[2]);
                $brand = $this->sanitizeData($data[3]);
                $category = $this->sanitizeData($data[4]);
                $unit = $this->sanitizeData($data[5]);
                $sales_price = $this->sanitizeNmber($data[6]);
                $unit2 = $this->sanitizeData($data[7]);
                $unit_factor2 = $this->sanitizeNmber($data[8]);
                $sales_price2 = $this->sanitizeNmber($data[9]);
                $unit3 = $this->sanitizeData($data[10]);
                $unit_factor3 = $this->sanitizeNmber($data[11]);
                $sales_price3 = $this->sanitizeNmber($data[12]);


                $model_store[$i] = new Store();
                if (!empty($partNumber)) {
                    $model_store[$i]['part_number'] = $partNumber;
                } else {
                    $model_store[$i]['part_number'] = '';
                }
                $partno_error[$i] = $model_store[$i]['part_number'];

                if (!empty($BarCode)) {
                    $model_store[$i]['bar_code'] = $BarCode;
                } else {
                    $model_store[$i]['bar_code'] = '';
                }


                //  $model_store[$i]['bar_code'] = $model_store[$i]['part_number'];

                if (!empty($description)) {
                    $model_store[$i]['description'] = $description;
                } else {
                    $model_store[$i]['description'] = '';
                }

                if (!empty($brand)) {
                    $condition = 'product_class  ="' . $brand . '"';
                    $model_store[$i]['brand_class_id'] = ProductClass::model()->find(array('select' => 'id', 'condition' => $condition))->id;
                    if (empty($model_store[$i]['brand_class_id'])) {
                        $model_store[$i]['brand_class_id'] = '';
                    }
                } else {
                    $model_store[$i]['brand_class_id'] = '';
                }

                if (!empty($category)) {
                    $condition = 'generic_name  ="' . $category . '"';
                    $model_store[$i]['generic_id'] = MasGeneric::model()->find(array('select' => 'id', 'condition' => $condition))->id;
                    if (empty($model_store[$i]['generic_id'])) {
                        $model_store[$i]['generic_id'] = '';
                    }
                } else {
                    $model_store[$i]['generic_id'] = '';
                }

                if (!empty($unit)) {
                    $condition = 'unit_name  ="' . $unit . '"';
                    $model_store[$i]['unit_id'] = Unit::model()->find(array('select' => 'id', 'condition' => $condition))->id;
                    if (empty($model_store[$i]['unit_id'])) {
                        $model_store[$i]['unit_id'] = '';
                    }
                } else {
                    $model_store[$i]['unit_id'] = '';
                }


                $model_store[$i]['warehouse_id'] = MasInventoryWarehouse::model()->findByAttributes(['isBaseWareHouse' => "Y"])->id;

                $model_store[$i]['tax_code'] = 1;


                if (!empty($sales_price)) {
                    $model_store[$i]['selling_price_1'] = $sales_price;
                } else {
                    $model_store[$i]['selling_price_1'] = '';
                }

                if (!empty($sales_price2)) {
                    $model_store[$i]['selling_price_2'] = $sales_price2;
                } else {
                    $model_store[$i]['selling_price_2'] = '';
                }

                $unitid = $model_store[$i]['unit_id'];
                $model_store[$i]['inventory_item_type'] = ((int) $inventory_item_type > 0) ? $inventory_item_type : 1;
                $model_store[$i]['purchase_from'] = 'L';
                $model_store[$i]['rack_id'] = 1;
                $model_store[$i]['bin_id'] = 1;
                $model_store[$i]['created_by'] = Yii::app()->user->id;
                $model_store[$i]['created_date_time'] = date('Y-m-d H:i:s');
                // ---------------------------------------------
                $model_store[$i]['unit2'] = $unit2;
                $model_store[$i]['unit_factor2'] = $unit_factor2;
                $model_store[$i]['unit3'] = $unit3;
                $model_store[$i]['unit_factor3'] = $unit_factor3;
                $model_store[$i]['sales_price3'] = $sales_price3;
                // ---------------------------------------------


                $validate = $model_store[$i]->validate() && $validate;
            }
        }
        function array_not_unique($raw_array)
        {
            $dupes = array();
            natcasesort($raw_array);
            reset($raw_array);

            $old_key = NULL;
            $old_value = NULL;
            foreach ($raw_array as $key => $value) {
                if ($value === NULL) {
                    continue;
                }
                if ($old_value != NULL) {
                    if (strcasecmp($old_value, $value) === 0) {
                        $dupes[$old_key] = $old_value;
                        $dupes[$key] = $value;
                    }
                }
                $old_value = $value;
                $old_key = $key;
            }
            return $dupes;
        }
        // $barcode_common = array_not_unique($barcode_error);
        $partno_common = array_not_unique($partno_error);
        if (!empty($partno_common)) {
            $validate = false;
        }



        if ($validate) {
            $jsonData['status'] = "success";
            if (!empty($model_store)) {
                foreach ($model_store as $eachModel) {
                    $eachModel->save(false);
                    $eachModel->refresh();
                    // $product_id = $eachModel->id;
                    $unitid = $eachModel->unit_id;
                    $modelunit = new Unit();
                    $modelunit = $modelunit->findByPk((int) $unitid);
                    $modeluom = new UnitOfMeasurement();
                    $modeluom->product_id = (int) $eachModel->id;
                    $modeluom->base_unit = (int) $eachModel->unit_id;
                    $modeluom->unit_id = (int) $eachModel->unit_id;
                    $modeluom->name = $modelunit->symbol;
                    $modeluom->factor = 1;
                    $modeluom->price = $eachModel->selling_price_1;
                    $modeluom->isBase = 'Y';
                    $modeluom->created_by = Yii::app()->user->id;
                    $modeluom->created_date_time = date('Y-m-d H:i:s');
                    $modeluom->save(false);
                    // --------------------------------------
                    $store = new Store();
                    $store->updateByPk($eachModel->id, array('default_sales_unit_id' => $modeluom->id, 'default_purchase_unit_id' => $modeluom->id));
                    // --------------------------------------


                    $modelSalesPriceGroup = new SalesPriceGroup();
                    $modelSalesPriceGroup->product_id = (int) $eachModel->id;
                    $modelSalesPriceGroup->pricing_group_id = 1;
                    $modelSalesPriceGroup->product_name = $eachModel->part_number;
                    $modelSalesPriceGroup->sales_price = $eachModel->selling_price_1;
                    $modelSalesPriceGroup->mas_unit_id = $unitid;
                    $modelSalesPriceGroup->uom_id = $modeluom->id;
                    $modelSalesPriceGroup->unit_name = $modeluom->name;
                    $modelSalesPriceGroup->created_by = Yii::app()->user->id;
                    $modelSalesPriceGroup->created_date_time = date('Y-m-d H:i:s');
                    $modelSalesPriceGroup->save(false);

                    if (!empty($eachModel->unit2)) {

                        $conditionunit2 = 'unit_name  ="' . $eachModel->unit2 . '"';
                        $unit_id2 = Unit::model()->find(array('select' => 'id', 'condition' => $conditionunit2))->id;
                        if ((int) $unit_id2 <= 0) {
                            $unit_id2 = 0;
                        }

                        if ((int) $unit_id2 > 0) {
                            $modelunit = new Unit();
                            $modelunit = $modelunit->findByPk((int) $unit_id2);
                            $modeluom2 = new UnitOfMeasurement();
                            $modeluom2->product_id = (int) $eachModel->id;
                            $modeluom2->base_unit = (int) $eachModel->unit_id;
                            $modeluom2->unit_id = (int) $unit_id2;
                            $modeluom2->name = $modelunit->symbol;
                            $modeluom2->factor = ($eachModel->unit_factor2 > 0) ? $eachModel->unit_factor2 : 1;
                            $modeluom2->price = $eachModel->selling_price_2;
                            $modeluom2->created_by = Yii::app()->user->id;
                            $modeluom2->created_date_time = date('Y-m-d H:i:s');
                            $modeluom2->save(false);


                            $modelSalesPriceGroup2 = new SalesPriceGroup();
                            $modelSalesPriceGroup2->product_id = (int) $eachModel->id;
                            $modelSalesPriceGroup2->pricing_group_id = 1;
                            $modelSalesPriceGroup2->product_name = $eachModel->part_number;
                            $modelSalesPriceGroup2->sales_price = $eachModel->selling_price_2;
                            $modelSalesPriceGroup2->mas_unit_id = $unit_id2;
                            $modelSalesPriceGroup2->uom_id = $modeluom2->id;
                            $modelSalesPriceGroup2->unit_name = $modeluom2->name;
                            $modelSalesPriceGroup2->created_by = Yii::app()->user->id;
                            $modelSalesPriceGroup2->created_date_time = date('Y-m-d H:i:s');
                            $modelSalesPriceGroup2->save(false);
                        }
                    }
                    if (!empty($eachModel->unit3)) {

                        $conditionunit3 = 'unit_name  ="' . $eachModel->unit3 . '"';
                        $unit_id3 = Unit::model()->find(array('select' => 'id', 'condition' => $conditionunit3))->id;
                        if ((int) $unit_id3 <= 0) {
                            $unit_id3 = 0;
                        }

                        if ((int) $unit_id3 > 0) {
                            $modelunit = new Unit();
                            $modelunit = $modelunit->findByPk((int) $unit_id3);
                            $modeluom3 = new UnitOfMeasurement();
                            $modeluom3->product_id = (int) $eachModel->id;
                            $modeluom3->base_unit = (int) $eachModel->unit_id;
                            $modeluom3->unit_id = (int) $unit_id3;
                            $modeluom3->name = $modelunit->symbol;
                            $modeluom3->factor = ($eachModel->unit_factor3 > 0) ? $eachModel->unit_factor3 : 1;
                            $modeluom3->price = $eachModel->sales_price3;
                            $modeluom3->created_by = Yii::app()->user->id;
                            $modeluom3->created_date_time = date('Y-m-d H:i:s');
                            $modeluom3->save(false);


                            $modelSalesPriceGroup3 = new SalesPriceGroup();
                            $modelSalesPriceGroup3->product_id = (int) $eachModel->id;
                            $modelSalesPriceGroup3->pricing_group_id = 1;
                            $modelSalesPriceGroup3->product_name = $eachModel->part_number;
                            $modelSalesPriceGroup3->sales_price = $eachModel->sales_price3;
                            $modelSalesPriceGroup3->mas_unit_id = $unit_id3;
                            $modelSalesPriceGroup3->uom_id = $modeluom3->id;
                            $modelSalesPriceGroup3->unit_name = $modeluom3->name;
                            $modelSalesPriceGroup3->created_by = Yii::app()->user->id;
                            $modelSalesPriceGroup3->created_date_time = date('Y-m-d H:i:s');
                            $modelSalesPriceGroup3->save(false);
                        }
                    }
                }
                $jsonData['error'] = "";
            }
        } else {
            if (!empty($model_store)) {
                foreach (array_slice($inventory_list, 1) as $s => $data) {
                    if (!empty($data)) {
                        $error_list[$s]['part_number'] = $data[0];
                        $error_list[$s]['bar_code'] = $data[1];
                        $error_list[$s]['description'] = $data[2];
                        $error_list[$s]['brand_class_id'] = $data[3];
                        $error_list[$s]['generic_id'] = $data[4];
                        $error_list[$s]['unit_id'] = $data[5];
                        $error_list[$s]['selling_price_1'] = $data[6];
                        $error_list[$s]['unit2'] = $data[7];
                        $error_list[$s]['unit_factor2'] = $data[8];
                        $error_list[$s]['sales_price2'] = $data[9];
                        $error_list[$s]['unit3'] = $data[10];
                        $error_list[$s]['unit_factor3'] = $data[11];
                        $error_list[$s]['sales_price3'] = $data[12];
                    }
                }
                foreach ($model_store as $s => $data_model) {

                    //  print_r('innnn'); exit;

                    if ($data_model->validate()) {
                        $error_list[$s]['remarks'] = "correct";
                    } else {
                        $error_list[$s]['remarks'] = $data_model->getErrors();
                    }
                }
            }
            $jsonData['status'] = "error";
        }
        $j = 0;
        fclose($file);
        $list = array();
        $file_error = fopen($error_url, "w+");
        if (!empty($error_list)) {

            $list[$j++] = array('Part No *', 'Barcode', 'Description *', 'Brand*', 'Category*', 'Unit1*', 'Sales Price1', 'Unit2', 'Unit Factor2', 'Sales Price2', 'Unit3', 'Unit Factor3', 'Sales Price3', 'Log Remarks');
            foreach ($error_list as $i => $error_detail) {
                $error_view[$i] = '';
                if (!empty($error_detail)) {
                    if (!empty($error_detail['remarks']) && is_array($error_detail['remarks'])) {
                        foreach ($error_detail['remarks'] as $p => $error_value) {
                            if (is_array($error_value) && isset($error_value[0])) {
                                $error_view[$i] .= $error_value[0] . " / ";
                            }
                        }
                    } else {
                        $error_view[$i] .= '';
                    }

                    if (in_array($error_detail['part_number'], $partno_common)) {
                        $error_view[$i] .= "Part Number duplication in CSV /";
                    } else {
                        $error_view[$i] .= '';
                    }
                    if (in_array($error_detail['part_number'], $conflictingPartNumber)) {
                        $error_view[$i] .= "Part Number is a barcode of another product in CSV /";
                    } else {
                        $error_view[$i] .= '';
                    }


                    $list[$j++] = array(
                        $error_detail['part_number'],
                        $error_detail['bar_code'],
                        $error_detail['description'],
                        $error_detail['brand_class_id'],
                        $error_detail['generic_id'],
                        $error_detail['unit_id'],
                        $error_detail['selling_price_1'],
                        $error_detail['unit2'],
                        $error_detail['unit_factor2'],
                        $error_detail['sales_price2'],
                        $error_detail['unit3'],
                        $error_detail['unit_factor3'],
                        $error_detail['sales_price3'],
                        $error_view[$i]
                    );
                }
            }
            $k = 0;
            foreach ($list as $k => $line) {
                fputcsv($file_error, $line);
            }
            fclose($file_error);
        }


        $jsonData['error_url'] = $error_url;
        $jsonData['filename'] = $file_name;
        $jsonData['link'] = CHtml::link('Download log', array('inventory/DownloadErrorCsv', 'id' => $file_name), array(
            'target' => '_blank',
            'style' => 'border: 1px solid #686869;padding: 2px 10px;border-radius: 10px;font-size: 10px;background: #a1a1a1;color: #fff;'
                . ''
        )) . '</div><div style="font-size: 12px;">Data updation failed. Please see this file.</div>';
        echo CJSON::encode($jsonData);
    }

    private function sanitizeData($data)
    {
        // Remove commas and trim any extra spaces
        return !empty($data) ? trim(trim(iconv('UTF-8', 'ASCII//TRANSLIT', $data), '"')) : '';
    }

    private function sanitizeNmber($data)
    {
        // Remove commas and trim any extra spaces
        $sanitizedData = !empty($data) ? trim(trim(iconv('UTF-8', 'ASCII//TRANSLIT', $data), '"')) : '';
        // Remove commas and convert to float
        $sanitizedData = str_replace(',', '', $sanitizedData);

        // Return as a float
        return is_numeric($sanitizedData) ? (float) $sanitizedData : 0.0;
    }

    public function readInventoryListCSV($csvFile)
    {
        $file_handle = fopen($csvFile, 'r');
        while (!feof($file_handle)) {
            $contents = fgetcsv($file_handle, 1024, ',');
            $line_of_text[] = $contents;
        }
        fclose($file_handle);
        return $line_of_text;
    }
    // public function actionDownloadErrorCsv()
    // {
    //     $file_name = $event_id = Yii::app()->request->getParam('id');
    //     $error_url = Yii::app()->basePath . '/../uploads/inventorylist_csv/error/' . $file_name;
    //     return Yii::app()->getRequest()->sendFile('log.csv', @file_get_contents($error_url));
    // }
    public function actionUploadinv($folder = null)
    {

        Yii::import("ext.EAjaxUpload.qqFileUploader");



        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';

        // make the directory to store the pic:

        if (!is_dir($folder)) {

            mkdir($folder, 0777, TRUE);

            //chmod($folder, 0755);
        }

        $allowedExtensions = array();

        $sizeLimit = 2 * 1024 * 1024; // maximum file size in bytes

        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);

        $result = $uploader->handleUpload($folder);

        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);

        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);



        $fileName = $result['filename']; //GETTING FILE NAME

        //  $this->CropIfImage($folder, $fileName, 100, 100);

        echo $return; // it's array
    }

    public function actionUploadInventory()
    {
        //added by nisha on 28-02-2023
        $model = new Store();
        Yii::app()->clientScript->scriptMap = array('*jquery.js' => false, '*jquery.min.js' => false, 'jquery.min.js' => false, '*jquery-ui.js' => false, '*jquery-ui.min.js' => false);
        $this->renderPartial('upload_inventory', array('model' => $model), false, true);
    }

    public function actionDownloadSampleCsv()
    {
        $filename = 'inventory_list.csv';
        header("Content-type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
        echo 'Part No.*, Description,Quantity,Category,Brand,Unit,Tax Code,Rate,Warehouse,Rack,Bin,Length,Width,Height,CBM,Have Expiry Date(Y/N),Have Serial No(Y/N),Bar code';
        Yii::app()->end();
    }

    public function readInventoryCSV($csvFile)
    {
        if (!file_exists($csvFile)) {
            throw new Exception("File not found: $csvFile");
        }

        $file_handle = fopen($csvFile, 'r');
        $line_of_text = [];
        while (($contents = fgetcsv($file_handle, 1024, ',')) !== false) {
            $line_of_text[] = $contents;
        }
        fclose($file_handle);

        return $line_of_text;
    }
    public function actionSaveInventoryUploadCsv()
    {
        $file_name = Yii::app()->request->getParam('filename');
        $batch = (int) Yii::app()->request->getParam('batch', 1);
        $url = Yii::app()->basePath . '/../uploads/inventory_csv/' . $file_name;
        $mas_inventory_list = $this->readInventoryCSV($url);
        $error_url = Yii::app()->basePath . '/../uploads/inventory_csv/error/' . $file_name;
        $error_list = [];
        $error_occurred = false;
        $batch_size = 200;
        $success_count = 0;
        $error_count = 0;
        $non_empty_row_count = 0;
        if (!empty($mas_inventory_list)) {
            $header = array_shift($mas_inventory_list); // Remove header row only once
        }
        $total_records = count($mas_inventory_list);
        $start_index = ($batch - 1) * $batch_size;
        $batch_data = array_slice($mas_inventory_list, $start_index, $batch_size);

        foreach ($mas_inventory_list as $index => $data) {
            if (!empty($data)) {
                $line_number = $index + 2; // Adjust for header row
                $log_remarks = [];

                // Sanitize and validate data
                $partNumber = $this->sanitizeData($data[0]);
                if ($batch == 1) {
                    $model_store = Store::model()->findByAttributes(['part_number' => $partNumber]);
                    if (empty($model_store)) {
                        $have_item = 'N';
                        // Validate and prepare log remarks for this row
                        $log_remarks = $this->validateAndPrepareLog($data, $log_remarks);
                    } else {
                        $have_item = 'Y';
                        $log_remarks = $this->validateAndPrepareLog($data, $log_remarks);
                    }

                }

                if (empty($log_remarks)) {
                    $error_list[$line_number] = [
                        'part_number' => $data[0],
                        'description' => $data[1],
                        'quantity' => $data[2],
                        'category' => $data[3],
                        'brand' => $data[4],
                        'unit' => $data[5],
                        'tax_code' => $data[6],
                        'rate' => $data[7],
                        'warehouse' => $data[8],
                        'rack' => $data[9],
                        'bin' => $data[10],
                        'length' => $data[11],
                        'width' => $data[12],
                        'height' => $data[13],
                        'cbm' => $data[14],
                        'have_expriry_date' => $data[15],
                        'have_serial_no' => $data[16],
                        'bar_code' => $data[17],
                        'log_remarks' => ''
                    ];
                } else {
                    $error_occurred = true;
                    $error_count++;
                    $error_list[$line_number] = [
                        'part_number' => $data[0],
                        'description' => $data[1],
                        'quantity' => $data[2],
                        'category' => $data[3],
                        'brand' => $data[4],
                        'unit' => $data[5],
                        'tax_code' => $data[6],
                        'rate' => $data[7],
                        'warehouse' => $data[8],
                        'rack' => $data[9],
                        'bin' => $data[10],
                        'length' => $data[11],
                        'width' => $data[12],
                        'height' => $data[13],
                        'cbm' => $data[14],
                        'have_expriry_date' => $data[15],
                        'have_serial_no' => $data[16],
                        'bar_code' => $data[17],
                        'log_remarks' => implode(" | ", $log_remarks)
                    ];
                }
            }
        }
        // var_dump($log_remarks);
        // die();
        if ($error_occurred) {
            // echo 'hii';
            $file_error = fopen($error_url, "w+");
            $error_directory = Yii::app()->basePath . '/../uploads/inventory_csv/error/';

            if (!is_dir($error_directory)) {
                mkdir($error_directory, 0777, true);  // Create the directory with appropriate permissions
            }
            if ($file_error === false) {
                // Handle the error if the file cannot be opened
                throw new Exception("Unable to open file for writing: $error_url");
            }
            // Add headers to the CSV file
            $headers = ['Part No.*', 'Description', 'Quantity', 'Category', 'Brand', 'Unit', 'Tax Code', 'Rate', 'Warehouse', 'Rack', 'Bin', 'Length', 'Width', 'Height', 'CBM', 'Have Expiry Date(Y/N)', 'Have Serial No(Y/N)', 'Bar code.', 'Log Remarks'];
            fputcsv($file_error, $headers);

            // Add each line from the original CSV, including rows with no errors
            foreach ($error_list as $error_detail) {
                $line = [
                    $error_detail['part_number'],
                    $error_detail['description'],
                    $error_detail['quantity'],
                    $error_detail['category'],
                    $error_detail['brand'],
                    $error_detail['unit'],
                    $error_detail['tax_code'],
                    $error_detail['rate'],
                    $error_detail['warehouse'],
                    $error_detail['rack'],
                    $error_detail['bin'],
                    $error_detail['length'],
                    $error_detail['width'],
                    $error_detail['height'],
                    $error_detail['cbm'],
                    $error_detail['have_expriry_date'],
                    $error_detail['have_serial_no'],
                    $error_detail['bar_code'],
                    $error_detail['log_remarks'], // Include log remarks, empty if no error
                ];
                fputcsv($file_error, $line);
            }
            fclose($file_error);

            $jsonData['error_url'] = $error_url;
            $jsonData['filename'] = $file_name;
            $jsonData['link'] = CHtml::link('Download Log', array('inventory/DownloadErrorCsv', 'id' => $file_name), array(
                'target' => '_blank',
                'style' => '
                display: inline-block; border: 2px solid #ff4d4f; padding: 5px 15px;border-radius: -3px;font-size: 12px;
                font-weight: bold; background: #ff4d4f; color: #fff;text-decoration: none;text-align: center; margin-bottom: 10px;'
            )) . '</div>
            <div style="
                font-size: 12px;
                font-weight: bold;
                color: #ff4d4f;
                margin-top: 10px; 
            ">
                Data updation failed. Please see this file.
            </div>';
            echo json_encode($jsonData);

            return; // Return to stop further execution
        }

        // die();
        foreach ($batch_data as $index => $data) {

            $non_empty_row_count++;
            if (!empty($data)) {
                $line_number = $start_index + $index + 2;
                $log_remarks = [];

                // Sanitize and validate data
                $part_number = $this->sanitizeData($data[0]);
                $description = trim($data[1]);
                $quantity = $this->sanitizeData($data[2]);
                $category = $this->sanitizeData($data[3]);
                $brand = $this->sanitizeData($data[4]);
                $unit = $this->sanitizeData($data[5]);
                $tax_code = $this->sanitizeData($data[6]);
                $rate = $this->sanitizeNumber($data[7]);
                $warehouse = $this->sanitizeData($data[8]);
                $rack = $this->sanitizeData($data[9]);
                $bin = $this->sanitizeData($data[10]);
                $length = $this->sanitizeNumber($data[11]);
                $width = $this->sanitizeNumber($data[12]);
                $height = $this->sanitizeNumber($data[13]);
                $cbm = $this->sanitizeNumber($data[14]);
                $have_expriry_date = $this->sanitizeData($data[15]);
                $have_serial_no = $this->sanitizeData($data[16]);
                $bar_code = $this->sanitizeData($data[17]);
                if (empty($bar_code)) {
                    $bar_code = $part_number;
                }
                // warehouse
                $warehouse_exist = MasInventoryWarehouse::model()->find(
                    'LOWER(warehouse_name) = :warehouse_name',
                    [':warehouse_name' => strtolower(trim($warehouse))]
                );
                if (!empty($warehouse_exist)) {
                    $warehouse_id = $warehouse_exist->id;
                }
                // brand
                $brand_exist = MasInvBrand::model()->find(
                    'LOWER(brand_name) = :brand_name',
                    [':brand_name' => strtolower(trim($brand))]
                );
                if (!empty($brand_exist)) {
                    $brand = $brand_exist->id;
                }

                // unit
                $unit_exist = Unit::model()->find(
                    'LOWER(unit_name) = :unit_name',
                    [':unit_name' => strtolower(trim($unit))]
                );
                if (!empty($unit_exist)) {
                    $unit_id = $unit_exist->id;
                    $symbol = $unit_exist->symbol;
                }

                // tax
                $tax_exist = MasInvTax::model()->find(
                    'LOWER(tax_code) = :tax_code',
                    [':tax_code' => strtolower(trim($tax_code))]
                );
                if (!empty($tax_exist)) {
                    $tax_code = $tax_exist->id;
                }

                // category
                if (!empty($category)) {
                    $category_exist = MasGeneric::model()->find(
                        'LOWER(generic_name) = :generic_name',
                        [':generic_name' => strtolower(trim($category))]
                    );
                    if (!empty($category_exist)) {
                        $generic_id = $category_exist->id;
                    }
                } else {
                    $generic_id = '';
                }

                // rack
                $rack_exist = MasInvRack::model()->find(
                    'LOWER(rack_name) = :rack_name',
                    [':rack_name' => strtolower(trim($rack))]
                );
                if (!empty($rack_exist)) {
                    $rack_id = $rack_exist->id;
                }

                // bin
                $bin_exist = MasInvBin::model()->find(
                    'LOWER(bin_name) = :bin_name',
                    [':bin_name' => strtolower(trim($bin))]
                );
                if (!empty($bin_exist)) {
                    $bin_id = $bin_exist->id;
                }
                if ($this->isTypeNameExists(trim($part_number))) {
                    $existing_count++;
                }
                // var_dump($generic_id);
                // else {
                $model_store = Store::model()->findByAttributes(['part_number' => $part_number]);

                if (empty($model_store)) {

                    // Save to DB   
                    $model = new Store();
                    $model->created_by = Yii::app()->user->id;
                    $model->updated_by = Yii::app()->user->id;
                    $model->created_date_time = date('Y-m-d H:i:s');
                    $model->updated_date_time = date('Y-m-d H:i:s');
                    $model->part_number = $part_number;
                    $model->description = $description;
                    $model->generic_id = $generic_id;
                    $model->brand_class_id = $brand;
                    $model->unit_id = $unit_id;
                    $model->tax_code = $tax_code;
                    $model->rate = $rate;
                    $model->warehouse_id = $warehouse_id;
                    $model->rack_id = $rack_id;
                    $model->bin_id = $bin_id;
                    $model->length = $length;
                    $model->width = $width;
                    $model->height = $height;
                    $model->volume = $cbm;
                    $model->have_expiry_date = $have_expriry_date;
                    $model->have_serial_no = $have_serial_no;
                    $model->bar_code = $bar_code;
                    $model->inventory_item_type = '1';
                    $model->ledger_id = '132';
                    $model->isActive = 'Y';
                    if ($model->save()) {
                        $modelUnitOfMeasurement = new UnitOfMeasurement();
                        $modelUnitOfMeasurement->product_id = $model->id;
                        $modelUnitOfMeasurement->unit_id = $unit_id;
                        $modelUnitOfMeasurement->name = $symbol;
                        $modelUnitOfMeasurement->base_unit = $unit_id;
                        $modelUnitOfMeasurement->factor = '1';
                        $modelUnitOfMeasurement->is_secondary_unit = 'N';
                        $modelUnitOfMeasurement->isBase = 'Y';
                        $modelUnitOfMeasurement->created_by = Yii::app()->user->id;
                        // $modelUnitOfMeasurement->updated_by = Yii::app()->user->id;
                        $modelUnitOfMeasurement->created_date_time = date('Y-m-d H:i:s');
                        if ($modelUnitOfMeasurement->save(false)) {
                            $errors = $modelUnitOfMeasurement->getErrors();
                            foreach ($errors as $field => $messages) {
                                foreach ($messages as $message) {
                                    $log_remarks[] = $message;
                                }
                            }

                        }
                        $success_count++;
                    } else {
                        // Echo model save errors
                        $errors = $model->getErrors();
                        foreach ($errors as $field => $messages) {
                            foreach ($messages as $message) {
                                $log_remarks[] = "Error in $field: $message<br>";
                            }
                        }
                    }
                }

                if (!empty($data[2])) {
                    $other = array();
                    $valid = true;

                    if (($quantity > 0)) {
                        $modelGoodsReceipt = new InventoryGoodsReceipt();
                        $model_item = new InventoryGoodsReceiptItem();
                        $modelGoodsReceipt->created_by = Yii::app()->user->id;
                        $modelGoodsReceipt->created_date_time = date('Y-m-d h:i:s');
                        $modelGoodsReceipt->receipt_type = 'N'; //$_POST['InventoryGoodsReceipt']['receipt_type'];
                        $modelGoodsReceipt->goods_receipt_date = date('Y-m-d');
                        $modelGoodsReceipt->reference = 'Added From Inventory Upload';
                        $modelGoodsReceipt->warehouse_id = $warehouse_id;

                        $valid = $modelGoodsReceipt->validate() && $valid;
                        $model_items = [];
                        // foreach ($list as $k => $rowItem) {
                        // var_dump($part_number);
                        // die();
                        $product = Store::model()->findByAttributes(['part_number' => $model->part_number]);

                        if (!empty($product)) {
                            // var_dump( UnitOfMeasurement::getBaseunit($product['id']) );
                            $model_item->created_by = Yii::app()->user->id;
                            $model_item->created_date_time = date('Y-m-d h:i:s');
                            $model_item->product_id = $product['id'];
                            $model_item->product_name = $product['part_number'];
                            $model_item->description = $product['description'];
                            $model_item->picked_qty = $quantity;
                            $model_item->unit = UnitOfMeasurement::getBaseunit($product['id']);
                            $model_item->rate = $product['rate'];
                            $valid = $model_item->validate() && $valid;
                            $model_items[] = $model_item;
                        }

                        // }
                    }
                    // die();


                    if (($quantity < 0)) {
                        $modelIssue = new InventoryGoodsIssue();
                        $model_issue_item = new InventoryGoodsIssueItem();
                        $modelIssue->created_by = Yii::app()->user->id;
                        $modelIssue->created_date_time = date('Y-m-d h:i:s');
                        $modelIssue->issue_type = 'N';
                        $modelIssue->goods_issue_date = date('Y-m-d');
                        $modelIssue->reference = 'Added From Inventory Upload';
                        $modelIssue->warehouse_id = $warehouse_id;

                        $valid = $modelIssue->validate() && $valid;
                        $model_items_issue = [];
                        // foreach ($list_issue as $k => $rowItemIssue) {
                        $product = Store::model()->findByAttributes(['part_number' => $part_number]);

                        $model_issue_item->created_by = Yii::app()->user->id;
                        $model_issue_item->created_date_time = date('Y-m-d h:i:s');
                        $model_issue_item->product_id = $product['id'];
                        $model_issue_item->product_name = $product['part_number'];
                        $model_issue_item->description = $product['description'];
                        $model_issue_item->picked_qty = Abs((int) $quantity);
                        $model_issue_item->unit = UnitOfMeasurement::getBaseunit($product['id']);
                        $model_issue_item->rate = $product['rate'];
                        $valid = $model_issue_item->validate() && $valid;
                        $model_items_issue[] = $model_issue_item;
                        // }
                    }

                    if ($valid) {
                        if (!empty($quantity > 0)) {
                            $modelGoodsReceipt->stock_updated = 'Y';
                            $modelGoodsReceipt->save(false);


                            // Audit Log
                            AuditLog::saveAuditLogs(
                                'RECEIPTS',
                                Yii::app()->user->id,
                                'CREATED',
                                " with Checkin No: - {$modelGoodsReceipt->id}"
                            );

                            $modelRack = new MasInvRack();
                            $modelBin = new MasInvBin();
                            $modelProductClass = new MasInvBrand();
                            $modelUOM = new UnitOfMeasurement();
                            $warehouse_id = 0;
                            if ((int) $modelGoodsReceipt->warehouse_id > 0) {
                                $warehouse_id = $modelGoodsReceipt->warehouse_id;
                            }

                            /* else {
                            $warehouse_id = (int) Yii::app()->user->getState('user_warehouse_id');
                        }*/

                            $warehouse_name = '';
                            if ($warehouse_id > 0) {
                                $modwarehouse = new MasInventoryWarehouse();
                                $warehouse_name = $modwarehouse->getWarehouseName($warehouse_id);
                            }
                            $modelCustomer = new Customer();
                            $modelcustomer_name = '';
                            if ((int) $modelGoodsReceipt->customer_id > 0) {
                                $modelcustomer_name = $modelCustomer->findByPk($modelGoodsReceipt->customer_id)->customer_name;
                            }

                            foreach ($model_items as $item) {
                                $item->inventory_goods_receipt_id = $modelGoodsReceipt->id;
                                $item->save(false);
                                $modelUOM = $modelUOM->findByPk((int) $item->unit);
                                $modelproduct_class = '';
                                if ((int) $item->product->brand_class_id > 0) {
                                    $modelproduct_class = $modelProductClass->findByPk($item->product->brand_class_id)->brand_name;
                                }
                                // ----------------------------------------------------------------
                                $arr_product_details = Store::model()->findbyPk($item->product_id);
                                $existing_store_rate = $arr_product_details->rate;
                                $rate = $existing_store_rate;
                                $existing_qty = $arr_product_details->totalQuantity;

                                $new_cost_price = $item->rate * $item->picked_qty;
                                $new_cost_price = round($new_cost_price, 6);

                                $quantity_with_unit_factor = $item->picked_qty * $modelUOM->factor;
                                $variance_value = ($quantity_with_unit_factor > 0) ? $new_cost_price / $quantity_with_unit_factor : 0;
                                $variance_value = round($variance_value, 6);
                                $cost_with_variance = $variance_value;

                                $cur_total = $cost_with_variance * $quantity_with_unit_factor;
                                $existing_amount = $rate * $existing_qty;
                                $total_quantity = $existing_qty + $quantity_with_unit_factor;
                                $total_amount = $existing_amount + $cur_total;
                                $new_amount = ($total_quantity > 0) ? $total_amount / $total_quantity : $existing_store_rate;
                                $new_amount = round($new_amount, 6);


                                Store::model()->updateByPk($item->product_id, array('rate' => $new_amount));
                                // ----------------------------------------------------------------
                                $modelStockLedger = new StockLedger();
                                $modelStockLedger->brand_id = $item->product->brand_class_id;
                                $modelStockLedger->brand_name = $modelproduct_class;
                                $modelStockLedger->customer_vendor_id = $modelGoodsReceipt->customer_id;
                                $modelStockLedger->customer_vendor_name = $modelcustomer_name;
                                $modelStockLedger->file_id = $modelGoodsReceipt->file_id;
                                $modelStockLedger->header_id = $modelGoodsReceipt->id;
                                $modelStockLedger->header_item_id = $item->id;
                                $modelStockLedger->product_id = $item->product_id;
                                $modelStockLedger->product_name = $item->product->part_number;
                                $modelStockLedger->product_description = $item->product->description;
                                $modelStockLedger->warehouse_id = (int) $warehouse_id;
                                $modelStockLedger->warehouse_name = $warehouse_name;
                                $modelStockLedger->rack_id = $modelRack->getDefaultRackId();
                                $modelStockLedger->rack_name = $modelRack->getRackName((int) $modelStockLedger->rack_id);
                                $modelStockLedger->bin_id = $modelBin->getDefaultBinId();
                                $modelStockLedger->bin_name = $modelBin->getBinName((int) $modelStockLedger->bin_id);
                                $modelStockLedger->unit_id = $item->unit;
                                $modelStockLedger->unit_name = $modelUOM->name;
                                $modelStockLedger->unit_factor = $modelUOM->factor;
                                $modelStockLedger->quantity = $item->picked_qty;
                                $modelStockLedger->available_status = 'A';
                                $modelStockLedger->buying_price = $item->rate / $modelUOM->factor;
                                $modelStockLedger->batch_no = '';
                                $modelStockLedger->serial_no = '';
                                $modelStockLedger->manufacturing_date = '0000-00-00';
                                $modelStockLedger->expiry_date = '0000-00-00';
                                $modelStockLedger->cost_price = $new_amount;
                                $modelStockLedger->sales_price = 0;
                                $modelStockLedger->transaction_date = date('Y-m-d');
                                $modelStockLedger->transaction_from = 'INVENTORY_GOODS_RECEIPT'; //when goods receipt -- item returned
                                $modelStockLedger->transaction_type = "IN";
                                $modelStockLedger->stock_updated = 'Y';
                                $modelStockLedger->created_by = (int) Yii::app()->user->id;
                                $modelStockLedger->created_date = date("Y-m-d H:i:s");
                                $modelStockLedger->save(false);
                            }

                            // echo CJSON::encode(['status' => 'success', 'message' => 'Stock uploaded successfully.']);
                            // return;



                        }

                        ////////////////////////////////////////////////////////////////////////
                        if (!empty($quantity < 0)) {
                            $modelIssue->stock_updated = 'N';
                            $modelIssue->save(false);


                            // Audit Log
                            AuditLog::saveAuditLogs(
                                'ISSUES',
                                Yii::app()->user->id,
                                'CREATED',
                                " with Checkin No: - {$modelIssue->id}"
                            );

                            foreach ($model_items_issue as $itemissue) {
                                $itemissue->inventory_goods_issue_id = $modelIssue->id;
                                $itemissue->save(false);
                            }
                        }
                    } else {
                        if ($modelGoodsReceipt) {
                            $error1 = json_decode(CActiveForm::validate($modelGoodsReceipt, '', false), true);
                        } else {
                            $error1 = [];
                        }

                        $error2 = $model_items[0]->product_id > 0
                            ? json_decode(CActiveForm::validateTabular($model_items, '', false), true)
                            : ["Please add at least one line item"];
                        $error3 = json_decode(CActiveForm::validate($modelIssue, '', false), true);
                        $error4 = $model_items_issue[0]->product_id > 0
                            ? json_decode(CActiveForm::validateTabular($model_items_issue, '', false), true)
                            : ["Please add at least one line item"];
                        $errors = array_merge_recursive($error1, $error2, $error3, $error4, $other);

                        echo CJSON::encode(['status' => 'error', 'message' => 'Validation failed.', 'errors' => $errors]);
                        return;
                    }
                    // }



                }


            }
        }
        // $existing_count = ($batch - 1) * $batch_size;

        // Yii::app()->session['batch_no'] = $batch + 1;
        if ($start_index + $batch_size < $total_records) {
            $next_batch = $batch + 1;
            echo json_encode([
                'status' => 'success',
                'message' => '',
                'flag' => 'continue',
                'next_button' => '<a href="javascript:void(0);" 
                            id="next-batch-btn" 
                            data-url="' . Yii::app()->createUrl('inventory/SaveInventoryUploadCsv', [
                                'filename' => $file_name,
                                'batch' => $next_batch

                            ]) . '"
                            style="display: inline-block; border: 2px solid #000080; padding: 5px 15px; font-size: 12px; font-weight: bold; background: #000080; color: #fff; text-decoration: none;">
                            Upload Next 200
                          </a>',
                'total_records' => $total_records,
                'success_count' => $success_count,
                'error_count' => $error_count,
                'non_empty_row_count' => $non_empty_row_count,
                'existing_count' => $existing_count,
                'log_remarks' => $log_remarks
            ]);
        } else {
            echo json_encode([
                'status' => 'success',
                'message' => '',
                'success_count' => $success_count,
                'error_count' => $error_count,
                'non_empty_row_count' => $non_empty_row_count,
                'existing_count' => $existing_count,
                'total_records' => $total_records,
            ]);
        }
    }
    public function actionDownloadErrorCsv()
    {

        $file_name = $event_id = Yii::app()->request->getParam('id');
        $error_url = Yii::app()->basePath . '/../uploads/inventory_csv/error/' . $file_name;
        return Yii::app()->getRequest()->sendFile('log.csv', @file_get_contents($error_url));
    }
    // private function sanitizeData($data)
    // {
    //     return !empty($data) ? trim(iconv('UTF-8', 'ASCII//TRANSLIT', $data), '"') : '';
    // }

    private function sanitizeNumber($data)
    {
        $sanitizedData = str_replace(',', '', trim($data));
        return is_numeric($sanitizedData) ? (float) $sanitizedData : 0.0;
    }
    private function validateAndPrepareLog($data, &$log_remarks)
    {
        $log_remarks = [];

        // Sanitize and assign data
        $part_number = $this->sanitizeData(trim($data[0]));
        $description = trim($data[1]);
        $quantity = $this->sanitizeData(trim($data[2]));
        $category = $this->sanitizeData(trim($data[3]));
        $brand = $this->sanitizeData(trim($data[4]));
        $unit = $this->sanitizeData(trim($data[5]));
        $tax_code = $this->sanitizeData(trim($data[6]));
        $rate = $this->sanitizeNumber(trim($data[7]));
        $warehouse = $this->sanitizeData(trim($data[8]));
        $rack = $this->sanitizeData(trim($data[9]));
        $bin = $this->sanitizeData(trim($data[10]));
        $length = $this->sanitizeNumber(trim($data[11]));
        $width = $this->sanitizeNumber(trim($data[12]));
        $height = $this->sanitizeNumber(trim($data[13]));
        $cbm = $this->sanitizeNumber(trim($data[14]));
        $have_expriry_date = $data[15];
        $have_serial_no = $data[16];
        $bar_code = $this->sanitizeData(trim($data[17]));




        // Validate 'code'

        if (empty($part_number)) {
            $log_remarks[] = "Part No. is required.";
        }
        if (empty($description)) {
            $log_remarks[] = "Description is required.";
        }

        if (!empty($category)) {
            $category_exist = MasGeneric::model()->find(
                'LOWER(generic_name) = :generic_name',
                [':generic_name' => strtolower(trim($category))]
            );
            if (empty($category_exist)) {
                $log_remarks[] = "Invalid Category Name";
            }
        }
        // brand
        if (empty($brand)) {
            $log_remarks[] = "Brand is required.";
        } else {
            $brand_exist = MasInvBrand::model()->find(
                'LOWER(brand_name) = :brand_name',
                [':brand_name' => strtolower($brand)]
            );
            if (empty($brand_exist)) {
                $log_remarks[] = "Invalid Brand Name";
            }
        }

        // unit
        if (empty($unit)) {
            $log_remarks[] = "Unit is required.";
        } else {
            $unit_exist = Unit::model()->find(
                'LOWER(unit_name) = :unit_name',
                [':unit_name' => strtolower($unit)]
            );
            if (empty($unit_exist)) {
                $log_remarks[] = "Invalid Unit Name";
            }
        }

        // tax
        if (empty($tax_code)) {
            $log_remarks[] = "Tax Code is required.";
        } else {
            $tax_exist = MasInvTax::model()->find(
                'LOWER(tax_code) = :tax_code',
                [':tax_code' => strtolower($tax_code)]
            );
            if (empty($tax_exist)) {
                $log_remarks[] = "Invalid Tax Code Name";
            }
        }

        // warehouse
        if (empty($warehouse)) {
            $log_remarks[] = "Warehouse is required.";
        } else {
            $warehouse_exist = MasInventoryWarehouse::model()->find(
                'LOWER(warehouse_name) = :warehouse_name',
                [':warehouse_name' => strtolower($warehouse)]
            );
            if (empty($warehouse_exist)) {
                $log_remarks[] = "Invalid Warehouse Name";
            }
        }

        // rack
        if (empty($rack)) {
            $log_remarks[] = "Rack is required.";
        } else {
            $rack_exist = MasInvRack::model()->find(
                'LOWER(rack_name) = :rack_name',
                [':rack_name' => strtolower($rack)]
            );
            if (empty($rack_exist)) {
                $log_remarks[] = "Invalid Rack Name";
            }
        }

        // expiry date flag
        if (empty($have_expriry_date)) {
            $log_remarks[] = "Have Expiry Date is required.";
        } else {
            if ($have_expriry_date !== 'Y' && $have_expriry_date !== 'N') {
                $log_remarks[] = "Have Expiry Date Invalid Entry.";
            }
        }

        // serial no flag
        if (empty($have_serial_no)) {
            $log_remarks[] = "Have Serial No is required.";
        } else {
            if ($have_serial_no !== 'Y' && $have_serial_no !== 'N') {
                $log_remarks[] = "Have Serial No Invalid Entry.";
            }
        }


        return $log_remarks;

    }
    private function isTypeNameExists($code)
    {
        $code = strtolower(trim($code));
        return Store::model()->exists('LOWER(TRIM(part_number)) = :code', [':code' => $code]);
    }

    public function actionUploadInventoryCsv($folder = null)
    {
        Yii::import("ext.EAjaxUpload.qqFileUploader");

        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';

        // Check if directory exists or create it
        if (!is_dir($folder)) {
            mkdir($folder, 0777, true);
        }

        // Define allowed extensions and size limit
        $allowedExtensions = array();
        $sizeLimit = 2 * 1024 * 1024; // 2MB

        // Handle file upload
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);

        // Return JSON response
        echo htmlspecialchars(json_encode($result), ENT_NOQUOTES);
    }


}
