<?php
/**
 * Description of Ajax
 *
 * @author carlos
 */
class PurchaseAjax extends VendorRepository {
    
    public $flashmessenger = null;
    
    public function __construct() {
        if(!$this->flashmessenger instanceof FlashMessenger){
            $this->flashmessenger = new FlashMessenger();
        }
    }
    
    public function getResponse($request, $options) {
        return $this->$request($options);
    }
    
    public function _getTranslation($text){
        $translator = new Translator();
        return $translator->_getTranslation($text);
    }
    
    public function getTranslation($options){
        $msj = $options['msj'];
        
        return array(
            'response'=>true,
            'translation'=>$this->_getTranslation($msj)
                );
    }    
    
    public function getDataToEdit($options){
        $purchaseRepo = new PurchaseRepository();
        $data = $purchaseRepo->getById($options['id']);
        $data['action'] = 'edit';
        $data['purchase_date'] = $data['purchase_date_formated'];
        
        $form = new Form();        
        $data = $form->formatDouble($data,$purchaseRepo->inputs_double);

        return array(
            'response'=>true,
            'purchaseData'=>$data
        );
    }
    
    public function deletePurchase($options){
        $purchaseRepo = new PurchaseRepository();
        
        if($purchaseRepo->delete($options['id'])){
            $this->flashmessenger->addMessage(array('success'=>'Compra se elimino exitosamente.'));                
        }
        
        return array(
            'response'=>true
        );
    }
    
    public function getTotalPurchases($options){
        $salesRecord = new PurchaseRepository();
        $purchasesData = $salesRecord->getPurchasesByDateRange($options['start'],$options['end']);
        
        $string = '';
        $totalPurchases = 0;
        $chartData = array();
        if($purchasesData){
            foreach($purchasesData as $purchase){
                $totalPurchases += $purchase['total_purchases'];
                $chartData[$purchase['vendor_name']] = number_format($purchase['total_purchases'],2,'.','');
                $string .= "<tr>";
                $string .= "<td class='text-center'>{$purchase['vendor_name']}</td>";
                $string .= "<td class='text-right'>$".number_format($purchase['total_purchases'],2)."</td>";
                $string .= "</tr>";
            }
            
            return array(
                'response'=>true,
                'caption'=>$this->_getTranslation('Compras')." ".$this->_getTranslation('del')." ".$options['start']." ".$this->_getTranslation('al')." ".$options['end'],
                'purchasesData'=>$string,
                'totalPurchases'=>number_format($totalPurchases,2,'.',''),
                'chartData'=>$chartData 
            );
        }   
        
        return array('response'=>false);
    }
}