<?php

class SaleNoteAjax extends SaleNoteRepository {
    public $formProduct = null;
    public $formSale = null;
    public $formVendor = null;        

    public function __construct() {
        parent::__construct();
    }

    public function getResponse($request, $options) {
        return $this->$request($options);
    }

    public function addCustomerPaymentFromInvoice() {
        try {
            $customerPaymentForm = new CustomerPaymentForm();
            $data = $_POST;           

            $customerPaymentForm->populate($data);            

            if(isset($data['document_type']) && $data['document_type'] != ''){
               /*Este parametro lo envio cuando se paga desde Cuentas x cobrar*/
                $fromCuentasPorCobrar = true;
                $document_type = $data['document_type'];                              

                if($document_type == 'notaventa'){
                    $saleNoteRepo = new SaleNoteRepository();
                    $saleNoteDbData = $saleNoteRepo->getById($data['invoice_id']);
                                        $customer_id = $saleNoteDbData['customer'];
                }elseif($document_type == 'chargenote'){
                    $saleNoteRepo = new ChargeNoteRepository();
                    $saleNoteDbData = $saleNoteRepo->getById($data['invoice_id']);
                    $customer_id = $saleNoteDbData['customer_id'];
                }
            }else{
                $saleNoteRepo = new SaleNoteRepository();
                $saleNoteDbData = $saleNoteRepo->getById($data['invoice_id']);
                $document_type = 'notaventa';
                $customer_id = $saleNoteDbData['customer'];
            }            

            if(in_array($saleNoteDbData['status'], ['3']) || in_array($saleNoteDbData['status_payment'], ['2'])) {
                throw new Exception("La nota ya no es editable (Cancelada o Pagada), no esta permitido agregar pagos.");
            }

            if($customerPaymentForm->isValid()) {
                $customerPayment = new CustomerPaymentRepository();        
                $data['customer'] = $customer_id;
                $data['pago'] = ["{$document_type}_" . $saleNoteDbData['id'] => $data['amount']];                

                $istFacturas = null;
                unset($data['document_type']);
                
                //UG Aqui actualizo salenote, para colocar el nuevo total y la comision correspondiente
                $saleNoteRepo = new SaleNoteRepository();
                //; 
                $saleNoteRepo->setOptions($saleNoteDbData);   
                $_updateSaleNote = $saleNoteRepo->getOptions();
              
                $_updateSaleNote['card_payment_fee'] = $data['card_payment_fee'];
                $_updateSaleNote['total_card_payment'] = $data['total_card_payment'];

                //UG Eliminamos los campos que no se van a ocupar insertan en customer_payment
                unset($data['real_amount']);
                unset($data['card_payment_fee']);
                unset($data['total_card_payment']);          

                if ($customerPayment->save($data)){
                    //UG Actualizamos los dos campos en salenote
                    $result_ = $saleNoteRepo->updateString(array('card_payment_fee'=>$_updateSaleNote['card_payment_fee'],'total_card_payment' => $_updateSaleNote['total_card_payment']),'id = "'.$data["invoice_id"].'"','sales_notes'); //no tengo id porque viene de post                                       
                    $this->flashmessenger->addMessage(['success' => "Pago registrado de forma satisfactoria con el No.: {$customerPayment->getLastInsertId()}"]);

                    if(isset($fromCuentasPorCobrar)){
                        $repotAjax = new ReportAjax();
                        $istFacturas = $repotAjax->getListFacturasByCustomerForAPReport(array('customer'=>$customer_id))['listFacturas'];
                    } 

                    return [
                        'response' => true,
                        'message' => $this->flashmessenger->getMessageString(),
                        'listFacturas'=>$istFacturas
                    ];
                }
            } else {
                return [
                    'response' => false,
                    'message' => $this->flashmessenger->getMessageString(),
                ];
            }
        } catch (Exception $e) {
            $this->flashmessenger->addMessage([
                'danger' => $e->getMessage()
            ]);
            return [
                'response' => false,
                'message' => $this->flashmessenger->getMessageString(),
            ];
        }
    }

