<?php

/**

 * Description of Ajax

 *

 * @author carlos

 */

class ReportAjax extends EntityRepository {

    

    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 getFiltersReport($options){

        $form = new ReportForm();        

       

        return array(

            'response'=>true,

            'filters'=>$form->getStringFiltersForm($options['report'])

        );

    }

    

     public function saveFixedExpense($options){    
        $year = $options['year'];
        $month = $options['month'];
        $data = array();

        foreach($options['options'] as $key => $option){  //var_dump($option);    
           
            if(strpos($option['name'], 'cost_')!== false){
                $name = str_replace('cost_', '', $option['name']);
                $data[$name]['cost'] = $option['value'];
            } 

            if(strpos($option['name'], 'duedate_')!== false){
                $name = str_replace('duedate_', '', $option['name']);
                $data[$name]['duedate'] = $option['value'];
            }           
        }     

        set_error_handler(function ($err_severity, $err_msg, $err_file, $err_line, array $err_context){

            throw new ErrorException( $err_msg, 0, $err_severity, $err_file, $err_line );

        }, E_WARNING);

        

        try{

            $expenseConfigRepo = new ExpenseConfigRepository();

            $expenseConfigRepo->_saveFixedExpense($data,$year,$month);

            $this->flashmessenger->addMessage(array('success'=>'Gastos guardados correctamente.'));

            

             return array(

                'response' => true,

                'msj'=>$this->flashmessenger->getRawMessage(),

            );

        } catch (Exception $ex) {

            //$this->flashmessenger->addMessage(array('success'=>'Error al guardar gastos.'));
            $this->flashmessenger->addMessage(array('success'=>$ex->getMessage()));

            restore_error_handler();            

            

             return array(

                'response' => null,

                'msj'=>$this->flashmessenger->getRawMessage(),

            );

        }    

    }

    

    function updateInventory($options){

        $array = explode('_', $options['id']);

        

        $inventoryRepo = new InventoryRepository();

        $inventoryRepo->updateInventory(array(

            'id_product'=>$array[0],

            'id_store'=>$array[1],

            'quantity'=>$options['stock'],

        ));

        

        return array(

            'response'=>true

        );

    }

