<?php

class WasteRepository extends EntityRepository {



    private $table = 'waste';

    private $table_details = 'waste_details';

    private $last_insert_id = null;

    private $options = array(

        'waste_num'=>null,

        'store_id'=>null,

        'date'=>null,

        'comments'=>null,       

        'status'=>null,       

        'attachments' => null,

    );

    

    private $details = array();

    

    public function setOptions($data){

       
        foreach ($this->options as $option => $value){        

            if(isset($data[$option])){

              $this->options[$option] = $data[$option];

            }

        }

      
      

        /*Todos los campos que pertenecen a tbl detalles, traen el posfijo _details*/        

        foreach($data as $key => $value){

            if(strpos($key, '_details')){

                /*$id[0] es el id de la tabla o uniqId cuando se agrega usando el boton Agregar*/

                /*Cuando $id[0] contiene x significa que es un detalle nuevo */

                $id = explode('_', $key);

                $this->details[$id[0]] = $value;

            }        

        }       
       // var_dump($this->details);exit;
    }

  

    public function getOptions(){

        return $this->options;

    }

    

    public function _getLastInsertId() {

        return $this->last_insert_id;

    }

      

    public function save(array $data, $table = null) {    
       
        $tools = new Tools();        

        $data['waste_num'] = $this->getNextFolio();

        $data['date'] = $tools->setFormatDateTimeToDB($data['date']);  

        $data['status'] = 1;

        $attachments = $data['attachments'];
       

        unset($data['attachments']);
     
        

                        

        $this->startTransaction();

        $rs = parent::save($data, $this->table);

        $this->setLastInsertId($this->getInsertId());

        $this->last_insert_id = $this->getLastInsertId();

        $repository_posProduct = new PosProductoRepository();

        if($rs){

            $waste_id = $this->last_insert_id;

            foreach($this->details as $key => $value){

                $dataProductPos = $repository_posProduct->getById($value['product_id']);


                $value['waste_id'] = $waste_id;    
                
                $value['p_uuid_pos'] = $dataProductPos['p_uuid'];

                if(empty($value['quantity'])){$value['quantity'] = 0;}   

                if(empty($value['cost'])){$value['cost'] = 0;}   

                if(empty($value['total_cost'])){$value['total_cost'] = 0;}   

                if(empty($value['price'])){$value['price'] = 0;}   

                if(empty($value['total_price'])){$value['total_price'] = 0;}   

                

                parent::save($value, $this->table_details);

               # $sql_update_inventory = "UPDATE inventory SET stock = (stock - )";

            }

            $this->commit();

            $fileManagement = new FileManagement();

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

                $fileManagement->saveFile($attachments['attachments'], $waste_id, 'waste');

            }

        }

        

        $this->rollback();