    public function setSaleNoteDetails(array $options) {
        $data = array();
         foreach($options['options'] as $row){ 
            /*Cuando se envia mas de una opcion en un select, el nombre  del campo viene con [],lo que hacemos es quitarlo;
              Cuando viene mas de una opcion en el select que se hace es meter los valores seleccionados a una cadena, 
              y los valores se separan por comas*/
            $row['name'] = str_replace('[]', '', $row['name']);
            
            if(key_exists($row['name'], $data)){
                $data[$row['name']] .= ",".$row['value'];   
            }else{
                $data[$row['name']] = $row['value']; 
            }            
        }       
        
        
        if($data['type'] == 'product'){
            $meRepo = new MachenaryAndEquipmentRepository();
            $producto = $meRepo->getById($data['id_product']);                        
            
            $tools = new Tools();
            $rentTermData = $meRepo->getRentTermById($data['rent_term']);
            if(!empty($data['service_start_date'])){
                $serviceStartDate = explode(' ',$data['service_start_date']);
                $serviceStartDate = new DateTime($tools->setFormatDateToDB($serviceStartDate[0]));

                if(!empty($rentTermData['days'])){
                    $days = (float)$rentTermData['days'] * (float)$data['quantity'];
                    $serviceStartDate->modify("+ {$days} days");
                    $data['service_end_date'] = $serviceStartDate->format('Y-m-d');
                }                    
            }        
                
        }elseif($data['type'] == 'service'){
            $productRepo = new ProductRepository();
            $producto = $productRepo->getById($data['id_product']);
        }              

        if($producto){
            if($data['quantity']){
                $data['description'] = $producto['description'];
                $this->insertDetalle($data);
                $compraDetalles = $this->getSaleNoteDetails($data['token_form']);
                $detalles = $this->listVentaDetalles($compraDetalles);

                $json = array(
                    'response' => true,
                    'saleNoteDetails' => $detalles['listDetails'],
                    'totalItems'=>number_format($detalles['totalItems'],2),
                    'total_importe'=>number_format($detalles['total_importe'],2),
                    'descuento_items'=>$detalles['descuento_items'],              
                    'descuento_general'=>$detalles['descuento_general'],
                    'total_descuentos'=>number_format($detalles['total_descuentos'],2),
                    'total_impuestos'=>$detalles['total_impuestos'],
                    'total_subtotal'=>number_format($detalles['total_subtotal'],2),
                    'total'=>$detalles['total']
                );

                return $json;

            }else{
               $this->flashmessenger->addMessage(array('danger'=>$this->_getTranslation('Falta cantidad de producto.')));

                return $json = array(
                    'response'=>null,
                    'message'=>$this->flashmessenger->getMessageString());
            }            
        }else{
            $this->flashmessenger->addMessage(array('danger'=>$this->_getTranslation('Producto no registrado.')));
            return $json = array(
                'response'=>null,
                'message'=>$this->flashmessenger->getMessageString());
        }
    }   

