<?php

class VendorController 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',
                    'CreateNote',
                    'SaveNote',
                    'create',
                    'getNotesList',
                    'SaveEditedVendor',
                    'CreateVendorEdit',
                    'GetList',
                    'SaveVendor',
                    'GetContactList',
                    'VendorContactCreate',
                    'SaveContact',
                    'DeleteContact',
                    'DeleteVendor',
                    'GetCurrency',
                    'getVendorCurrency',
                    'GetCustomer',
                    'GetCustomerActivity',
                    'GetVendor',
                    'addSubledger',
                    'UploadSupplierDocuments',
                    'CreateDocumentForm',
                    'SaveDocForm',
                    'GetDocsList',
                    'DownloadDocument',
                    'CheckTrnExistance',
                    'GetVendorByType',
                    'Menu',
                    'DefaultContact',
                    'DashboardSettingsRating',
                    'GetCurrencyWithAddress',
                    'UploadVendor',
                    'DownloadSampleCsv',
                    'DownloadSampleCsv',
                    'SaveVendorUploadCsv',
                    'UploadVendorCsv',
                    'DownloadErrorCsv'
                ),
                'expression' => '$user->isMember()',
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

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

    /**
     * This is the default 'index' action that is invoked
     * when an action is not explicitly requested by users.
     */
    public function actionIndex()
    {
        $model = new Vendor();
        // Disable loading of certain JS files
        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,
        );

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

    /*
     * function to list all vendors
     *
     */

    public function actiongetList()
    {
        $model = new Vendor();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'id',
            1 => 'vendor_name',
            2 => 'vendor_location',
            3 => 'vendor_country',
            4 => 'vendor_phone_no',
            // 5 => 'vendor_email_id',
            5 => 'vendor_city',
            6 => 'vendor_trn_no'
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = '1=1';
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            //$condition.=" AND (vendor_name LIKE '%" . $searchString . "%' OR vendor_location LIKE '%" . $searchString . "%' OR vendor_city LIKE '%" . $searchString . "%' OR vendor_phone_no LIKE '%" . $searchString . "% OR vendor_email_id LIKE '%" . $searchString . "% OR vendor_trn_no LIKE '%" . $searchString . "%')";

            $condition .= " AND (id LIKE '%" . $searchString . "%' OR vendor_name LIKE '%" . $searchString . "%' OR vendor_city LIKE '%" . $searchString . "%' OR vendor_phone_no LIKE '%" . $searchString . "%' OR vendor_email_id LIKE '%" . $searchString . "%' OR vendor_trn_no LIKE '%" . $searchString . "%' OR vendor_location LIKE '%" . $searchString . "%')";
        }
        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 'isActive,vendor_name'));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        foreach ($model as $row) {

            $div = '';
            $div .= ' <button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'vendor/menu&id=' . $row['id'] . '\',\'Vendor Actions \',\'lg\')"><i class="fa fa-tasks"></i></button>';

            $rowData[] = array(
                $row['id'],
                $row['vendor_name'],
                $row['vendor_location'],
                $row['country']['country_name'],
                $row['vendor_phone_no'],
                // $row['vendor_email_id'],
                $row['vendor_trn_no'],
                $row['isActive'],
                array('id' => $row['id'], 'code' => $row['vendor_name'])
            );
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actiongetNotesList()
    {
        $model = new FileNotes();
        $vendor_id = $_POST['vendor_id'];
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'notes',
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.customer_vendor_id=' . $vendor_id . ' AND t.customer_vendor_type = 2';
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $condition .= " AND (notes LIKE '%" . $searchString . "%')";
        }
        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 'created_datetime DESC'));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        foreach ($model as $row) {
            $model2 = User::model()->find(array('condition' => 't.id = "' . $row['created_by'] . '"'));
            $rowData[] = array($m, $row['notes'], $model2->username, date("d/m/Y h:m:s", strtotime($row['created_datetime'])));
            $m++;
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    /*
     * function to create vendor details
     */

    public function actionCreate()
    {
        $model = new Vendor();
        $models = new VendorContact();
        //$modelnote = new FileNotes();
       // $modeldoc = new SupplierDocs();
        $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, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false, '*.css' => false);
        $this->render('vendor_form', array('model' => $model, 'models' => $models  ));
    }

    public function actionCreateNote()
    {

        $model = new Vendor();
        $modelnote = new FileNotes();
        $id = (int) Yii::app()->request->getParam('id');

        if ($id > 0) {
            $model = $model->findByPk($id);
            $var = $model->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, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false, '*.css' => false);
        $this->render('notes_details_2', array('model' => $model, 'modelnote' => $modelnote, 'var' => $var));
    }

    /*
     * function to create vendor contact using modal pop up
     */

    public function actionVendorContactCreate()
    {

        $models = new VendorContact();
        $id = (int) Yii::app()->request->getParam('id');
        $vendor_id = (int) Yii::app()->request->getParam('c_id');
        if ($id > 0) {
            $models = $models->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, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false, '*.css' => false);
        $this->render('contact_form_2', array('models' => $models, 'v_id' => $id, 'c_id' => $vendor_id));
    }

    /*
     * function to save vendor details
     */

    function actionSaveVendor()
    {

        $model = new Vendor();
        $modelcontact = new VendorContact();
        //$modelnote = new FileNotes();
        //$modeldoc = new SupplierDocs();
        /*         * ********** START Code for Save ************** */
        if (isset($_POST['Vendor'])) {

            if ($_POST['Vendor']['id'] > 0) {
                $scene = 'update';
                $id = $_POST['Vendor']['id'];
                $model = $model->findByPK($id);
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d h:i:s');
                $audit_type = 'UPDATED';
            } else {
                $audit_type = 'CREATED';
                // $model->crm_user_id = Yii::app()->user->id;
                $scene = 'new';
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = date('Y-m-d H:i:s');
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d H:i:s');
            }
            $approve = $_POST['approve'];
            $model->attributes = $_POST['Vendor'];
            $model->approve = $_POST['approve'];
            /* if($approve == 1){
              $model->close_date  = date("Y-m-d H:i:s");
              $model->closed_by = Yii::app()->user->id;
              } */
            $model->isActive = $_POST['Vendor']['isActive'];
            $model->type = $_POST['Vendor']['type'];
            $model->vendor_address = $_POST['Vendor']['vendor_address'];
            if ($_POST['Vendor']['vendor_emirates_name'] != '') {
                $model->vendor_emirates_name = $_POST['Vendor']['vendor_emirates_name'];
            }

            // if ($_POST['SupplierDocs']['id'] > 0) {
            //     $docid = $_POST['SupplierDocs']['id'];
            //     $modeldoc = $modeldoc->findByPK($docid);
            // }
            // $modeldoc->attributes = $_POST['SupplierDocs'];
            //$model->notes = $_POST['Vendor']['notes'];
            if (isset($_POST['VendorContact'])) {
                if ($_POST['VendorContact']['id'] > 0) {
                    $id = $_POST['VendorContact']['id'];
                    $modelcontact = $modelcontact->findByPK($id);
                    $modelcontact->updated_by = Yii::app()->user->id;
                    $modelcontact->updated_date_time = date('Y-m-d h:i:s');
                } else {

                    $modelcontact->created_by = Yii::app()->user->id;
                    $modelcontact->created_date_time = date('Y-m-d h:i:s');
                    $modelcontact->updated_by = Yii::app()->user->id;
                    $modelcontact->updated_date_time = date('Y-m-d h:i:s');
                }
                $modelcontact->attributes = $_POST['VendorContact'];
                $modelcontact->isActive = $_POST['VendorContact']['isActive'];
            }
            // if (isset($_POST['FileNotes']) && $_POST['FileNotes']['notes'] != '') {
            //     if ($_POST['FileNotes']['id'] > 0) {
            //         $id = $_POST['FileNotes']['id'];
            //         $modelnote = $modelnote->findByPK($id);
            //         $modelnote->updated_by = Yii::app()->user->id;
            //         $modelnote->updated_datetime = date('Y-m-d h:i:s');
            //     } else {

            //         $modelnote->created_by = Yii::app()->user->id;
            //         $modelnote->created_datetime = date('Y-m-d h:i:s');
            //     }
            //     $modelnote->attributes = $_POST['FileNotes'];
            // }
            $valid = $model->validate();
            if ($scene == 'new') {
                $valid = $modelcontact->validate() && $valid;
            }
            if ($valid) {
                echo CJSON::encode(array('status' => 'success'));
                $model->save();
                // inserting to audit log
                AuditLog::saveAuditLogs(
                    'VENDOR',
                    Yii::app()->user->id,
                    $audit_type,
                    " with No: - {$model->id}  "
                );
                // end audit log
                // -----------------------------------------------------------------------------------------------------------
                //save this vendor to Subledgder---added- by-indhu-05_01_2023
                //------------------------------------------------------------------------------------------------------------
                // $modelAccSubledger = new AccSubledger();
                $type = "v";
                // $modelAccSubledger->saveEachSubledgder($model->id, $model->vendor_name, $type);
                // -----------------------------------------------------------------------------------------------------------
                //-----------------------------------end-------------------------------------------------------------------------


                if ($scene == 'new') {
                    $modelcontact->vendor_id = $model->id;
                    $modelcontact->person_name = "Sales/Account";
                    $modelcontact->save(false);

                    // $modelnote->customer_vendor_id = $model->id;
                    // $modelnote->customer_vendor_type = 2;
                    // if ($modelnote->notes != '') {
                    //     $modelnote->save(false);
                    // }
                    //Mail Settings
                    /* $model_mail_setting=Notification::model()->find(array('condition' => 'event_id="10"'));
                      Yii::import('application.controllers.front.MasternotificationController');
                      if($model_mail_setting->mail_required=='Y'){
                      MasternotificationController::sendmail(10,$model->id);
                      }
                      if($model_mail_setting->notification_required=='Y'){
                      MasternotificationController::sendnotification(10,$model->id);
                      }
                      if($model_mail_setting->sms_required=='Y'){
                      MasternotificationController::sendsms(10,$model->id);
                      } */
                }


                // if ($_POST['SupplierDocs']['document'] != '') {
                //     if ($_POST['SupplierDocs']['from_date'] != '00/00/0000' && $_POST['SupplierDocs']['from_date'] != '') {
                //         $modeldoc->from_date = str_replace('/', '-', $_POST['SupplierDocs']['from_date']);
                //         $modeldoc->from_date = date("Y-m-d", strtotime($modeldoc->from_date));
                //     }
                //     if ($_POST['SupplierDocs']['to_date'] != '00/00/0000' && $_POST['SupplierDocs']['to_date'] != '') {
                //         $modeldoc->to_date = str_replace('/', '-', $_POST['SupplierDocs']['to_date']);
                //         $modeldoc->to_date = date("Y-m-d", strtotime($modeldoc->to_date));
                //     }
                //     $modeldoc->score = $_POST['SupplierDocs']['score'];
                //     $modeldoc->supplier_id = $model->id;
                //     $modeldoc->save(false);
                // }
            } else {
                //echo 'inside error';
                $error2 = $error3 = array();
                if ($scene == 'new') {
                    $error3 = json_decode(CActiveForm::validate($modelcontact, '', false), true);
                }
                $error1 = json_decode(CActiveForm::validate($model, '', false), true);
                //if($modelshipping[0]->street_address == '')
                //$error2 = json_decode(CActiveForm::validateTabular($modelshipping, '', false), true);
                $error = CJSON::encode(array_merge_recursive($error1, $error2, $error3));
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    /*
     * function to list vendor conatcts
     */

    function actionGetContactList()
    {
        $model = new VendorContact();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $vendor_id = $_POST['vendor_id'];
        $columns = array(
            // datatable column index  => database column name
            0 => 'person_name',
            1 => 'designation',
            2 => 'contact_phone_no',
            3 => 'isActive',
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        $condition = 't.vendor_id = "' . $vendor_id . '"';
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $condition .= " AND (person_name LIKE '%" . $searchString . "%' OR designation LIKE '%" . $searchString . "%' OR contact_phone_no LIKE '%" . $searchString . "%')";
        }
        $or = 't.isActive ';
        $count = $model->count(array('condition' => $condition));
        $model = $model->with('vendor')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => $or));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        foreach ($model as $row) {

            $st = "Blocked";
            if ($row['isActive'] == "Y") {
                $st = "Active";
            }

            $rowData[] = array($row['person_name'], $row['designation'], $row['contact_phone_no'], $st, $row['id']);
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    /*
     * function to save vendor contact
     */

    public function actionSaveContact()
    {
        $model = new VendorContact();
        $date = date("Y-m-d H:i:s");
        /*         * ********** START Code for Save ************** */
        if (isset($_POST['VendorContact'])) {

            if ((int) @$_POST['VendorContact']['id'] > 0) {
                $model->id = (int) $_POST['VendorContact']['id'];
                $model = $model->findByPK($model->id);
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = $date;
                $audit_type = 'UPDATED';
            } else {
                $audit_type = 'CREATED';
                //$model->crm_user_id = Yii::app()->user->id;
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = $date;
            }
            $model->vendor_id = $_POST['hid_vendor_id'];
            $model->attributes = $_POST['VendorContact'];
            $model->isActive = $_POST['VendorContact']['isActive'];
            //$model->notes = $_POST['VendorContact']['notes'];
            if ($model->save()) {
                // inserting to audit log
                AuditLog::saveAuditLogs(
                    'VENDOR',
                    Yii::app()->user->id,
                    $audit_type,
                    " Contact with No: - {$model->id}  "
                );
                // end audit log
                $jsonData['status'] = 'success';
                $jsonData['frm'] = $_POST['vendor_contact_form'];
                $jsonData['id'] = $model->id;
                echo CJSON::encode($jsonData);
            } else {
                $error = CActiveForm::validate($model, '', false);
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    public function actionSaveNote()
    {
        $model = new FileNotes();
        $date = date("Y-m-d H:i:s");
        /*         * ********** START Code for Save ************** */
        if (isset($_POST['FileNotes'])) {


            //$model->crm_user_id = Yii::app()->user->id;
            $model->created_by = Yii::app()->user->id;
            $model->created_datetime = $date;
            $model->attributes = $_POST['FileNotes'];
            $model->customer_vendor_type = 2;
            //$model->notes = $_POST['VendorContact']['notes'];
            if ($model->save()) {
                //die();
                $jsonData['status'] = 'success';
                $jsonData['frm'] = $_POST['notes_details_2'];
                $jsonData['id'] = $model->id;
                echo CJSON::encode($jsonData);
            } else {
                $error = CActiveForm::validate($model, '', false);
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    /*
     * function to delete vendor contact
     */

    public function actionDeleteContact()
    {
        $id = $_POST['id'];
        $model = new VendorContact();
        $model->deleteByPk($id);
        echo "success";
    }

    /*
     * function to delete vendor
     */

    public function actionDeleteVendor()
    {
        $id = $_POST['id'];
        $model = Vendor::model()->findByPk($id);
        if (!empty($model)) {
            $model->isActive = "N";
            $model->save(false);
            echo "success";
        } else {
            echo "fail";
        }
    }

    public function actionGetVendor()
    {
        $from = $_GET['frm'];
        $searchTerm = $_GET['term'];
        $condition = 'vendor_name LIKE "%' . $searchTerm . '%"';
        $model = new Vendor();
        $model = $model->findAll(array('condition' => $condition));
        $i = 0;
        foreach ($model as $eachModel) {
            $data[$i]['value'] = $eachModel->id;
            $vendor_location = ucfirst(trim($eachModel->vendor_location));
            $vendor_name = $eachModel->vendor_name;
            if (!empty($customer_location)) {
                $vendor_name = $eachModel->vendor_name . " [" . $vendor_location . "]";
            }

            $data[$i]['label'] = $vendor_name;
            $i++;
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }

    public function actionGetCurrency()
    {
        $vendor_id = $_POST['vendor_id'];
        $data = array();
        $model = new PurchasingOrder;
        if ($vendor_id > 0) {
            $vendor = Vendor::model()->findByPk($vendor_id);
            //$modshipaddress = VendorShippingDetails::model()->findByPk($vendor_id);
            $data['billaddress'] = $vendor->vendor_address . ", PO Box : " . $vendor->vendor_postal_code . "," . $vendor->vendor_city . "," . $vendor->country->country_name;
            $data['shipaddress'] = $vendor->vendor_address . ", PO Box : " . $vendor->vendor_postal_code . "," . $vendor->vendor_city . "," . $vendor->country->country_name;
            //$data['shipaddress'] = $modshipaddress->street_address . ", PO Box : " . $modshipaddress->postal_code . "," . $modshipaddress->city . "," . $modshipaddress->country->country_name;

            $model->currency = $vendor->vendor_currency_id;
            $model->payment_terms = $vendor->vendor_payment_term;
            $data['currency'] = CHtml::activedropDownList($model, 'currency', MasCurrency::getCurrency(), array('onChange' => 'getExchangeRate(this.id)', 'class' => 'tooltipster', 'title' => 'Currency', 'data-label' => 'Currency', 'prompt' => '-select-'));
            $data['payterm'] = CHtml::activedropDownList($model, 'payment_terms', MasPaymentTerm::getPaymentTerms(), array('class' => '', 'title' => 'Select Payment Terms', 'data-label' => 'Payment Terms <span style="color:red;">*</span> '));
            $data['exchange_rate'] = $vendor->currency_detail->exchange_rate;

            //code added by mereena on 04/02/2020
            $models = VendorContact::getVendorContacts($vendor_id);

            $drop = '<li class="col-sm-3">';
            $model = new PurchasingOrder;
            $drop .= CHtml::activedropDownList($model, 'vendor_contact_id', $models, array('class' => 'tooltipster', 'title' => 'Please Select Contact', 'data-label' => 'Contact <span style="color:red">*</span>', 'data-search' => true));
            $drop .= '</li>';
            $data['contact'] = $drop;
            //end
        }
        echo CJSON::encode($data);
    }


    public function actionGetCurrencyWithAddress()
    {
        $vendor_id = $_POST['vendor_id'];
        $data = array();
        $model = new PurchasingOrder;
        if ($vendor_id > 0) {
            $vendor = Vendor::model()->findByPk($vendor_id);
            //$modshipaddress = VendorShippingDetails::model()->findByPk($vendor_id);
            $data['billaddress'] = $vendor->vendor_address;
            $data['shipaddress'] = $vendor->vendor_address . ", PO Box : " . $vendor->vendor_postal_code . "," . $vendor->vendor_city . "," . $vendor->country->country_name;
            //$data['shipaddress'] = $modshipaddress->street_address . ", PO Box : " . $modshipaddress->postal_code . "," . $modshipaddress->city . "," . $modshipaddress->country->country_name;

            $model->currency = $vendor->vendor_currency_id;
            $model->payment_terms = $vendor->vendor_payment_term;
            $data['currency'] = CHtml::activedropDownList($model, 'currency', MasCurrency::getCurrency(), array('onChange' => 'getExchangeRate(this.id)', 'class' => 'tooltipster', 'title' => 'Currency', 'data-label' => 'Currency', 'prompt' => '-select-'));
            $data['payterm'] = CHtml::activedropDownList($model, 'payment_terms', MasPaymentTerm::getPaymentTerms(), array('class' => '', 'title' => 'Select Payment Terms', 'data-label' => 'Payment Terms <span style="color:red;">*</span> '));
            $data['exchange_rate'] = $vendor->currency_detail->exchange_rate;

            //code added by mereena on 04/02/2020
            $models = VendorContact::getVendorContacts($vendor_id);

            $drop = '<li class="col-sm-3">';
            $model = new PurchasingOrder;
            $drop .= CHtml::activedropDownList($model, 'vendor_contact_id', $models, array('class' => 'tooltipster', 'title' => 'Please Select Contact', 'data-label' => 'Contact <span style="color:red">*</span>', 'data-search' => true));
            $drop .= '</li>';
            $data['contact'] = $drop;
            //end
        }
        echo CJSON::encode($data);
    }

    public function actionGetVendorCurrency()
    {
        $vendor_id = $_POST['vendor_id'];
        $data = array();
        $model = new DirectPurchaseOrderGeneral;
        if ($vendor_id > 0) {
            $vendor = Vendor::model()->findByPk($vendor_id);
            //$modshipaddress = VendorShippingDetails::model()->findByPk($vendor_id);
            $data['billaddress'] = $vendor->vendor_address . ", PO Box : " . $vendor->vendor_postal_code . "," . $vendor->vendor_city . "," . $vendor->country->country_name;
            $data['shipaddress'] = $vendor->vendor_address . ", PO Box : " . $vendor->vendor_postal_code . "," . $vendor->vendor_city . "," . $vendor->country->country_name;

            //$data['shipaddrss'] = $modshipaddress->street_address . ", PO Box : " . $modshipaddress->postal_code . "," . $modshipaddress->city . "," . $modshipaddress->country->country_name;

            $model->currency = $vendor->vendor_currency_id;
            //$model->payment_terms = $vendor->vendor_payment_term;
            $data['currency'] = CHtml::activedropDownList($model, 'currency', MasCurrency::getCurrency(), array('onChange' => 'getExchangerate(this.value)', 'class' => 'tooltipster', 'title' => 'Currency', 'data-label' => 'Currency'));
            //$data['payterm'] = CHtml::activedropDownList($model, 'payment_terms', MasPaymentTerm::getPaymentTerms(), array('class' => '','title' => 'Select Payment Terms','data-label'=>'Payment Terms <span style="color:red;">*</span> '));
            $data['exchange_rate'] = $vendor->currency_detail->exchange_rate;
        }
        echo CJSON::encode($data);
    }

    public function actionSetMenu()
    {
        echo Yii::app()->session['selected_menu'] = $_POST['menu_name'];
    }

    public function actionUploadSupplierDocuments($folder = null)
    {
        Yii::import("ext.EAjaxUpload.qqFileUploader");
        $field_id = "";
        if (isset($_GET['field_id'])) {
            $field_id = Yii::app()->request->getParam('field_id');
        }

        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
        // make the directory to store the pic:
        if (!is_dir($folder)) {
            mkdir($folder, 0777, TRUE);
        }
        $allowedExtensions = array("jpg", "png", "doc", "docx", "xls", "xlsx", "pdf", "bmp", "jpeg"); //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);

        if ($result['success']) {
            $originalFile = $result['filename'];
            $extension = pathinfo($originalFile, PATHINFO_EXTENSION);
            $datePrefix = date('Y-m-d') . '-';

            $newFileName = $datePrefix . $originalFile;
            $oldPath = $folder . $originalFile;
            $newPath = $folder . $newFileName;

            if (file_exists($oldPath)) {
                rename($oldPath, $newPath);
            }

            $result['filename'] = $newFileName;
            $result['fileType'] = strtolower($extension);
        }

        //$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/supplierdocuments/' . $fileName;
        echo $return; // it's array
    }

    public function actionCreateDocumentForm()
    {

        $model = new Vendor();
        $modeldoc = new SupplierDocs();
        $id = (int) Yii::app()->request->getParam('id');
        $supplier_id = (int) Yii::app()->request->getParam('c_id');
        if ($id > 0) {
            $modeldoc = $modeldoc->findByPk($id);
            $supplier_id = $modeldoc->supplier_id;
        }
        if ($supplier_id > 0) {
            $model = $model->findByPk($supplier_id);
            $modeldoc->supplier_id = $supplier_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, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false, '*.css' => false);
        $this->render('doc_form', array('model' => $model, 'modeldoc' => $modeldoc, 'c_id' => $supplier_id));
    }

    public function actionSaveDocForm()
    {
        $model = new SupplierDocs();
        $id = $_POST['SupplierDocs']['id'];
        if ($_POST['SupplierDocs']['id'] > 0) {
            $model = $model->findByPk($id);
        }
        $model->attributes = $_POST['SupplierDocs'];
        $model->score = $_POST['SupplierDocs']['score'];
        if ($_POST['SupplierDocs']['from_date'] != '00/00/0000' && $_POST['SupplierDocs']['from_date'] != '') {
            $model->from_date = str_replace('/', '-', $_POST['CustomerDocs']['from_date']);
            $model->from_date = date("Y-m-d", strtotime($model->from_date));
        }
        if ($_POST['SupplierDocs']['to_date'] != '00/00/0000' && $_POST['SupplierDocs']['to_date'] != '') {
            $model->to_date = str_replace('/', '-', $_POST['SupplierDocs']['to_date']);
            $model->to_date = date("Y-m-d", strtotime($model->to_date));
        }
        if ($model->save()) {
            $jsonData['status'] = 'success';
            $jsonData['frm'] = $_POST['SupplierDocs'];
            $jsonData['id'] = $model->id;
            echo CJSON::encode($jsonData);
        } else {
            $error = CActiveForm::validate($model, '', false);
            if ($error != '[]')
                echo $error;
        }
    }

    public function actionGetDocsList()
    {
        $model = new SupplierDocs();
        $vendor_id = $_POST['vendor_id'];
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $columns = array(
            // datatable column index  => database column name
            0 => 't.id',
            1 => 'document_type',
            2 => 'document_no',
            3 => 'to_date',
        );
        $filterColumn = $columns[$_POST['order'][0]['column']];
        $filterOrder = $_POST['order'][0]['dir'];
        $orderBy = $filterColumn . " " . $filterOrder;
        if ($vendor_id > 0) {
            $condition = 't.supplier_id=' . $vendor_id;
        } else {
            $condition = '1=1';
        }
        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $condition .= " AND (t.document_no LIKE '%" . $searchString . "%')";
        }
        $count = $model->with('sup_details')->count(array('condition' => $condition));
        $model = $model->with('sup_details')->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 't.id DESC'));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = 1;
        foreach ($model as $row) {
            $type = $row['document_type'];
            $model1 = MasDocumentType::model()->findAll(array('condition' => 'id=' . $type));
            $document_type = $model1[0]['document_type'];
            // $edit = '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" title ="Edit" onclick="loadPopupModal(\'vendor/createDocumentform&id=' . $row['id'] . '\',\'' . $row['id'] . ' : ' . $row['sup_details']['vendor_name'] . '\',\'lg\')"><i class="fa fa-pencil"></i></button> ';
            // $edit .= ' <a title= "Download" href ="' . Yii::app()->createUrl('vendor/downloaddocument&id=' . $row['id']) . '" class=" btn btn-primary btn-xs"><i class="fa fa-download"></i></a>';
            $rowData[] = array($m, $document_type, $row['document_no'], date("d/m/Y", strtotime($row['to_date'])), $edit, $row['id']);
            $m++;
        }
        $data['data'] = $rowData;
        echo json_encode($data);
    }

    public function actionDownloadDocument()
    {
        $id = (int) Yii::app()->request->getParam('id');
        $arr_employee_doc = SupplierDocs::model()->findByPk($id);
        $file = $arr_employee_doc->document;
        $arr_doc_val = explode(',', $arr_employee_doc->document);
        $path = Yii::getPathOfAlias('webroot') . "/uploads/supplierdocuments/" . $file;
        header("Content-type:application/octet-stream"); //for txt file
        header("Content-Type: application/download");
        //header('Content-Type:text/plain; charset=ISO-8859-15');
        //if you want to read text file using text/plain header
        header('Content-Disposition: attachment; filename="' . basename($path) . '"');
        header('Content-Length: ' . filesize($path));
        readfile($path);
        Yii::app()->end();
    }

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

    public function actionGetVendorByType()
    {
        $agent_id = (int) Yii::app()->request->getParam('agent_id');
        $model = new PurchasingOrder();
        $modelVendor = Vendor::model()->findAll(array('condition' => 'type=' . $agent_id));
        $vendor_list = CHtml::listData($modelVendor, 'id', 'vendor_name');
        $data['vendorlist'] = CHtml::activedropDownList($model, 'vendor_id', $vendor_list, array('onChange' => 'getContactCurrencyDetails(this.value)', 'class' => 'tooltipster', 'title' => 'Supplier', 'data-label' => 'Supplier <span style="color:red;">*</span>', 'prompt' => '-select-', 'data-search' => true));
        echo CJSON::encode($data);
    }


    public function actionMenu()
    {
        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, '*jquery-2.1.4.min.js' => false, 'jquery-2.1.4.min.js' => false, '*.css' => false);
        $this->renderPartial('menu');

    }

    public function actionUploadVendor()
    {
        //added by nisha on 28-02-2023
        $model = new Vendor();
        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_vendor', array('model' => $model), false, true);
    }

    public function actionDefaultContact()
    {
        $id = Yii::app()->request->getParam('id');
        $model = VendorContact::model()->findByPk($id);
        if (empty($model)) {
            echo json_encode([
                "status" => "error",
                "message" => "Contact not found."
            ]);
        } else {
            $model->setDefault();
            echo json_encode([
                "status" => "success",
                "message" => $model->person_name . " successfully changed to default contact."
            ]);
        }
    }

    public function actionDashboardSettingsRating()
    {
        $data = array();
        $id = Yii::app()->request->getParam('id');
        $type_id = Yii::app()->request->getParam('type_id');
        $vendor_id = Yii::app()->request->getParam('vendor_id');
        $rating = Yii::app()->request->getParam('rating');
        $model = new MasAidashboardSettingsData();
        $sql = "SELECT * FROM {{mas_aidashboard_settings_data}} WHERE rating_id = " . $type_id . " AND customer_id = " . $vendor_id;
        $command = Yii::app()->db->createCommand($sql);
        $modelData = $command->queryRow();
        if (empty($modelData)) {
            $model->rating = $rating;
            $model->rating_id = $type_id;
            $model->customer_id = $vendor_id;
            $model->created_by = Yii::app()->user->id;
            $model->created_date_time = date('Y-m-d h:i:s');
            $model->save();
            $data['success'] = true;
        } else {
            $model->id = $modelData['id'];
            $model->rating_id = $modelData['rating_id'];
            $model->customer_id = $modelData['customer_id'];
            $model->rating = $rating;
            $model->updated_by = Yii::app()->user->id;
            $model->updated_date_time = date('Y-m-d h:i:s');
            $sql = "UPDATE {{mas_aidashboard_settings_data}} SET rating = " . $rating . ", updated_by =" . Yii::app()->user->id . ", updated_date_time = '" . date('Y-m-d h:i:s') . "' WHERE id = " . $id;
            Yii::app()->db->createCommand($sql)->execute();
            $data['success'] = true;
        }
        $ratingScore = $model->getDashboardSettingsRating($vendor_id);
        $data['rating_score'] = $ratingScore;
        echo json_encode($data);
    }
    public function actionDownloadErrorCsv()
    {
        $file_name = $event_id = Yii::app()->request->getParam('id');
        $error_url = Yii::app()->basePath . '/../uploads/vendor_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
        $person_name = $this->sanitizeData($data[0]);
        $vendor_phone_no = isset($data[1]) ? $this->sanitizeNumber($data[1]) : '';
        $vendor_email_id = isset($data[2]) ? $this->sanitizeData($data[2]) : '';
        $vendor_web = trim($data[3]);
        $vendor_location = isset($data[4]) ? $this->sanitizeData($data[4]) : '';
        $vendor_trn_no = isset($data[5]) ? $this->sanitizeNumber($data[5]) : '';
        $vendor_address = isset($data[6]) ? $this->sanitizeData($data[6]) : '';
        $vendor_city = isset($data[7]) ? $this->sanitizeData($data[7]) : '';
        $vendor_postal_code = isset($data[8]) ? $this->sanitizeNumber($data[8]) : '';
        $vendor_country = isset($data[9]) ? $this->sanitizeData($data[9]) : '';
        $vendor_bank_name = isset($data[10]) ? $this->sanitizeData($data[10]) : '';
        $vendor_bank_branch_name = isset($data[11]) ? $this->sanitizeData($data[11]) : '';
        $vendor_bank_account_no = isset($data[12]) ? $this->sanitizeData($data[12]) : '';
        $vendor_bank_ifsc = isset($data[13]) ? $this->sanitizeNumber($data[13]) : '';
        $vendor_currency_id = isset($data[14]) ? $this->sanitizeData($data[14]) : '';
        $vendor_payment_term = isset($data[15]) ? $this->sanitizeData($data[15]) : '';

        $contact_person = isset($data[16]) ? $this->sanitizeData($data[16]) : '';
        $contact_person_mobile = isset($data[17]) ? $this->sanitizeNumber($data[17]) : '';
        $contact_person_phone = isset($data[18]) ? $this->sanitizeNumber($data[18]) : '';
        $contact_person_designation = isset($data[19]) ? $this->sanitizeData($data[19]) : '';
        $contact_person_department = isset($data[20]) ? $this->sanitizeData($data[20]) : '';
        $contact_person_email = isset($data[21]) ? $this->sanitizeData($data[21]) : '';


        // Validate 'code'
        if (empty($person_name)) {
            $log_remarks[] = "Vendor Name is required.";
        }

        if (empty($vendor_phone_no)) {
            $log_remarks[] = "Vendor Phone is required.";
        }

        if (!empty($vendor_country)) {
            $country_exist = MasCountry::model()->find(
                'LOWER(country_name) = :country OR LOWER(country_code) = :country',
                [':country' => strtolower(trim($vendor_country))]
            );
            if (empty($country_exist)) {
                $log_remarks[] = "Invalid Country Code.";
            }
        } else {
            $log_remarks[] = "Vendor Country is required.";
        }

        if (!empty($vendor_bank_name)) {
            $payment_exist = MasBank::model()->find(
                'LOWER(bank_name) = :bank_name',
                [':bank_name' => strtolower($vendor_bank_name)]
            );
            if (empty($payment_exist)) {
                $log_remarks[] = "Bank is not valid.";
            }
        }

        if (!empty($vendor_currency_id)) {
            $currency_exist = MasCurrency::model()->find(
                'LOWER(currency_code) = :currency_code',
                [':currency_code' => strtolower($vendor_currency_id)]
            );
            if (empty($currency_exist)) {
                $log_remarks[] = "Currency is not valid.";
            }
        }

        if (!empty($vendor_payment_term)) {
            $payment_exist = MasPaymentTerm::model()->find(
                'LOWER(payment_code) = :payment_code OR LOWER(payment_terms) = :payment_code',
                [':payment_code' => strtolower($vendor_payment_term)]
            );
            if (empty($payment_exist)) {
                $log_remarks[] = "Payment Term is not valid.";
            }
        }


        // var_dump($log_remarks);

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

    public function actionUploadVendorCsv($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);
    }
    public function actionDownloadSampleCsv()
    {
        $filename = 'vendor_list.csv';
        header("Content-type: application/vnd.ms-excel");
        header("Content-Disposition: attachment; filename=\"" . $filename . "\"");
        echo 'Vendor Name*,Phone *,Email,Website,Location,TRN No,Address , City, P.O Box, Country Code,Bank,Branch,Acc no,IFSC Code , Currency, Payment Terms,Contact Person, Contact Person Mobile, Contact Person Phone, Designation,Department,Contact Person Email';
        Yii::app()->end();
    }
        public function actionSaveVendorUploadCsv()
    {
        $file_name = Yii::app()->request->getParam('filename');
        $batch = (int) Yii::app()->request->getParam('batch', 1);
        $url = Yii::app()->basePath . '/../uploads/vendor_csv/' . $file_name;
        $mas_vendor_list = $this->readVendorCSV($url);
        $error_url = Yii::app()->basePath . '/../uploads/vendor_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_vendor_list)) {
            $header = array_shift($mas_vendor_list); // Remove header row only once
        }
        $total_records = count($mas_vendor_list);
        $start_index = ($batch - 1) * $batch_size;
        $batch_data = array_slice($mas_vendor_list, $start_index, $batch_size);
        // print_r($batch_data);
        // die();
        foreach ($mas_vendor_list as $index => $data) {
            if (!empty($data)) {
                $line_number = $index + 2; // Adjust for header row
                $log_remarks = [];

                // Sanitize and validate data

                if ($batch == 1) {
                    $log_remarks = $this->validateAndPrepareLog($data, $log_remarks);
                }


                if (empty($log_remarks)) {
                    $error_list[$line_number] = [
                        'person_name' => $data[0],
                        'person_phone' => $data[1],
                        'person_email' => $data[2],
                        'website' => $data[3],
                        'location' => $data[4],
                        'person_trn_no' => $data[5],
                        'person_address' => $data[6],
                        'person_city' => $data[7],
                        'person_PO_box' => $data[8],
                        'person_country' => $data[9],
                        'person_bank' => $data[10],
                        'person_branch' => $data[11],
                        'person_acc_no' => $data[12],
                        'person_ifsc_code' => $data[13],
                        'person_currency' => $data[14],
                        'person_payment_terms' => $data[15],
                        'contact_person' => $data[16],
                        'contact_person_mobile' => $data[17],
                        'contact_person_phone' => $data[18],
                        'contact_person_designation' => $data[19],
                        'contact_person_department' => $data[20],
                        'contact_person_email' => $data[21],
                        'log_remarks' => ''
                    ];
                } else {
                    $error_occurred = true;
                    $error_count++;
                    $error_list[$line_number] = [
                        'person_name' => $data[0],
                        'person_phone' => $data[1],
                        'person_email' => $data[2],
                        'website' => $data[3],
                        'location' => $data[4],
                        'person_trn_no' => $data[5],
                        'person_address' => $data[6],
                        'person_city' => $data[7],
                        'person_PO_box' => $data[8],
                        'person_country' => $data[9],
                        'person_bank' => $data[10],
                        'person_branch' => $data[11],
                        'person_acc_no' => $data[12],
                        'person_ifsc_code' => $data[13],
                        'person_currency' => $data[14],
                        'person_payment_terms' => $data[15],
                        'contact_person' => $data[16],
                        'contact_person_mobile' => $data[17],
                        'contact_person_phone' => $data[18],
                        'contact_person_designation' => $data[19],
                        'contact_person_department' => $data[20],
                        'contact_person_email' => $data[21],
                        '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/vendor_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 = ['Vendor Name*', 'Phone *', 'Email', 'Website', 'Location', 'TRN No', 'Address', 'City', 'P.O Box', 'Country Code', 'Bank', 'Branch', 'Acc no', 'IFSC Code', 'Currency', 'Payment Terms', 'Contact Person', 'Contact Person Mobile', 'Contact Person Phone', 'Designation', 'Department', 'Contact Person Email', '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['person_name'],
                    $error_detail['person_phone'],
                    $error_detail['person_email'],
                    $error_detail['website'],
                    $error_detail['location'],
                    $error_detail['person_trn_no'],
                    $error_detail['person_address'],
                    $error_detail['person_city'],
                    $error_detail['person_PO_box'],
                    $error_detail['person_country'],
                    $error_detail['person_bank'],
                    $error_detail['person_branch'],
                    $error_detail['person_acc_no'],
                    $error_detail['person_ifsc_code'],
                    $error_detail['person_currency'],
                    $error_detail['person_payment_terms'],
                    $error_detail['contact_person'],
                    $error_detail['contact_person_mobile'],
                    $error_detail['contact_person_phone'],
                    $error_detail['contact_person_designation'],
                    $error_detail['contact_person_department'],
                    $error_detail['contact_person_email'],
                    $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('vendor/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
        }

        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
                $person_name = $this->sanitizeData($data[0]);
                $vendor_phone_no = isset($data[1]) ? $this->sanitizeNumber($data[1]) : '';
                $vendor_email_id = isset($data[2]) ? $this->sanitizeData($data[2]) : '';
                $vendor_web = trim($data[3]);
                $vendor_location = isset($data[4]) ? $this->sanitizeData($data[4]) : '';
                $vendor_trn_no = isset($data[5]) ? $this->sanitizeNumber($data[5]) : '';
                $vendor_address = isset($data[6]) ? $this->sanitizeData($data[6]) : '';
                $vendor_city = isset($data[7]) ? $this->sanitizeData($data[7]) : '';
                $vendor_postal_code = isset($data[8]) ? $this->sanitizeNumber($data[8]) : '';
                $vendor_country = isset($data[9]) ? $this->sanitizeData($data[9]) : '';
                $vendor_bank_name = isset($data[10]) ? $this->sanitizeData($data[10]) : '';
                $vendor_bank_branch_name = isset($data[11]) ? $this->sanitizeData($data[11]) : '';
                $vendor_bank_account_no = isset($data[12]) ? $this->sanitizeData($data[12]) : '';
                $vendor_bank_ifsc = isset($data[13]) ? $this->sanitizeNumber($data[13]) : '';
                $vendor_currency_id = isset($data[14]) ? $this->sanitizeData($data[14]) : '';
                $vendor_payment_term = isset($data[15]) ? $this->sanitizeData($data[15]) : '';

                $contact_person = isset($data[16]) ? $this->sanitizeData($data[16]) : '';
                $contact_person_mobile = isset($data[17]) ? $this->sanitizeNumber($data[17]) : '';
                $contact_person_phone = isset($data[18]) ? $this->sanitizeNumber($data[18]) : '';
                $contact_person_designation = isset($data[19]) ? $this->sanitizeData($data[19]) : '';
                $contact_person_department = isset($data[20]) ? $this->sanitizeData($data[20]) : '';
                $contact_person_email = isset($data[21]) ? $this->sanitizeData($data[21]) : '';



                // country
                $country_exist = MasCountry::model()->find(
                    'LOWER(country_name) = :country OR LOWER(country_code) = :country',
                    [':country' => strtolower(trim($vendor_country))]
                );
                if (!empty($country_exist)) {
                    $vendor_country = $country_exist->id;
                }
                // var_dump($vendor_country);
                // die()
                // bank
                if (!empty($vendor_bank_name)) {
                    $bank_exist = MasBank::model()->find(
                        'LOWER(bank_name) = :bank_name',
                        [':bank_name' => strtolower($vendor_bank_name)]
                    );
                    if (!empty($bank_exist)) {
                        $vendor_bank_name = $bank_exist->id;
                    }
                }

                // currency
                $currency_exist = MasCurrency::model()->find(
                    'LOWER(currency_code) = :currency_code',
                    [':currency_code' => strtolower($vendor_currency_id)]
                );
                if (!empty($currency_exist)) {
                    $vendor_currency_id = $currency_exist->id;
                }

                // payment terms
                if (!empty($vendor_payment_term)) {
                    $payment_exist = MasPaymentTerm::model()->find(
                        'LOWER(payment_code) = :payment_code OR LOWER(payment_terms) = :payment_code',
                        [':payment_code' => strtolower($vendor_payment_term)]
                    );
                    if (!empty($payment_exist)) {
                        $vendor_payment_term = $payment_exist->id;
                    }
                }


                if ($this->isTypeNameExists($person_name)) {
                    $existing_count++;
                } else {
                    // Save to DB
                    $model = new Vendor();
                    $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->vendor_name = ucfirst(strtolower($person_name));
                    $model->vendor_phone_no = $vendor_phone_no;
                    $model->vendor_email_id = $vendor_email_id;
                    $model->vendor_web = $vendor_web;
                    $model->vendor_trn_no = $vendor_trn_no;
                    $model->vendor_address = $vendor_address;
                    $model->vendor_city = $vendor_city;
                    $model->vendor_postal_code = $vendor_postal_code;
                    $model->vendor_country = $vendor_country;
                    $model->vendor_bank_name = $vendor_bank_name;
                    $model->vendor_bank_branch_name = $vendor_bank_branch_name;
                    $model->vendor_bank_account_no = $vendor_bank_account_no;
                    $model->vendor_bank_ifsc = $vendor_bank_ifsc;
                    $model->vendor_currency_id = $vendor_currency_id;
                    $model->vendor_payment_term = $vendor_payment_term;

                    $model->vendor_location = $vendor_location;
                    $model->type = '1';

                    if ($model->save()) {
                        $modelVendorContact = new VendorContact();
                        $modelVendorContact->created_by = Yii::app()->user->id;
                        $modelVendorContact->updated_by = Yii::app()->user->id;
                        $modelVendorContact->created_date_time = date('Y-m-d H:i:s');
                        $modelVendorContact->updated_date_time = date('Y-m-d H:i:s');
                        $modelVendorContact->vendor_id = $model->id;
                        $modelVendorContact->person_name = empty($contact_person) ? 'Sales/Account' : $contact_person;
                        $modelVendorContact->contact_mobile_no = empty($contact_person_mobile) ? $model->vendor_phone_no : $contact_person_mobile;
                        $modelVendorContact->contact_phone_no = $contact_person_phone;
                        $modelVendorContact->designation = $contact_person_designation;
                        $modelVendorContact->department = $contact_person_department;
                        $modelVendorContact->contact_email_id = $contact_person_email;
                        $modelVendorContact->isActive = 'Y';
                        if ($modelVendorContact->save(false)) {
                            $errors = $modelVendorContact->getErrors();
                            foreach ($errors as $field => $messages) {
                                foreach ($messages as $message) {
                                    echo 'modelVendorContact' . $message;
                                }
                            }
                        }

                        $success_count++;
                    } else {
                        $errors = $model->getErrors();
                        foreach ($errors as $field => $messages) {
                            foreach ($messages as $message) {
                                echo 'model :' . $message;
                            }
                        }
                    }
                }


            }
        }
        // $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('vendor/SaveVendorUploadCsv', [
                                '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,
            ]);
        } 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 readVendorCSV($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;
    }
}