        return true;

    }

    

    public function delete($id, $table = null) {        

        $query = "UPDATE $this->table SET status = '2' WHERE id = '$id'";

        return $this->query($query);                

    }



    public function update($id, $data, $table = null) {   
     
        $tools = new Tools();        

        $data['date'] = $tools->setFormatDateTimeToDB($data['date']);  

        $attachments = $data['attachments'];              

        $this->startTransaction();

        unset($data['waste_num'],$data['attachments']);       

        $rs = parent::update($id,$data, $this->table);

        

        if($rs){

            $currentDetails = $this->getWasteDetailsByWasteId($id);

            $idQueSeMantienen = array();

            $repository_posProduct = new PosProductoRepository();

            foreach($this->details as $key => $value){    
                
                $dataProductPos = $repository_posProduct->getById($value['product_id']);


                $value['p_uuid_pos'] = $dataProductPos['p_uuid'];

                $value['waste_id'] = $id;            

                if(empty($value['quantity'])){$value['quantity'] = 0;}   

                if(empty($value['cost'])){$value['cost'] = 0;}   

                if(empty($value['total_cost'])){$value['total_cost'] = 0;}   

                if(empty($value['price'])){$value['price'] = 0;}   

                if(empty($value['total_price'])){$value['total_price'] = 0;}    

                

                /*Cuando $key[0] contiene x significa que es un detalle nuevo */

                if(strpos($key, 'x')){
                   

                    parent::save($value, $this->table_details);

                }else{                    

                    $idQueSeMantienen[$key] = $key;

                    parent::update($key, $value,$this->table_details);

                }

            }



            foreach($currentDetails as $idDetail => $detail){

                if(!key_exists($idDetail, $idQueSeMantienen)){

                    parent::query("DELETE FROM $this->table_details WHERE id = '$idDetail'");

                }

            }

            

            $this->commit();

            

            $fileManagement = new FileManagement();

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

                $fileManagement = new FileManagement();

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

            }

            

            return true;

        }

        

        $this->rollback();

        return null;

    }



    public function getById($id, $table = null,$selectAux = null) {

        $query = "SELECT p.*,"

                . "DATE_FORMAT(p.date,'%d/%m/%Y %r')as formatedDate,"

                . "fxGetUserName(p.creado_por)as created_by, "               

                . "fxGetUserName(p.ultima_mod_por)as last_modification_by, "    

                . "DATE_FORMAT(p.ultima_mod_fecha,'%d/%m/%Y %r')as last_modification_at "

                . "FROM $this->table p "

                . "WHERE p.id = '$id' ";

        

        $result = $this->query($query);

        

        if($result->num_rows > 0){

            return $this->resultToArray($result)[0];

        }

        

        return null;

    }



    public function isUsedInRecord($id, array $buscarEn = null,$andWhere = null) {

        return null;

    }

    

    public function getListWaste($options = null){

        $date = null;        

        $user_id = null;

        $store_id = null;

        $status = null;       

        $limit = null;

        

        if($options){

            $date = $this->createFilterFecha($options,'t.date');                                    

            if(trim($options['status']) !== ''){$status = " AND t.status = '{$options['status']}' ";}         

            

            if(isset($options['user_id'])){

                if(is_array($options['user_id']) && count($options['user_id']) > 0){

                    $userIds = implode(',', $options['user_id']);

                    $user_id = " AND find_in_set(t.creado_por,'{$userIds}')";

                }else{

                     if(trim($options['user_id'])!= ''){$user_id = " AND find_in_set(t.creado_por,'{$options['user_id']}')";}       

                }           

            }    

            

            if(isset($options['store_id'])){

                if(is_array($options['store_id']) && count($options['store_id']) > 0){

                    $storeIds = implode(',', $options['store_id']);

                    $store_id = " AND find_in_set(m.store_id,'{$storeIds}')";

                }else{

                     if(trim($options['store_id'])!= ''){$store_id = " AND find_in_set(m.store_id,'{$options['store_id']}')";}       

                }           

            }    

            

            if(is_null($date)  

                    && is_null($store_id)   

                    && is_null($status)    

                    && is_null($user_id)){$limit = " LIMIT 300";}           

        }else{

            $limit = " LIMIT 300";

        }       

        

        $query = "SELECT t.*,"               

                . "DATE_FORMAT(t.date,'%m/%d/%Y %r')as formated_date,"                

                . "fxGetUserName(t.creado_por)as user_name, "

                . "fxGetStatusName(t.status,'Waste')as status_name,"

                . "s.name as store_name,"                

                . "SUM(quantity)as total_quantity, "

                . "SUM(total_cost)as total_cost, "

                . "SUM(total_price)as total_price "

                . "FROM $this->table t "

                . "LEFT JOIN $this->table_details d ON d.waste_id = t.id "

                . "LEFT JOIN stores s ON t.store_id = s.id "               

                . "WHERE 1 = 1 "

                . "$date "

                . "$store_id "

                . "$user_id "

                . "GROUP BY t.id ORDER BY waste_num DESC "

                . "$limit";

        //var_dump($query);exit;

        $result = $this->query($query);

        

        if($result->num_rows > 0){

            return $this->resultToArray($result);

        }

        

        return null;

    }

    

    public function getWasteDetailsByWasteId($tramiteId){

        $query = "SELECT "

                . "d.id,"

                . "d.waste_id,"

                . "d.product_id,"

                . "d.quantity,"

                . "d.cost,"

                . "d.total_cost,"

                . "d.price,"

                . "d.total_price,"

                . "p.descripcion as product "

                . "FROM $this->table_details d "

                . "LEFT JOIN pos_productos p ON d.product_id =  p.id "               

                . "WHERE d.waste_id = $tramiteId ";

        

        $result =  $this->query($query);

        

        if($result->num_rows > 0){

            $array = array();

            $result = $this->resultToArray($result);

            

            foreach($result as $row){

                $array[$row['id']] = $row;

            }

            

            return $array;

        }

        return null;                

    }

    

    public function getStringDetailsToEdit($id){

        $string = '';

        $ajax = new WasteAjax();

        

        $query = "SELECT * "

                . "FROM $this->table_details "

                . "WHERE waste_id = '$id' ";

        

        $result = $this->query($query);

        

        if($result->num_rows > 0){

            $result = $this->resultToArray($result);

            foreach($result as $row){

                $string .= $ajax->addDetail($row, $row['id'])['detail_string'];

            }

        }

        

        return $string;

    }

    

    public function getNextFolio(){        

        $query = "SELECT waste_num FROM $this->table ORDER BY waste_num DESC LIMIT 1";        

        $result = $this->query($query);

        

        if($result->num_rows > 0){

            $result = $result->fetch_object();

            $folio = $result->waste_num;

            $folio = $folio + 1;

            return $folio;

        }else{

            return 1;

        }

    }

    

    public function getListStatus(){

        $query = "SELECT * FROM status_code WHERE operation = 'Waste'";

        $result = $this->query($query);

        

        if($result->num_rows > 0){

            $array = array();

            foreach($result as $status){

                $array[$status['code']] = $status['description'];

            }

            return $array;

        }

        return null;

    }

    

    public function getListFiles($id){

        $fileManagement = new FileManagement();

        return $fileManagement->getStringListFilesByOperationAndPrefix('waste', $id);

    }

    

    public function showImages($id){

         $fileManagement = new FileManagement();

         return $fileManagement->getStringListFilesByOperationAndPrefix_Image('waste', $id);

    }

    

    public function createFilterFecha($options,$campoFecha = null ){

        if(!isset($options['startDate']) && !isset($options['endDate'])){return null;}        

        $startDate = $options['startDate'];

        $endDate = $options['endDate'];

        $fecha = null;

        $tools = new Tools();

        if($startDate!=null){

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

            if($endDate!=null){

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

                $fecha .=" AND $campoFecha BETWEEN '{$startDate}' AND '{$endDate}' ";

            }else{

                $fecha .=" AND $campoFecha BETWEEN '{$startDate}' AND '{$startDate}' ";

            }

        }elseif($endDate!=null){

            $fecha .=" AND $campoFecha BETWEEN '{$endDate}' AND '{$endDate}' ";

        }

        

        return $fecha;

    }

}