    public function listVentaDetalles($detalles){      
        $listDetalles = "";
        $cantidadItems = 0;
        $total_subtotal = 0;
        $total_importe = 0;
        $total_descuentos = 0;
        $descuentos_item = 0;
        $descuentos_general = 0;
        $total_impuestos_string = '';       
        $totalImpuestoTrasladado = 0;
        $totalImpuestoRetenido = 0;
        $impuestosAplicables = array('Trasladable'=>array(),'Retenible'=>array());
        $partida = 1;                
        
        $meRepo = new MachenaryAndEquipmentRepository();        
        foreach($detalles as $detalle){
            $stringImpuestos = '';
            $id = $detalle['id'];         
            unset($detalle['id'],$detalle['discount_general'],$detalle['discount_general_type']);  
            
            $array = json_encode($detalle);
            $cantidadItems += $detalle['quantity'];
            $total_importe_item = $detalle['cost_without_tax'] * $detalle['quantity']; 
            $total_importe +=  $total_importe_item;
            $descuentos_item += $detalle['discount_amount'];
            $descuentos_general += $detalle['discount_general_amount'];
            $total_descuento_item = $detalle['discount_amount'] + $detalle['discount_general_amount'];
            $total_descuentos += $total_descuento_item;
            $total_subtotal += $total_importe_item - $total_descuento_item;            

            if($detalle['impuestos_aplicables'] != ''){    
                $impuestos = unserialize($detalle['impuestos_aplicables']);
                foreach($impuestos as $tipo =>  $impuesto){   
                    foreach($impuesto as $idImpuesto =>$impuestoInfo){
                        $stringImpuestos .= $impuestoInfo['descripcion']." ".$impuestoInfo['Importe']."<br/>";                        

                        if(key_exists($idImpuesto,  $impuestosAplicables[$tipo])){
                            $impuestosAplicables[$tipo][$idImpuesto]['Importe'] += number_format($impuestoInfo['Importe'],4,'.','');
                        }else{
                            $impuestosAplicables[$tipo][$idImpuesto]['Importe'] = number_format($impuestoInfo['Importe'],4,'.','');
                            $impuestosAplicables[$tipo][$idImpuesto]['nombre'] = $impuestoInfo['nombre'];
                            $impuestosAplicables[$tipo][$idImpuesto]['descripcion'] = $impuestoInfo['descripcion'];
                            $impuestosAplicables[$tipo][$idImpuesto]['Impuesto'] = $impuestoInfo['Impuesto'];
                            $impuestosAplicables[$tipo][$idImpuesto]['TipoFactor'] = $impuestoInfo['TipoFactor'];
                            $impuestosAplicables[$tipo][$idImpuesto]['TasaOCuota'] = $impuestoInfo['TasaOCuota'];
                        }
                    } 
                }
            }            

            $desciption = $detalle['description'];
            $serviceEndDate = null;           
            $replacement = null;
            if($detalle['type'] == 'product'){
                $desciption .= "<br/> # Economico: ".$detalle['economic_number']."<br/> Estado:".$detalle['status_name'];                               
                if(!empty($detalle['formated_service_end_date'])){
                    $serviceEndDate = "<br/>Termina el: {$detalle['formated_service_end_date']}";
                }    
                
                if(!empty($detalle['me_id_before_replacement']) && $detalle['me_id_before_replacement'] > 0){
                    $meData = $meRepo->getById($detalle['me_id_before_replacement']);    
                    $replacement = "<span class='label label-warning' style='cursor: pointer' title='Equipo original: ".htmlentities(nl2br($meData['economic_number'].' '.$meData['description']),ENT_QUOTES)."'>Reemplazo</span><br/>";
                }
            }            

            if($detalle['aditamento'] != '' && $detalle['aditamento'] != '0'){
                $desciption .= "<br/> Aditamento: ".$detalle['aditamento_name'];
            }            

            if($detalle['description_details'] != ''){
                $desciption .= "<br/>".nl2br($detalle['description_details']);
            }         

            /*usamos setDetailQuotationToEdit() porque estamos usando el modalQuotation para agregar productos y servicios*/                      
            $listDetalles .= "<tr>  
                <td class='text-left' style='white-space: nowrap'>                       
                    <a class='btn btn-sm btn-default' onclick='setDetailQuotationToEdit($array,\"SaleNote\");' title='Editar'><i class='fa fa-pencil'></i></a>
                    <a id='replace_product' class='btn btn-sm btn-warning' onclick='setDetailQuotationToEdit($array,\"SaleNote\");' title='Reemplazar'><i class='fa fa-refresh'></i></a>
                    <a class='btn btn-sm btn-danger' onclick='deleteDetallesOnSaleNote($id);' title='Eliminar'><i class='fa fa-minus'></i></a>
                </td>
                <td class='text-center'>$partida</td>
                <td>".$replacement.$desciption."</td> 
                <td class='text-center'>".$detalle['rent_term_name'].$serviceEndDate."</td>
                <td class='text-right'>".number_format($detalle['quantity'],2)."</td>
                <td class='text-right'>".number_format($detalle['price'],2)."</td>
                <td class='text-right'>".number_format($detalle['discount'],2)."</td>
                <td class='text-right'>".number_format($detalle['amount'],2)."</td>
                <td class='text-right' style='white-space: nowrap;'>".$stringImpuestos."</td>                       
                <td class='text-right'>".number_format($detalle['total'],2)."</td>  
                </tr>";          

            $partida++;
        }                

        $total_impuestos_string = '';       
        if(count($impuestosAplicables['Trasladable']) > 0){    
            foreach($impuestosAplicables['Trasladable'] as $impuestoAplicable){
                $totalImpuestoTrasladado +=  $impuestoAplicable['Importe'];
                $total_impuestos_string .= "<tr>"
                    . "<th class='text-right' style='border: 0px' colspan='2'>{$impuestoAplicable['descripcion']}</th>"
                    . "<th class='text-right'>$</th>"
                    . "<th class='text-right'  style='border: 0px;border-bottom: 1px solid #eee'>".number_format($impuestoAplicable['Importe'],2)."</th>"
                    . "</tr>";
            } 
        }       

        if(count($impuestosAplicables['Retenible']) > 0){
            foreach($impuestosAplicables['Retenible'] as $impuestoAplicable){
                $totalImpuestoRetenido +=  $impuestoAplicable['Importe'];                

                $total_impuestos_string .= "<tr>"
                    . "<th class='text-right' style='border: 0px' colspan='2'>{$impuestoAplicable['descripcion']}</th>"
                    . "<th class='text-right'>$</th>"
                    . "<th class='text-right'  style='border: 0px;border-bottom: 1px solid #eee'>".number_format($impuestoAplicable['Importe'],2)."</th>"
                    . "</tr>";
            }
        }        

        $total = $total_subtotal - $totalImpuestoRetenido + $totalImpuestoTrasladado;
        return array('listDetails'=>$listDetalles,
                     'totalItems'=>$cantidadItems,
                     'total_subtotal'=>$total_subtotal,
                     'total_importe'=>$total_importe,
                     'descuento_items'=>$descuentos_item,
                     'descuento_general'=>$descuentos_general,
                     'total_descuentos'=>$total_descuentos,
                     'total_impuestos'=>$total_impuestos_string,
                     'total'=>$total
            );
    }    