    public function getTotalEstadoByStore($options){

      
        $salesGastos = new ReportsListRepository();
        
        $optionFormat = array(
            'month' => $options['month'],
            'year' => $options['year'],        
        );

        $dataGastos = $salesGastos->getsummary_byStore($optionFormat);
        $totalGastado = array();

       //echo "<pre>";var_dump($dataGastos['result']);echo "</pre>";exit;
        foreach ($dataGastos['result'] as $key => $data) {
          
            // Ventas
            $totalVenta = 0;
            foreach ($data['ventas'] as $venta) {
                $totalVenta += isset($venta['total_venta']) ? (float)$venta['total_venta'] : 0;
            }
          
            // Rentas
            $totalRentas = 0;

            foreach ($data['rentas'] as $renta) {
                $totalRentas += isset($renta['total_valor']) ? (float)$renta['total_valor'] : 0;
            }
          
            $totalLuz = 0;

            foreach ($data['luz'] as $luz) {
                $totalLuz += isset($luz['total_valor']) ? (float)$luz['total_valor'] : 0;
            }
          
            $totalTelefono = 0;

            foreach ($data['telefono'] as $telefono) {
                $totalTelefono += isset($telefono['total_valor']) ? (float)$telefono['total_valor'] : 0;
            }
          
            $totalInternet = 0;

            foreach ($data['internet'] as $internet) {
                $totalInternet += isset($internet['total_valor']) ? (float)$internet['total_valor'] : 0;
            }
        
            // Horas

            $salarioHora = 0;
            $salariofijo_social = 0;
            foreach ($data['horas'] as $hora) {

                $salarioHora += isset($hora['salario_Hora']) ? (float)$hora['salario_Hora'] : 0;
                $salariofijo_social += isset($hora['salario_fijo_Social']) ? (float)$hora['salario_fijo_Social'] : 0;
            }
            $salarioSocialSumado  = round($salarioHora + $salariofijo_social, 2);        

            // Fijo
            $totalFijo = 0;
            $totalHoraContratista = 0;

            foreach ($data['fijo'] as $fijo) {
                $totalFijo += isset($fijo['salario_fijo']) ? (float)$fijo['salario_fijo'] : 0;
                $totalHoraContratista += isset($fijo['salario_Hora_Contratista']) ? (float)$fijo['salario_Hora_Contratista'] : 0;
            }
            $salarioContratistaSumado  = round($totalFijo + $totalHoraContratista, 2);          

            // Producción
            $totalProduccion = 0;
            foreach ($data['produccion'] as $produccion) {
                $totalProduccion += isset($produccion['total_sum']) ? (float)$produccion['total_sum'] : 0;
            }           

            // Gastos
            $totalGastos = 0;
            foreach ($data['gastos'] as $gasto) {
                $totalGastos += isset($gasto['total_sum']) ? (float)$gasto['total_sum'] : 0;
            }

            // Compras
            $totalCompras = 0;
            foreach ($data['compras'] as $compra) {
                $totalCompras += isset($compra['total_compras']) ? (float)$compra['total_compras'] : 0;
            }        

            // Ganancia
            $totalGastado[$data['sucursal']] = ($totalRentas + $totalLuz + $totalTelefono + $totalInternet + $salarioSocialSumado  + $totalFijo + $totalProduccion + $totalGastos + $totalCompras);         

        }

       

        #$options['startDate'], $options['endDate']      

        $salesRecord = new SalesRecordRepository();
        $salesData = $salesRecord->getSalesByDateRange($options['start'],$options['end']);
        $salesDataPOS = $salesRecord->getSalesByDateRangeFromSalesPOS($options['start'],$options['end']);       

        $existSales = null;
        $data = null;      
            
        if($salesData){
            $existSales = true;
            foreach($salesData as $sale_data){
                /*Especial para Cage Temporalmente*/
                //if($sale_data['store_name'] == 'Cage'){$cageSales = (float)$sale_data['total_sales'];}                
                $data[$sale_data['store_name']] = $sale_data;
            }
        }        

        if($salesDataPOS){
            $existSales = true;
            foreach($salesDataPOS as $sale_data_pos){
                $data[$sale_data_pos['store_name']] = $sale_data_pos;
            }
        }

        $string = '';
        $totalSales = 0;
        $totalGastos_ = 0;
        $chartData = array();        
        $charDataGastos = array();
       
        if($data){            
            foreach($data as $sale){
                /*Especial para Cage Temporalmente*/
                //if($sale['store_name'] == 'Cage'){(float)$sale['total_sales'] += $cageSales;}
                
                $totalSales += $sale['total_sales'];               
                $chartData[$sale['store_name']] = number_format($sale['total_sales'],2,'.','');
                $charDataGastos[$sale['store_name']] = number_format($totalGastado[$sale['store_name']],2,'.','');
                $string .= "<tr>";
                $string .= "<td class='text-center'>{$sale['store_name']}</td>";
                $string .= "<td class='text-right'>$".number_format($sale['total_sales'],2)."</td>";
                $string .= "<td class='text-right'>$".number_format($totalGastado[$sale['store_name']],2)."</td>";
                
                $string .= "</tr>";
                $totalGastos_ += $totalGastado[$sale['store_name']];
            }        
        }        
       
        if($existSales){
             return array(
                'response'=>true,
                'caption'=>$this->_getTranslation('Ventas')." ".$this->_getTranslation('de')." ".$options['start']." ".$this->_getTranslation('a')." ".$options['end'],
                'salesData'=>$string,
                'totalSales'=>number_format($totalSales,2,'.',''),
                'totalGastos'=> number_format($totalGastos_,2),
                'chartData'=>$chartData,
                'charGastos'=>$charDataGastos
            );
        }             

        return array('response'=>false);

    }

}