<?php   
class CobroTempRepository extends EntityRepository {

    private $table = 'cobros_temp_';
    
    public function __construct(){
        $login = new Login();
        $this->table = $this->table.$login->getId();
    }
    // Guarda en temporal
    public function save(array $data, $table = null) {
        if(isset($data['id']) && trim($data['id'])!= ''){
            $id = $data['id'];
            $result = $this->getById($id);
            if($result){        
                return parent::update($id, $data,$this->table);
            }
         }
         
         /*Si es efectivo verifico si existe ya un cobro registrado con esta formaPag, si existe, actualizo y sumo el nuevo monto*/
         if($data['formaPago']==3){
             $query = "SELECT id,monto FROM $this->table WHERE formaPago = 3";
             $result = $this->query($query);
             
             if($result->num_rows > 0){
                 $result = $result->fetch_object();
                 return parent::update($result->id, array('monto'=>$result->monto + $data['monto']), $this->table);
             }
         }
         
        $data['status'] = 1;
        unset($data['id']);
        return parent::save($data, $this->table);
    }
    
    // Guarda en tabla cobros
    public function saveCobros($idVenta,$total_venta,$cambio){
        $query = "SELECT SUM(monto)as monto FROM $this->table ";
        $result = $this->query($query);
        if($result->num_rows > 0){
            $result = $result->fetch_object();
            //echo $result->monto."|".$total_venta;
            if($result->monto < $total_venta){
                $flashmessenger = new FlashMessenger();
                $flashmessenger->addMessage(array('info'=>'Debe pagar el monto total de la venta.'));
                return null;
            }
        }
        
        $login = new Login();
        $fecha = date('Y-m-d');
        $creado_fecha = date('Y-m-d H:i:s');
        
        $query = "SELECT "
                . " '$fecha' as fecha,"
                . " '$idVenta' as idVenta,"
                . " IF(formaPago=3,monto-$cambio,monto)as monto,"
                . " formaPago as formaPago,"
                . " numDocumento as numDocumento,"
                . " SUBSTRING(cardnumber, -4)as last_4, "
                . " status as status,"
                . " '$creado_fecha' as creado_fecha,"
                . " '{$login->getId()}' as creado_por "
                . "FROM $this->table WHERE status = '1'";
                
        $result = $this->query($query);
        if($result->num_rows > 0){
            $result = $this->resultToArray($result);
            $repository = new EntityRepository();
            $operacionesRepo = new OperacionesTarjetasRepository();
            $operacionesRepo->setIdSale($row['numDocumento'],$idVenta);
              
            foreach($result as $row){
               $repository->save($row, 'cobros');
            }
            return true;
        }
    } 
    
    public function delete($id, $table = null) {
        
        return parent::delete($id, $this->table);
    }
    
    public function clearDetalles(){
        $query = "DELETE FROM $this->table WHERE status = '1'";
        $result = $this->query($query);
        
        if($result){
            return true;
        }
        return null;
    }
    
    public function truncate(){
        $query = "TRUNCATE ".$this->table;
        $result = $this->query($query);
        
        if($result){
            return true;
        }
        
        return null;
    }
    
    public function drop(){
        $query = "DROP TABLE ".$this->table;
        $result = $this->query($query);
        
        if($result){
            return true;
        }
        
        return null;
    }
    
    public function setVentaDetallesById($idVenta){
        $this->query("TRUNCATE ".$this->table);
        $query = "INSERT INTO ".$this->table." (idVenta,idProducto,cantidad,descripcion,precio,immpuestos,descuento,cuentaContable)
                    SELECT idVenta,idProducto,cantidad,descripcion,precio,impuestos,descuento,cuentaContable FROM ventasdetalles WHERE idVenta = '$idVenta'";
        
        $result = $this->query($query);
        if($result){
            return true;
        }        
        return null;
    }

    public function update($id, $data, $table = null) {
        if(isset($data['idVenta'])){
            if($data['idVenta']=='' || !$data['idVenta']){
                unset($data['idVenta']);
            }
        }
        
        return parent::update($id, $data, $this->table);
    }

    public function getById($id, $table = null,$selectAux = null) {
        return parent::getById($id, $this->table,$selectAux);
    }    

    public function isUsedInRecord($id, array $buscarEn = null,$andWhere = null) {
        return parent::isUsedInRecord($id, array('pfa' => 'usuario'));
    }
    
   public function crearTablaCobrosForUser(){
        $login = new Login();
        //$query = "DROP TABLE IF EXISTS cobros_temp_".$login->getId();
        //$this->query($query);
        
        $query = "CREATE TABLE IF NOT EXISTS cobros_temp_".$login->getId()." 
                 (  `id` int(11) NOT NULL AUTO_INCREMENT,
                    `idDetalle` int(11) NULL,
                    `idVenta` int(11) NULL,
                    `monto` double NULL,
                    `formaPago` int(11) NULL,
                    `numDocumento` varchar(255) DEFAULT NULL,
                    `cardnumber` varchar(255) DEFAULT NULL,
                    `exp_month` varchar(2) DEFAULT NULL,
                    `exp_year` varchar(4) DEFAULT NULL,
                    `cvv` varchar(3) DEFAULT NULL,
                    `status` int(11) NULL,
                    PRIMARY KEY (`id`)
                 )ENGINE=InnoDB DEFAULT CHARSET=utf8;";
        
       $result = $this->query($query);
    }
    
    public function getCobrosVentaActiva(){
            $query = "SELECT *,fxGetFormaPagoName(formaPago)as formaPagoName FROM $this->table WHERE status = '1'";
            $result = $this->query($query);
            
            if($result->num_rows > 0){
                return $this->resultToArray($result);
            }
            return null;
    }
}