    public function getListSaleDetails($tokenForm){

        $compraDetalles = $this->getSaleNoteDetails($tokenForm);

        $detalles = $this->listVentaDetalles($compraDetalles);

            

            $json = array(

                'response' => true,

                'saleNoteDetails' => $detalles['listDetails'],

                'totalItems'=>number_format($detalles['totalItems'],2),

                'total_importe'=>number_format($detalles['total_importe'],2),

                'descuento_items'=>$detalles['descuento_items'],

                'descuento_general'=>$detalles['descuento_general'],

                'total_descuentos'=>number_format($detalles['total_descuentos'],2),

                'total_subtotal'=>number_format($detalles['total_subtotal'],2),

                'total_impuestos'=>$detalles['total_impuestos'],

                'total'=>$detalles['total']

            ); 

            

            return $json;

    }

    

    public function calculateGralDiscount($options){

        $repo = new SaleNoteDetailsTempRepository();

        $rs = $repo->setGeneralDiscount(array('discount'=>$options['discount'],'token_form'=>$options['token_form'],'customer'=>$options['customer']));

        

        if($rs){

             return $this->getListSaleDetails($options['token_form']);

        }else{

            #null == no existen registro para aplicar descuentos

            return array(

                'reponse'=>false

            );

        }     

    }



    public function deleteDetalles(array $options){

        $id = $options['id'];

        $repository = new SaleNoteDetailsTempRepository();



        $currentData = $repository->getById($id);

        

        if($repository->delete($id)){

            $response = true;

            $msj = 'Producto eliminado correctamente.';

        }else{

            $response = null;

            $msj = "No se pudo eliminar producto. Intente nuevamente.";

        }

        

        $compraDetalles = $this->getSaleNoteDetails($currentData['token_form']);

        $detalles = $this->listVentaDetalles($compraDetalles);

        $json = array(

                'response' => true,

                'saleNoteDetails' => $detalles['listDetails'],

                'totalItems'=>$detalles['totalItems'],

                'total_subtotal'=>number_format($detalles['total_subtotal'],2),

                'total_importe'=>number_format($detalles['total_importe'],2),

                'total_descuentos'=>number_format($detalles['total_descuentos'],2),

                'total_impuestos'=>$detalles['total_impuestos'],

                'total'=>$detalles['total']

            );

        //var_dump($json);exit();

            return $json;

        

    }

    

    public function getDefaultDataProduct($options){

        $repo = new ProductRepository();

        $data = $repo->getById($options['product']);        

        

        return array(

            'response'=>true,

            'price'=>$data['sale_price'],

            'taxes'=>$data['taxes'],

            'retencion_id'=>$data['retencion_id'],

            'taxes_included'=>$data['taxes_included']

        );

    }

    

    public function getCustomerMethodPayment($options){
        $customer = $options['customer'];
        $date = $options['date'];
        $dueDate = $date;       

        $repoCustomer = new CustomerRepository();
        $dataCustomer = $repoCustomer->getById($customer);        

        $paymentTermsRepo = new PaymentTermRepository();
        $paymentTermsData = $paymentTermsRepo->getById($dataCustomer['payment_terms']); 
        
        //UG Validar Si el cliente tiene credito o notas de ventas pendientes
        $customer_repository = new CustomerPaymentRepository();
        $_resp_validPagos = $customer_repository->validPagos($customer);

        if($date !== '' && !is_null($date)){
            $tools = new Tools();
            $date = $tools->setFormatDateToDB($date);
            $dueDate = $this->getDueDate($date, $paymentTermsData['days']);
            $dueDate = $tools->setFormatDateToForm($dueDate);
        }            
        
        if($_resp_validPagos){
            return array(
                'response'=>true,
                'payment_terms'=>$paymentTermsData['id'],
                'due_date'=>$dueDate
            );     
        }else{
            //UG Enviar alerta al intentar seleccionar el cliente con deuda
            $this->flashmessenger->addMessage(array('danger' => 'El cliente tiene un saldo pendiente de pagar, o no tiene el credito suficiente para la operacion.'));
            return array(
                'response' => true,
                'payment_terms' => $paymentTermsData['id'],
                'due_date' => $dueDate,
                'message' => $this->flashmessenger->getMessageString()
            );
        }
    }   

    public function setDueDate($options) {

       $date = $options['date'];

       $creditDays = $options['credit_days'];

       

       $tools = new Tools();

       $date = $tools->setFormatDateToDB($date);

       

       $dueDate = parent::getDueDate($date, $creditDays);       

       

       $dueDate = $tools->setFormatDateToForm($dueDate);

       

       return array(

            'response'=>true,

            'due_date'=>$dueDate

        );

    }

    

    public function setReleaseForLogistic($options){

        $repo = new EntityRepository();

        if($options['checked'] == 'true'){$releseForLogistics = 1;}else{$releseForLogistics = 0;}

        $repo->update($options['salenote_id'], array('released_for_logistics'=>$releseForLogistics), 'sales_notes');

        

        return array(

            'response'=>true

        );

    }



    /*==========================================

    =            EMAILING SALENOTES            =

    ==========================================*/

    public function getDataSaleNote($options){

        $salenoteData = $this->getById($options['salenote_id']);

        $this->setOptions($salenoteData);

        

        $customerRepo = new CustomerRepository();

        $customerData = $customerRepo->getById($this->getCustomer());

        

        $settingRepo = new SettingsRepository();

        $settingMsg = $settingRepo->_get("message_mail_salenote");

        

        return array(

            'response'=>true,

            'to'=>$customerData['email'],

            'subject'=>$this->_getTranslation("Nota de venta # {$salenoteData['num_notaventa']}"),

            'messageMail'=>$settingMsg,

        );

        

    }

    

    public function emailingSaleNote($options){

        $repo = new EntityRepository();

        $data = array();

        foreach($options['options'] as $row){

            $data[$row['name']] = $row['value'];

        }

        

        $shippingRepo = new SaleNoteRepository();

        $shippingRepo->setOptions($shippingRepo->getById($data['salenote_id']));

        $bolPdf = $shippingRepo->crearPDF($data['salenote_id']);

        

        $company = new CompanyRepository();

        $company->setOptions($company->getById(1));

       

        try{

            $emailer = new Emailer();

            $correo = $emailer->sendEmail(array(

                'from'=>$data['from'],

                'to'=>$data['to'],

                'cc'=>$data['cc'],

                'subject'=>$data['subject'],

                'from_title'=>$company->getName(),

                'message'=>$data['message'],

                'attachment'=>$bolPdf

            ));

            if($correo){

                $repo->update($data['salenote_id'], array('email_sent'=>'1'), 'sales_notes');

            

                $this->flashmessenger->addMessage(array('success'=>'La nota de venta se envio correctamente.'));

            }

            

            return array(

                'response'=>true

            );

        } catch (Exception $ex) {

            $this->flashmessenger->addMsg(array('danger'=>'Oops =(. Algo salio mal al tratar de enviar la nota de venta. Intenta nuevamente'));

            return array(

                'response'=>null,

                'msg'=>$this->flashmessenger->getMessageString()

            );

        }        

    }  

    /*=====  End of EMAILING SALENOTES  ======*/

    

    public function delteInvoiceFile(array $file){

        $fileDelete = $file['fileDelete'];

        $fileDelete = explode("/", $fileDelete);

        $fileInvoice = $fileDelete[7];

        

        $response ="";

        $msj = "";

        define("RAIZ", $_SERVER['DOCUMENT_ROOT'].'/app/resources/docs/facturas_de_notasdeventas/');

        $target_path = RAIZ.$fileInvoice;

        

        if (unlink($target_path)) 

        {

            $response = true;

            $msj = 'Archivo eliminado correctamente.';

        }

        else

        {

            $response = false;

            $msj = 'Archivo no eliminado.';

            /*if (is_null($fileDelete))

            {

                $response = false;

                $msj = 'Archivo no eliminado.';

            }*/

        }



        $json = array(

            'response'=>$response,

            'message'=>$msj

        );

        return $json;

    }

    

    /*EMAILING Invoice*/

    public function getDataInvoice($options){

        $invoiceData = $this->getById($options['invoice_id']);

        $this->setOptions($invoiceData);

        

        $customerRepo = new CustomerRepository();

        $customerData = $customerRepo->getById($this->getCustomer());

        

        $settingRepo = new SettingsRepository();

        $settingMsg = $settingRepo->_get("message_mail_sale");

        

        return array(

            'response'=>true,

            'to'=>$customerData['email'],

            'subject'=>$this->_getTranslation("Invoice # {$invoiceData['num_venta']}"),

            'messageMail'=>$settingMsg,

        );

        

    }

    

     public function saveDataDepositoEnGarantia($data){    

        $id = $data['id'];

        //$attachments = $data['documents'];

        unset($data['action'],$data['id'],$data['request']);        

         

        if(trim($id) != '' && !is_null($id)){

            $this->_updateDepositoEnGarantia($id,$data);

            $this->flashmessenger->addMessage(array('success'=>'Deposito en garantia actualizado correctamente.'));

        }else{

            $this->_saveDepositoEnGarantia($data);

            $this->flashmessenger->addMessage(array('success'=>'Deposito en garantia guardado correctamente.'));

            $id = $this->getInsertId();      

        }          

        

        //var_dump($attachments);exit;

        /*

        $fileManagement = new FileManagement();    

        if(isset($attachments['deposito_en_garantia_attachment']['name'][0]) && $attachments['waybill_attachment']['name'][0]!=''){                    

            $fileManagement->saveFile($attachments['deposito_en_garantia_attachment'], $id,'waybill');

        }        */

        

        $dgData = $this->_getByIdDepositoEnGarantia($id);

        $string = "<tr class='tr_dg_{$dgData['id']}'>";

        $string .= "<td class='text-center'>{$dgData['date']}</td>";        

        $string .= "<td class='text-center'>{$dgData['receipt_number']}</td>";

        $string .= "<td class='text-center'>".number_format($dgData['amount'],2)."</td>";

        $string .= "<td class='text-center'>{$dgData['received_by']}</td>";

        $string .= "<td class='text-center'>{$dgData['return_date']}</td>";

        $string .= "<td class='text-center td_dg_{$dgData['id']}'>{$dgData['status_name']}</td>";

        $string .= "<td class='text-center'>

                        <span class='btn btn-default _editDepositoEnGarantia' data-id='{$dgData['id']}'><i class='fa fa-pencil'></i></span>

                        <span class='btn btn-danger _deleteDepositoEnGarantia' data-id='{$dgData['id']}'><i class='fa fa-trash'></i></span>                    

                    </td>";

        $string .= "</tr>";

        

        

        

        return array(

            'response'=>true,

            'new_data_dg'=>$string,

            'msg'=>$this->flashmessenger->getMessageString()

        );

    }

    

    public function deleteDepositoEnGarantia($options){

        return $this->_deleteDepositoEnGarantia($options['id']);       

    }

    

    public function getDataToEditDepositoEnGarantia($options){

        $data = $this->_getByIdDepositoEnGarantia($options['id']);

        $data['action'] = 'edit';

        

        return array(

            'response'=>true,

            'dgData'=>$data

        );

    }    

    

    public function getSalesNotesListByCustomerId($options){

        $list = $saleNoteRepo = $this->getListSelectSaleNoteByCustomerId($options['customer_id']);

        

        $string = "<option value='0'>Seleccionar una opcion...</option>";

        foreach($list as $value => $text){

            $string .= "<option value='$value'>{$text}</option>";

        }

        

        return array(

            'response'=>true,

            'listNotes'=>$string

        );

    }    
    public function setValidUnlockedCorrect($options){
        $data = array();
        foreach($options['options'] as $row){
            $data[$row['name']] = $row['value'];
        }
        
        $validCredencial = new SaleNoteRepository();
        //UG valida el nivel correcto del usuario PO REQUERIMIENTO CAMBIA SOLO A PEDIR PASSWORD
     //   $respData = $validCredencial->isUnlockedCorrect($data['user_unlocked'],$data['password_unlocked']);
        $respData = $validCredencial->isUnlockedCorrect($data['password_unlocked']);
        
        if($respData){
            //UG Modificar el status de la saleNote a 1 en campo unlocked
            $id = $data['id_sale_note'];                              
            parent::query("UPDATE sales_notes SET unlocked = '{$respData[0]['id']}' WHERE id = '$id'");

        }else{
            $this->flashmessenger->addMessage(array('danger'=>$this->_getTranslation('Usuario incorrecta o sin acceso..')));

            return $json = array(    
                'response'=>null,    
                'message'=>$this->flashmessenger->getMessageString());
        }

                 

        return array(
            'response'=>true
        );
    }
    public function calculateGralCardPayment_fee($options){

        $settings = new SettingsRepository();
        
        $card_payment_fee_BD = $settings->_get('card_payment_fee');
        
        $card_payment_fee = round($options['amount'] * ($card_payment_fee_BD/100),2,PHP_ROUND_HALF_UP);
        $new_amount =$options['amount'] + $card_payment_fee;
        //$repo = new SaleNoteDetailsTempRepository();

        //$rs = $repo->setGeneralDiscount(array('discount'=>$options['discount'],'token_form'=>$options['token_form'],'customer'=>$options['customer']));

        

        if($card_payment_fee /** $rs*/){

            return array(

                'response'=>true,

                'card_payment_fee'=>$card_payment_fee,

                'new_amount'=>$new_amount

            );

        }else{

            #null == no existen registro para aplicar descuentos

            return array(

                'response'=>false

            );

        }     

    }
    
    public function getModalCausesCancelSaleNote($options){
        $saleNoteForm = new SaleNoteForm();
        $string = "";
        
        $string .= $saleNoteForm->getElementString('cause_of_salenote_rejected');
        
        return array(
            'response'=>true,
            'string'=>$string
        );
    }
    
    public function setCauseToCancelSaleNote($options){
        if($this->isUsedInRecord($options['salenote_id'])){
            $msg = $this->flashmessenger->getMessageString();
            return array(
                'response'=>null,
                'msg'=>$msg
            );
        }
        
        if($this->delete($options['salenote_id'])){
            $this->flashmessenger->addMessage(array('success'=>'Nota de venta se cancelo exitosamente.'));
            $this->_setCauseToCancelSaleNote($options['cause_of_salenote_rejected'],$options['salenote_id']);
        }          
        
        return array('response'=>true);
    }
}


