Warning: Undefined array key 1094 in /home/computer/public_html/dooframework/diagnostic/debug.php on line 126 Warning: Undefined array key 1094 in /home/computer/public_html/dooframework/diagnostic/debug.php on line 129 Warning: Undefined array key 1 in /home/computer/public_html/dooframework/diagnostic/debug.php on line 133 Deprecated: str_replace(): Passing null to parameter #3 ($subject) of type array|string is deprecated in /home/computer/public_html/dooframework/diagnostic/debug.php on line 133 DooPHP Diagnostics - Trying to access array offset on false

See file /home/computer/public_html/protected/controller/MainController.php


+ Error on line 1095

<?php //tempstart
<?php

/**
 * MainController
 * @author Manuel Cuevas
 */
class MainController extends DooController {

    public $data = [];
    public $params = [];
    public $routematch = [];

    public function index() {
        Doo::loadModel("Contenidos");
        $p = Doo::db()->find('Contenidos', array('where' => 'page="empresa"', 'limit' => 1));
        $this->data['html'] = $p->descripcion;

        $p2 = Doo::db()->find('Contenidos', array('where' => 'page="formapago"', 'limit' => 1));
        $this->data['titulopago'] = $p2->titulo;
        $this->data['htmlpago'] = $p2->descripcion;

        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->Banner();
        $this->configuracion();
        $this->ProductosPromocion();
        $this->ProductosDestacados();
        $this->busqueda_avanzada();
        $this->getProductos();
        $this->Aliados();
        $this->Categorias();

        $this->data['content'] = 'inicio';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function renderSearchOrders() {
        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->Banner();
        $this->configuracion();
        $this->ProductosPromocion();
        $this->ProductosDestacados();
        $this->busqueda_avanzada();
        $this->getProductos();
        $this->Aliados();
        $this->Categorias();

        $this->data['content'] = 'search_orders';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function searchOrders() {
        $identificationType = $_POST["identificationType"];
        $identification = $_POST["identification"];
        $reference = $_POST["reference"];

        $orders = Doo::db()->query("SELECT o.`id` AS reference, DATE_FORMAT(o.`fecha`, '%b %d, %Y, %h:%i:%s %p') AS fecha, o.`total` AS valor, o.`costoenvio` AS valor_envio, o.`estado`
        FROM `pedidos` p
        INNER JOIN `pedidos` o ON (p.`nodocumento` = o.`nodocumento` AND p.`tipo_docto` = o.`tipo_docto`)
        WHERE p.`id` = '$reference' AND p.`nodocumento` = '$identification' AND p.`tipo_docto` = '$identificationType'
        ORDER BY o.`fecha` DESC LIMIT 5")->fetchAll();

        if ($orders && count($orders) > 0) {
            echo json_encode(array('success' => true, 'message' => 'Informacion consultada exitosamente', 'orders' => $orders));
        } else {
            echo json_encode(array('success' => false, 'message' => 'No se encontraron pedidos para la información suministrada', 'orders' => array()));
        }
    }

    public function send_otp(){
        Doo::loadClass("mail/PHPMailer");
        Doo::loadController("TokensController");
        $token = new TokensController();
        $mail = new PHPMailer();
        //$mail->isSMTP(); 
        //$mail->SMTPAuth = true;
        $mail->Host = 'mail.compuworking.com.co';
        $mail->Port = '465';
        $mail->SMTPSecure = 'tls';
        $mail->Username = 'notificaciones@compuworking.com.co';
        $mail->Password = 't_@drxNXLlRi';
        $mail->AddAddress($_POST['email']);
        $mail->Subject = 'Inicio de Sesion';
        $mail->MsgHTML($token->basicTokenTemplate());
        $mail->setFrom('notificaciones@compuworking.com.co');
        $mail->SMTPDebug  = 2;
        $mail->send();
        echo json_encode(array("status"=>"success"));
    }

    public function validateToken(){
        $token = new TokensController();
        $token=$_POST['codgo_otp'];
        $isValid = Doo::db()->query("SELECT * FROM tokens where date_add(create_at,interval 15 minute) > date(now()) and token='$token';")->fetch();
        if($token){
            $token->desactivate($token);
            echo json_encode(array('status'=>'valid'));
        }else{
            echo json_encode(array('status'=>'invalid'));
        }
        
    }

    public function renderi() {
        $this->data["vale"]="";
        $this->data["rootUrl"]=Doo::conf()->APP_URL;
        $this->renderc("viewcart_item",  $this->data,TRUE);
    }
    
    

    public function respuesta() {        
        $ch = curl_init("https://secure.epayco.co/validation/v1/reference/".$_GET['ref_payco']); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data=json_decode($data);
        $data=$data->data;
       $res = Doo::db()->query("update pedidos set estado ='$data->x_respuesta' where id='$data->x_id_invoice'");
       
        if (isset($_SESSION["carrito"])) {
            unset($_SESSION["carrito"]);
        }
        
       if($data->x_response=='Rechazada'){
           $this->sendConfirmacionclienteClient($data->x_id_invoice,"HOLA, TU PAGO HA SIDO RECHAZADO VERIFICA TUS DATOS");
       }else{
           $this->sendConfirmacionclienteClient($data->x_id_invoice,"HOLA, HEMOS PROCESADO EXITOSAMENTE SU PAGO, EN ESTOS MOMENTOS PROCEDEREMOS A PREPARAR TU PEDIDO");
       }      
        $this->data["vale"]="";
        $this->data["rootUrl"]=Doo::conf()->APP_URL;
        $this->renderc("respuesta",  $this->data,TRUE);
    }
    
     public function sendConfirmacionclienteClient($id,$text) {
         Doo::loadHelper('DooMailer');
        $pedido = Doo::db()->query("SELECT * FROM pedidos WHERE id = ?",array($id))->fetch();
        $pro = Doo::db()->query("SELECT * FROM pedido_productos pp inner join productos p on (p.id=pp.cod_prod) where id_pedido = ?;",array($id))->fetchAll();
        $html='';
        foreach($pro  as $p){
                    $valor = number_format($p["valor"], 2);
            $html.=    "<tr>
                        <td style='height:50px; width:80px;' >
                            <img style='width: 64px;' class='img-responsive' src='https://www.computerworking.com.co/uploads/productos/$p[imagen2]' alt='image'>
                        </td>        
                        <td style='height:80px; ' >
                            <div style='padding-left:10px; '> $p[nom_prod]</div><br>
                            <div style='padding-left:10px; '><b> Valor:</b> $valor<br><b>Cantidad:</b> $p[cantidad]</div>
                        </td>                      
                    </tr>";
        }
        
        $fecha = date('Y-m-d H:i:s');
        $total = number_format($pedido['costoenvio'] + $pedido['subtotal'], 2);
        $envio = number_format($pedido["costoenvio"], 2);
        $subtotal = number_format($pedido["subtotal"], 2);
        
        $mail = new DooMailer();
        $msj="<body link='#00a5b5' vlink='#00a5b5' alink='#00a5b5'>
                    <table class=' main contenttable' align='center' style='font-weight: normal;border-collapse: collapse;border: 0;margin-left: auto;margin-right: auto;padding: 0;font-family: Arial, sans-serif;color: #555559;background-color: white;font-size: 16px;line-height: 26px;width: 600px;'>
                        <tr>
                            <td class='border' style='border-collapse: collapse;border: 1px solid #eeeff0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;'>
                                <table style='font-weight: normal;border-collapse: collapse;border: 0;margin: 0;padding: 0;font-family: Arial, sans-serif;'>
                                    <tr>
                                        <td colspan='4' valign='top' class='image-section' style='text-align:center;border-collapse: collapse;border: 0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;background-color: #fff;border-bottom: 4px solid #014daf'>
                                            <a href='http://www.computerworking.com.co'><img class='top-image' src='https://www.computerworking.com.co/global/img/logo.jpg' style='line-height: 1;width: 350px;' alt=''></a>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td valign='top' class='side title' style='border-collapse: collapse;border: 0;margin: 0;padding: 20px;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;vertical-align: top;background-color: white;border-top: none;'>
                                            <table style='font-weight: normal;border-collapse: collapse;border: 0;margin: 0;padding: 0;font-family: Arial, sans-serif;'>
                                                <tr>
                                                    <td class='head-title' style='border-collapse: collapse;border: 0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 28px;line-height: 34px;font-weight: bold; text-align: center;'>
                                                        <div class='mktEditable' id='main_title'>
                                                        
                                                        </div>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class='sub-title' style='border-collapse: collapse;border: 0;margin: 0;padding: 0;padding-top:5px;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 18px;line-height: 29px;font-weight: bold;text-align: center;'>
                                                        <div class='mktEditable' id='intro_title'>
                                                
                                                        </div>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class='top-padding' style='border-collapse: collapse;border: 0;margin: 0;padding: 5px;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;'></td>
                                                </tr>
                                                <tr>
                                                    <td class='grey-block' style='border-collapse: collapse;border: 0;margin: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;background-color: #fff; text-align:center;'>
                                                    <div class='mktEditable' id='cta'>
                                                    <img class='top-image' src='https://www.computerworking.com.co/global/img/img_7-2.jpg' width='560'/><br><br>
                                                        
                                                    </div>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class='top-padding' style='border-collapse: collapse;border: 0;margin: 0;padding: 15px 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 21px;'>
                                                        <hr size='1' color='#eeeff0'>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class='text' style='text-align:center;border-collapse: collapse;border: 0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;'>
                                                        <div class='mktEditable' id='main_text'>
                                                        $text. <br> RECUERDA QUE SI EL ENVIO ES LOCAL ENTREGAREMOS EN UN TIEMPO DE 24 HORAS Y PARA ENVIOS NACIONALES DE 2 A 4 DIAS SEGÚN DESTINO.<br/><br/>
                
                                                        SI TIENE ALGUNA PREGUNTA O COMENTARIO, POR FAVOR ESCRIBENOS AL 3008151220.<br/><br/>
                                                            ¡SERA UN PLACER AYUDARTE!.
                
                                                        </div>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td style='border-collapse: collapse;border: 0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 24px;'>
                                                     &nbsp;<br>
                                                    </td>
                                                </tr>
                                                <tr>
                                                    <td class='text' style='border-collapse: collapse;border: 0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 24px;'>
                                                        <div class='mktEditable' id='download_button' style='border-top:1px solid #F5F5F5; height:135px; text-align: center;'>
                                                            <table style='width:100%'>
                                                                <tr style='background:#F5F5F5'>
                                                                    <td style='width:50%'>Estado de transacción: </td>
                                                                    <td>$pedido[estado]</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>Número de pedido: </td>
                                                                    <td>$pedido[id]</td>     
                                                                </tr>
                                                                <tr style='background:#F5F5F5'>
                                                                    <td>Costo de Envío:</td>
                                                                    <td>$envio</td>
                                                                </tr>
                                                                <tr>
                                                                    <td>Valor compra: </td>
                                                                    <td>$subtotal</td>
                                                                </tr>
                                                                <tr style='background:#F5F5F5'>
                                                                    <td>Valor Total :   </td>
                                                                    <td>$total</td>
                                                                </tr>                                        
                                                            </table>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style='font-family: Arial, sans-serif; -webkit-text-size-adjust: none;' align='center'>
                                            <div style='border-top:1px solid #F5F5F5; height:70px; text-align: center;'>
                                                <table style='width: 100%;'>
                                                    <tr>
                                                        <td align='center' style='font-family: Arial, sans-serif; -webkit-text-size-adjust: none; font-size: 16px;'>
                                                            <p style='color: #014daf;'>Datos de envío</p>                                        
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </td>          
                                    </tr>
                                    <tr style='background:#014daf85;height:200px'>                                    
                                        <td>               
                                            <table  style='width: 100%;     text-align: center;'>
                                              <tr>
                                                <td style='width:50%'><b>Nombre:</b><br>$pedido[nombre] $pedido[papellido]</td>
                                                <td style='width:50%'><b>Dirección:</b><br>$pedido[direccion]</td> 
                                              </tr>
                                              <tr>
                                              <td><b>Referencia:</b><br>$pedido[telecasa]</td> 
                                                <td><b>Email</b><br>$pedido[email]</td>                                                                
                                              </tr>
                                              <tr>
                                                <td><b>Teléfono:</b><br>$pedido[celular]</td> 
                                                <td><b>Numero de Cédula</b> <br>$pedido[nodocumento]</td>
                                              </tr>                                              
                                            </table>
                                        </td>                                                  
                                    </tr>

                                    <tr>
                                        <td style='font-family: Arial, sans-serif; -webkit-text-size-adjust: none;' align='center'>
                                            <div style='border-top:1px solid #F5F5F5; height:70px; text-align: center;'>
                                                <table style='width: 100%;'>
                                                    <tr>
                                                        <td align='center' style='font-family: Arial, sans-serif; -webkit-text-size-adjust: none; font-size: 16px;'>
                                                            <p style='color: #014daf;'>Datos de facturación</p>                                        
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </td>          
                                    </tr>
                                    <tr style='background:#014daf85;height:200px'>                                    
                                        <td>               
                                            <table  style='width: 100%;     text-align: center;'>
                                              <tr>
                                                <td style='width:50%'><b>Nombre o Razón Social:</b><br>$pedido[razon_social] </td>
                                                <td style='width:50%'><b>Dirección:</b><br>$pedido[dir_empresa]</td> 
                                              </tr>
                                              <tr>
                                              <td><b>Documento: </b> <br>$pedido[nit_empresa]</td>
                                                <td><b>Email: </b><br>$pedido[email_empresa]</td>                                                                
                                              </tr>
                                                                                          
                                            </table>
                                        </td>                                                  
                                    </tr>
                                      <tr>
                                        <td style='font-family: Arial, sans-serif; -webkit-text-size-adjust: none;' align='center'>
                                            <div style='border-top:1px solid #F5F5F5; height:70px; text-align: center;'>
                                                <table style='width: 100%;'>
                                                    <tr>
                                                        <td align='center' style='font-family: Arial, sans-serif; -webkit-text-size-adjust: none; font-size: 16px;'>
                                                            <p style='color: #014daf;'>Productos Adquiridos</p>                                        
                                                        </td>
                                                    </tr>
                                                </table>
                                            </div>
                                        </td>          
                                    </tr>
                                                                        
                                    <tr>
                                        <td   style='border-collapse: collapse;border: 0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;'>
                                            <table style='font-weight: normal;border-collapse: collapse;border: 0;margin: 0;padding: 0;font-family: Arial, sans-serif;'>
                                                <tr>
                                                    <td    style='border-collapse: collapse;border: 0;margin: 0;padding: 10px;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;'>
                                                        <table style='font-weight: normal;border-collapse: collapse;border: 0;margin: 0;padding: 0;font-family: Arial, sans-serif;'>
                                                             $html
                                                        </table>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr bgcolor='#fff' style='border-top: 4px solid #00a5b5;'>
                                        <td valign='top' class='footer' style='border-collapse: collapse;border: 0;margin: 0;padding: 0;-webkit-text-size-adjust: none;color: #555559;font-family: Arial, sans-serif;font-size: 16px;line-height: 26px;background: #fff;text-align: center;'>
                                            <table style='font-weight: normal;border-collapse: collapse;border: 0;margin: 0;padding: 0;font-family: Arial, sans-serif;'>
                                                <tr>
                                                    
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                  </body>";
  
  
  
        
        $mail->addTo($pedido['email']);
        $mail->addTo("ventas6@compuworking.com.co");
        $mail->setSubject('Confirmación de compra ');
        $mail->setBodyHtml($msj);
        $mail->setFrom('ventas6@compuworking.com.co');
        $mail->send();
    }
   
    public function configuracion() {
        $sql = "SELECT id,nombre,fondo_pagina,footer_1,footer_2,footer_3,footer_4,"
                . "title_fot_1,title_fot_2,title_fot_3,title_fot_4,facebook,twitter,instagram"
                . " from plantilla where estado=1";
        $rs = Doo::db()->query($sql)->fetch();
        $this->data['planti'] = $rs;
    }

    public function getProductos() {
        $pst = filter_input_array(INPUT_POST);
        if (!isset($pst["texto"])) {
            if (!isset($this->params['texto'])) {
                $texto = "";
            } else {
                $texto = $this->params['texto'];
            }
        } else {
            $texto = $pst["texto"];
        }
        $where = "publicado='S' AND novedoso='S' AND nombre LIKE '%$texto%' AND CURDATE() <= fecha_vencimiento ORDER BY id_fabricante,precio_venta DESC";
        $rst = Doo::db()->query("select count(*) as total FROM productos where " . $where);
        $t = $rst->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        }
        if ($total == 0) {
            $total = 1;
        }
        Doo::loadHelper('DooPager');
        $pager = new DooPager("#", $total, 12, 10);
        if (isset($this->params['number'])) {
            $pager->paginate(intval($this->params['number']));
        } else {
            $pager->paginate(1);
        }
        $sql = "SELECT id,nombre,caract,precio_venta,precio_promocion,imagen2 FROM productos WHERE " . $where;
        $this->data['productos'] = Doo::db()->query($sql . " LIMIT $pager->limit")->fetchAll();
        $this->data['pager'] = $pager->output;
        $this->data['texto'] = $texto;
    }

    public function getProductosajax() {
        $pst = filter_input_array(INPUT_POST);
        if (!isset($pst["texto"])) {
            $texto = "";
        } else {
            $texto = $pst["texto"];
        }

        $where = "publicado='S'";
        if (isset($pst["novedoso"])) {
            $where.=" AND novedoso='S' ";
        }

        if ($texto != "") {
            $where.=" AND (nombre LIKE '%$texto%' OR descripcion LIKE '%$texto %' OR caract LIKE '%$texto %') ORDER BY id_fabricante,precio_venta DESC";
        } else {
            $where.=" AND CURDATE() <= fecha_vencimiento ORDER BY id_fabricante,precio_venta DESC";
        }

        $rst = Doo::db()->query("select count(*) as total FROM productos where " . $where);
        $t = $rst->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        }
        if ($total == 0) {
            $total = 1;
        }
        Doo::loadHelper('DooPager');
        $pager = new DooPager("#", $total, 12, 10);
        $pg = filter_input(INPUT_POST, "page");
        if (isset($pg)) {
            $pager->paginate(intval($pg));
        } else {
            $pager->paginate(1);
        }
        $sql = "SELECT id,nombre,caract,precio_venta,iva,precio_promocion,imagen2 FROM productos WHERE " . $where;
        $this->data['productos'] = Doo::db()->query($sql . " LIMIT $pager->limit")->fetchAll();
        $this->data['texto'] = $texto;
        $this->data['id_categoria'] = "0";
        $this->data['content'] = 'itemsbusqueda';
        $this->data['pager'] = $pager->output;
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('itemsbusqueda', $this->data, true);
    }

    public function getCombo($id_catg) {
        $sql = "SELECT nombre,imagen FROM combos WHERE id_categoria='$id_catg'";
        $rs = Doo::db()->query($sql)->fetch();
        if ($rs) {
            echo '<div class="col-lg-12"><img class="img-responsive"  src="' . Doo::conf()->APP_URL . 'gestorweb/img_combos/' . $rs["imagen"] . '" alt="' . $rs["nombre"] . '" title="' . $rs["nombre"] . '"/></div>';
        }
    }

    public function Banner() {
        $banner = Doo::db()->find('Banners', array("select" => "id,nombre,imagen", "where" => "publicado='S'", "ORDER" => "nombre", "asc" => "nombre"));
        $this->data['banners'] = $banner;
    }

    public function Aliados() {
        $aliado = Doo::db()->find('Aliados', array("select" => "id,nombre,foto", "where" => "estado=1", "ORDER" => "nombre", "asc" => "nombre"));
        $this->data['aliado'] = $aliado;
    }

    public function Categorias() {
        $ctg = Doo::db()->find('Categorias', array("select" => "id,nombre,imagen", "where" => "estado=1 and principal = 'S'", "ORDER" => "nombre", "asc" => "nombre", "limit" => 6));
        $this->data['categoria'] = $ctg;
    }

    public function ProductosPromocion() {
        $promocion = Doo::db()->find('Productos', array("select" => "id,nombre,iva,precio_venta,descripcion,precio_promocion,imagen2", "where" => "publicado='S' and promocion='S' and  CURDATE() <= fecha_vencimiento", "ORDER" => "nombre", "asc" => "nombre", "limit" => 8));
        $this->data['promocion'] = $promocion;
    }

    public function ProductosDestacados() {
        $destacado = Doo::db()->find('Productos', array("select" => "id,nombre,iva,precio_venta,precio_promocion,imagen2,descripcion", "where" => "publicado='S' and novedoso='S' and  fecha_vencimiento >= CURDATE()", "ORDER" => "nombre", "asc" => "nombre", "limit" => 8));
       
        //var_dump(Doo::db()->find('Productos', array("select" => "id,nombre,iva,precio_venta,precio_promocion,imagen2,descripcion", "where" => "publicado='S' and novedoso='S' and  CURDATE() <= fecha_vencimiento", "ORDER" => "nombre", "asc" => "nombre", "limit" => 8)));
        $this->data['destacado'] = $destacado;
    }

    function getInputINT($key) {
        $val = filter_input(INPUT_GET, $key, FILTER_SANITIZE_NUMBER_INT);
        if (is_null($val)) {
            return false;
        } else if (!$val) {
            return false;
        } else {
            return $val;
        }
    }

    public function getInfoProducto() {
        $id = $this->getInputINT("id");
        
        if (!$id) {
            return Doo::conf()->APP_URL;
        } else {
             
            
            $n = Doo::db()->find('Productos', array("select" => "id,nombre,iva,codigo,imagen,imagen2,precio_venta,precio_promocion,caract,descripcion,id_categoria,id_fabricante,telefono_fab", "where" => 'id=? AND publicado="S"', 'limit' => 1, 'param' => array($id)));
            if (is_object($n)) {
                $this->data['titulo'] = $n->nombre;
                $this->data['html'] = $n->codigo;
                $this->data['id'] = $n->id;
                $this->data['imagen_small'] = $n->imagen;
                $this->data['imagen_big'] = $n->imagen2;
                $this->data['cod_produc'] = $n->codigo;
                $this->data['precioventa'] = $n->precio_venta;
                $this->data['iva'] = $n->iva;
                $this->data['preciopromocion'] = $n->precio_promocion;
                $this->data['caracteristicas'] = $n->caract;
                $this->data['descripcionP'] = $n->descripcion;
                $this->data['telefono_fabricante'] = $n->telefono_fab;
                $this->data['categoria'] = $n->id_categoria;
                $this->buildMenu();
                $this->buildMenuH();
                $this->busqueda_avanzada();
                $id_cat = $n->id_categoria;
                $product = Doo::db()->find('Productos', array("select" => "id,iva,nombre,imagen2,descripcion,caract,precio_venta,precio_promocion", "where" => "id_categoria='$id_cat' and publicado='S' and id != $id ", 'limit' => '10', "ORDER" => "nombre", "asc" => "nombre"));
                $this->data['ctg_relacionada'] = $product;
                $this->configuracion();
                $this->data['content'] = 'infoproduct';
                $id_fab = $n->id_fabricante;
                $nom_fab1 = Doo::db()->query("SELECT nombre FROM fabricantes WHERE id=?", array($id_fab))->fetch();
                $nom_fab = $nom_fab1["nombre"];
                $nom_cag1 = Doo::db()->query("SELECT nombre FROM categorias WHERE id=?", array($id_cat))->fetch();
                $nom_cag = $nom_cag1["nombre"];

                $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" class="previous" title="Pagina de inicio">Inicio</a></li>';
                //$ruta.='<li><a href="' . Doo::conf()->APP_URL . 'fabricante/' . $id_fab . '" class="previous" title="' . $nom_fab . '">' . $nom_fab . '</a></li>';
//                $ruta.='<a href="'.Doo::conf()->APP_URL.'busqueda/'.$id_fab.'/'.$id_cat.'" class="previous" title="'.$nom_cag.'">'.$nom_cag.'</a>';
              //  $ruta.='<li><a href="' . Doo::conf()->APP_URL . 'categorias?id_cat=' . $id_cat . '" class="active" title="' . $nom_cag . '">' . $nom_cag . '</a></li>';
              $ruta.='<li><a href="' . Doo::conf()->APP_URL . 'categorias/' . $id_cat . '/false" class="active" title="' . $nom_cag . '">' . $nom_cag . '</a></li>';
//                $ruta.='<li><a href="'.Doo::conf()->APP_URL.'infoproducto?id='.$id.'" class="previous" title="'.$n->nombre.'">'.$n->nombre.'</a></li>';

                $_SESSION["stak_url"] = $ruta;
                //$this->data['stak_url'] = $ruta;
                $this->data['texto'] = '';
                $this->data['rootUrl'] = Doo::conf()->APP_URL;
                $this->renderc('home', $this->data, true);
            } else {
                return Doo::conf()->APP_URL;
            }
        }
    }
    
    public function getSubcategorias() {
        $id = $this->getInputINT("id");
        if (!$id) {
            return Doo::conf()->APP_URL;
        } else {

                $nom_cag1 = Doo::db()->query("SELECT nombre,imagen
                 FROM categorias WHERE id=?", array($id))->fetch();

                $nom_cag = $nom_cag1["nombre"];
                $nom_img = $nom_cag1["imagen"];

               $sub =  Doo::db()->query("SELECT c.id,c.nombre,c.imagen,c.depende ,(SELECT COUNT(t.id) 
                FROM categorias t WHERE depende=c.id)AS cantidad
                FROM categorias c WHERE depende = '$id' AND c.estado = 1
                GROUP BY(id)")->fetchAll();

                $this->data["texto"]= $nom_cag;
                $this->data["img"]= $nom_img;
                $this->buildMenu();
                $this->buildMenuH();
                $this->busqueda_avanzada();
                //$id_cat = $n->id_categoria;
                $this->data['subtctg'] = $sub;
                $this->configuracion();
                $this->data['content'] = 'page_categorias';
                 $this->data['rootUrl'] = Doo::conf()->APP_URL;
             $this->renderc('home', $this->data, true);
                
        }
    }

    public function getVistaImprimir() {
        $id = $this->getInputINT("id");
        if (!$id) {
            return Doo::conf()->APP_URL;
        } else {
            $n = Doo::db()->find('Productos', array("select" => "id,nombre,codigo,imagen,imagen2,precio_venta,precio_promocion,caract,descripcion", "where" => 'id=?', 'limit' => 1, 'param' => array($id)));
            $sql = Doo::db()->query("SELECT c.nombre,c.id_categoria,c.imagen AS imgcombo FROM combos c INNER JOIN productos p ON (p.id_categoria=c.id_categoria) WHERE p.id='$id' LIMIT 1")->fetch();

            $this->data['img_combos'] = $sql ? $sql['imgcombo'] : "";

            if (is_object($n)) {
                $this->data['titulo'] = $n->nombre;
                $this->data['codigo'] = $n->codigo;
                $this->data['imagen'] = $n->imagen;
                $this->data['imagen2'] = $n->imagen2;
                $this->data['precio_venta'] = $n->precio_venta;
                $this->data['descripcion'] = $n->descripcion;
                $this->data['caracteristica'] = $n->caract;
                $this->data['preciopromocion'] = $n->precio_promocion;

                $this->data['rootUrl'] = Doo::conf()->APP_URL;
                $this->renderc('vista_imprimir', $this->data, true);
                
               /* Doo::loadClass("pdf/PDF_ImageAlpha");
                Doo::loadClass("reportes/ImprimirVista");
                $pdf = new ImprimirVista();
                $pdf->AliasNbPages();
                $pdf->AddPage();
                $pdf->body($this->data);
                $pdf->Output();*/
                
            } else {
//                return Doo::conf()->APP_URL;
            }
        }
    }

    public function imagen() {
        $param = $this->params['pindex'];
        $id = $_REQUEST['id'];
        $rs = Doo::db()->find($param, array("select" => "imagen",
            "where" => "id = ?",
            "limit" => 1,
            "param" => array($id)));
        $imagen = $rs->imagen;

        if ($imagen == "") {
            echo "";
        } else {
            Header("Content-type: image/jpg ");
            echo $imagen;
        }
    }

    public function verMapa() {
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('mapa', $this->data);
    }

    public function showPage() {
        $page = $this->params['pagina'];
        Doo::loadModel("Contenidos");
        $p = new Contenidos();
        $p->page = $page;
        $p = Doo::db()->find($p, array('limit' => 1));
        if ($p == false) {
            return array(Doo::conf()->APP_URL . "/error", 404);
        }
        $this->data['titulo'] = $p->titulo;
        $this->data['html'] = $p->descripcion;
        $this->configuracion();
        $this->buildMenu();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        $this->data['content'] = 'pagina';
        $this->data['texto'] = '';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function getBanner() {
        $id = $_REQUEST['id'];
        $b = Doo::db()->find('Articulos', array("select" => "id,titulo,descripcion", "where" => 'id=?', 'limit' => 1, 'param' => array($id)));
        $this->data['titulo'] = $b->titulo;
        $this->data['html'] = $b->descripcion;
        $this->buildMenu();
        $this->Menu();
        $this->NoticiasyAseguradoras();
        $this->buildOptionfotter();
        $this->data['content'] = 'pagina';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    private function buildMenu() {
        $sql = "SELECT c.id,c.nombre,c.imagen,c.depende,c.depende2 FROM categorias c WHERE depende='0' and estado=1 ORDER BY orden LIMIT 0,7";
        $rs = Doo::db()->query($sql);
        $parentMenu = $rs->fetchAll();
        $contentHtml = "";
        $contents = Doo::db()->query("SELECT * FROM contenidos WHERE `page` != 'formapago'")->fetchAll();
        foreach($contents as $content) {
            $contentHtml .= 
            '<li class="hidden-xs">
                <a href="' . Doo::conf()->APP_URL . $content["page"] . '">' . $content["titulo"] . '</a>
            </li>';
        }

        $this->data["htmlmenu"] = '<ul class="nav navbar-nav navbar-right">
        <li class="hidden-xs">
            <a href="' . Doo::conf()->APP_URL .'">
                <i class="fa fa-home" aria-hidden="true"></i>                  
            </a>
        </li>
        <li class="dropdown megaDropMenu">
            <a href="javascript:void(0)" class="dropdown-toggle " data-toggle="dropdown" data-hover="dropdown" data-delay="300" data-close-others="true" aria-expanded="false">
                NOSOTROS
            </a>
            <ul class="dropdown-menu row ">
                <li class="col-sm-12 col-xs-12 unique">
                    <ul class="list-unstyle">
                        <li class="hidden-xs">
                            <a href="' . Doo::conf()->APP_URL .'contactenos">
                                Contactenos
                            </a>
                        </li>
                        <li class="hidden-xs">
                            <a target="_blank" href="' . Doo::conf()->APP_URL .'global/documentos/2. Politica Tratamiento Datos.pdf">Politica Tratamiento Datos</a>
                        </li>
                        <li class="hidden-xs">
                            <a target="_blank" href="' . Doo::conf()->APP_URL .'global/documentos/3. TyC COMPUWORKING Consumidor.pdf">Términos y Condiciones</a>
                        </li>
                        <li class="hidden-xs">
                            <a target="_blank" href="https://www.sic.gov.co/">SIC</a>
                        </li>'
                        . $contentHtml .
                        '
                    </ul>
                </li>
            </ul>
        </li>';
        $this->buildChildMenu($parentMenu, false);
        $this->data["htmlmenu"].= '</ul>';
    }

    private function buildChildMenu($parentMenu, $sub) {

        foreach ($parentMenu as $row) {
            $items = array();
            $submenu = $row["depende"];
            $submenu2 = $row["depende2"];

            $codigo = $row["id"];
            $url = "categoria/" . $row["id"];
            $url2 = "principalproducto/" . $row["id"];
            $validar = Doo::db()->query("SELECT COUNT(c.`depende2`)AS CANTIDAD FROM categorias c WHERE  "
                            . "depende='$codigo' AND estado=1 AND c.`depende2`='S' ORDER BY orden ")->fetch();

            if ($validar["CANTIDAD"] == 1) {
                $mega = '';
                $width = 'widthmenu';
                $tamano = 'col-sm-4';
                $dimension = 'style="background: rgb(255, 255, 255) url(' . Doo::conf()->APP_URL . 'gestorweb/imagenes/img_categorias/' . $row["imagen"] . ') no-repeat scroll  right bottom / 220px auto"';
            } else if ($validar["CANTIDAD"] == 2) {
                $mega = '';
                $width = 'widthmenu';
                $tamano = 'col-sm-3';
                $dimension = 'style="background: rgb(255, 255, 255) url(' . Doo::conf()->APP_URL . 'gestorweb/imagenes/img_categorias/' . $row["imagen"] . ') no-repeat scroll  right bottom / 220px auto"';
            } else {

                $mega = 'megaDropMenu';
                $width = '';
                $tamano = 'col-sm-2';
                $dimension = 'style="background: rgb(255, 255, 255) url(' . Doo::conf()->APP_URL . 'gestorweb/imagenes/img_categorias/' . $row["imagen"] . ') no-repeat scroll right bottom / 220px auto"';
            }
            if ($submenu2 == 'S') {
                if ($submenu == 0) {
                    $this->data["htmlmenu"].= '<li class="dropdown ' . $mega . ' ">'
                            . ' <a href="javascript:void(0)" class="dropdown-toggle " data-toggle="dropdown" data-hover="dropdown" data-delay="300" data-close-others="true" aria-expanded="false">' . $row["nombre"] . '</a>';
                    $this->data["htmlmenu"].='<ul  class="dropdown-menu row ' . $width . '"' . $dimension . '>';
                }

                if ($submenu != 0) {

                    $this->data["htmlmenu"].= '<li class="col-sm-2 col-xs-12">
                      <ul class="list-unstyled">
                        <li>Products Grid View</li>';
                    $this->data["htmlmenu"].='</ul>';
                    $this->data["htmlmenu"].='</li>';
                }

                $sql = "SELECT c.imagen_icon,c.id,c.nombre,c.imagen,c.depende,c.depende2 FROM categorias c WHERE  depende='$codigo' and estado=1 ORDER BY orden";
                $rs = Doo::db()->query($sql);
                $i = 0;
                foreach ($rs as $p) {
                    $sql2 = "SELECT c.id,c.nombre,c.imagen,c.depende,c.depende2 FROM categorias c WHERE  depende=" . $p['id'] . " and estado=1 ORDER BY orden";
                    $rs2 = Doo::db()->query($sql2)->fetchAll();
                    if ($rs2) {
                        $i++;
                        $this->data["htmlmenu"].='<li  class="' . $tamano . ' col-xs-12 unique"><ul class="list-unstyle">';
                        $this->data["htmlmenu"].='<li><a class="submenu" style="white-space:nowrap" href="' . Doo::conf()->APP_URL . 'categorias/' . $p['id'] . '/true"><img class="unique-img" src="'. Doo::conf()->APP_URL .'/gestorweb/img_icon/'. $p['imagen_icon'] .'" > ' . $p['nombre'] . '</a></li>';
                        foreach ($rs2 as $data) {
                            $this->data["htmlmenu"].='<li class="hidden-xs"><a href="' . Doo::conf()->APP_URL . 'categorias/' . $data["id"] . '/false">' . $data['nombre'] . '</a></li>';
                        }
                        $this->data["htmlmenu"].='</ul></li>';
                        if ($i == 5) {
                            $i = 0;
                            $this->data["htmlmenu"].='<div class="clearfix"></div>';
                        }
                    } else {
                        $obj = array("nombre" => $p['nombre'], "id" => $p['id']);
                        $items[] = $obj;
                    }                     
                }



                if ($submenu != 0) {
                    $this->data["htmlmenu"].='</ul>
                    </li>
                    ';
                }

                if ($submenu == 0) {
                    $this->data["htmlmenu"].='<li class="col-sm-2 col-xs-12">';
                    foreach ($items as $p) {
                        $this->data["htmlmenu"].='<ul>';
                        $this->data["htmlmenu"].='<li><a  class="submenu" href="' . Doo::conf()->APP_URL . 'categorias/' . $p['id'] . '/false">' . $p['nombre'] . '</a></li></ul>';
                    }
                    $this->data["htmlmenu"].='</li>';


                    $this->data["htmlmenu"].='</ul>';
                }

            } else {
                $this->data["htmlmenu"].= '<li><a  href="' . Doo::conf()->APP_URL . 'categorias/' . $codigo . '/false">' . $row["nombre"] . '</a>'
                        . '</li></li>';
                if (!$sub) {
                    $this->data["htmlmenu"].= '</li>';
                }
            }
        }
    }




    private function busqueda_avanzada() {
        $fabricantes = Doo::db()->find('Fabricantes', array("select" => "id,nombre", "where" => "estado=1", "asc" => "nombre"));
        $this->data['marca'] = $fabricantes;
        $categorias = Doo::db()->find('Categorias', array("select" => "id,nombre", "where" => "estado=1 and depende <> 0 ", "desc" => "nombre"));
        $this->data['categorias'] = $categorias;
        $precio = Doo::db()->find('Productos', array("select" => "id,precio_venta"));
        $this->data['precio_1'] = $precio;
        $precio2 = Doo::db()->find('Productos', array("select" => "id,precio_venta"));
        $this->data['precio_2'] = $precio2;
    }

    public function Contacto() {
        $this->configuracion();
        $this->buildMenu();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        $this->data['content'] = 'contactenos';
        $this->data['texto'] = '';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function send() {
        Doo::loadHelper('DooValidator');
        $validator = new DooValidator;
        $validator->checkMode = DooValidator:: CHECK_ALL_ONE;
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->configuracion();
        $this->buildMenu();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        //$param = $this->db()->find("Parametros", array("select" => "email", "limit" => 1));
        $mail->addTo('ventas4@compuworking.com.co');
        $mail->setSubject($_POST['asunto']);
        $mail->setBodyHtml($_POST['mensaje']);
        $mail->setFrom($_POST['email'], $_POST['nombre']);
        $mail->send();
        $this->data['content'] = 'confirmacion';
        $this->data["message"] = "El mensaje ha sido enviado exitosamente ..";
        $this->renderc('home', $this->data, true);
    }

    public function confirmacion() {
        $this->buildMenu();
        $this->data['content'] = 'confirmacion';
        $this->data["message"] = "Tu Registro ha sido Satisfactorio ..";
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function validar() {
        $usuario = $_POST["usuario"];
        $count = Doo::db()->query("select * from clientes where usuario = '$usuario'")->rowCount();
        if ($count > 0)
            echo true;
        else
            echo false;
    }

    private function buildOptionfotter() {
        $sql = "SELECT etiqueta,url,destino FROM direcciones WHERE isfotter='S' AND posicionf='1' ORDER BY orderfotter";
        $rs = Doo::db()->query($sql);
        $primeracolumna = $rs->fetchAll();

        $sql = "SELECT etiqueta,url,destino FROM direcciones WHERE isfotter='S' AND posicionf='2' ORDER BY orderfotter";
        $rs = Doo::db()->query($sql);
        $segundacolumna = $rs->fetchAll();

        $sql = "SELECT etiqueta,url,destino FROM direcciones WHERE isfotter='S' AND posicionf='3' ORDER BY orderfotter";
        $rs = Doo::db()->query($sql);
        $terceracolumna = $rs->fetchAll();
        $this->data["menufotter"] = '<div class="block">';
        foreach ($primeracolumna as $row):
            $url = $row['url'];
            $destino = $row['destino'];
            $etiqueta = $row['etiqueta'];
            $this->data["menufotter"].= '<div><a style="font-size: 13px; color:#fff" ' . ($destino == 'L' ? '' : 'target="_black"') . ' href="' . $url . '">' . mb_convert_encoding($etiqueta, 'ISO-8859-1', 'UTF-8') . '</a></div>';
        endforeach;
        $this->data["menufotter"].= '</div>';

        $this->data["menufotter"].= '<div class="block">';
        foreach ($segundacolumna as $row2):
            $url = $row2['url'];
            $destino = $row2['destino'];
            $etiqueta = $row2['etiqueta'];
            $this->data["menufotter"].= '<div><a style="font-size: 13px; color:#fff" ' . ($destino == 'L' ? '' : 'target="_black"') . ' href="' . $url . '">' . mb_convert_encoding($etiqueta, 'ISO-8859-1', 'UTF-8') . '</a></div>';
        endforeach;
        $this->data["menufotter"].= '</div>';

        $this->data["menufotter"].= '<div class="block">';
        foreach ($terceracolumna as $row3):
            $url = $row3['url'];
            $destino = $row3['destino'];
            $etiqueta = $row3['etiqueta'];
            $this->data["menufotter"].= '<div><a style="font-size: 13px; color:#fff" ' . ($destino == 'L' ? '' : 'target="_black"') . ' href="' . $url . '">' . mb_convert_encoding($etiqueta, 'ISO-8859-1', 'UTF-8') . '</a></div>';
        endforeach;
        $this->data["menufotter"].= '</div>';
    }

    public function getCategorias() {
        $id_cat = $this->params["id_cat"];
        $selected = [];
        $filterEspe = "";
        $selectedFeature = "";
        $principal = "";
        $id_marca="";
        $hasMarcas = "";
        $fab = '';
        if(isset($_POST["filterProducts"])){
            $selected = $_POST["filterProducts"];
            $index = 0;
            $totalElem = count($selected);
            $filterEspe = "AND (";
            foreach ($selected as $value) {
                $selectedFeature .= $index != 0 ? "," : "";
                $selectedFeature .= join(",", $value);
                $filterEspe .= "(";
                $idx = 0;
                foreach($value as $val){
                    $filterEspe .= $idx == 0 ? "" : "OR";
                    $filterEspe .= " FIND_IN_SET('$val',p.especificaciones) ";
                    $idx++;
                }
                $filterEspe .= ")";
                $filterEspe .= ($totalElem-1) == $index ? "" : " AND";
                $index++;
            }
            $filterEspe = "$filterEspe)";
        }
        if(isset($this->params["p"])){
            $principal = $this->params["p"];
        }      

        if (!$id_cat) {
            return Doo::conf()->APP_URL;
        } else {

            Doo::loadHelper('DooPager');

            if (isset($this->params["id_marca"])) {
                $id_marca = $this->params["id_marca"];
                $rst = Doo::db()->query("select count(*) as total FROM productos p 
                inner join categorias c  on c.id = p.id_categoria 
                WHERE  publicado='S' $filterEspe AND id_categoria=$id_cat AND id_fabricante=$id_marca || publicado='S' $filterEspe  AND  depende='$id_cat' AND id_fabricante='$id_marca' LIMIT 1");
                $hasMarcas = "/marcas";
                $fab = "/$id_marca";
            } else if($principal=="true") {

            $rst = Doo::db()->query("SELECT COUNT(*) AS total FROM productos p
            INNER JOIN categorias c ON (c.id=p.id_categoria) AND c.`depende`=$id_cat where p.publicado='S' $filterEspe LIMIT 1");
            
           // print_r($rst);

            }else{
                $rst = Doo::db()->query("select count(*) as total FROM productos p 
                inner join categorias c  on c.id = p.id_categoria 
                WHERE publicado='S' $filterEspe
                 AND id_categoria='$id_cat' LIMIT 1");
            }
            $t = $rst->fetch();
            if (count($t) > 0) {
                $total = $t["total"];
            } else {
                $total = 0;
            }
            if ($total == 0) {
                $total = 1;
            }
            $pager = new DooPager(Doo::conf()->APP_URL."categorias$hasMarcas/$id_cat/$principal$fab", $total, 12, 10);
            if (isset($this->params['number'])) {
                $pager->paginate(intval($this->params['number']."?id_cat=$id_cat&p=true"));
            } else {
                $pager->paginate(1);
            }

           
            if (isset($this->params["id_marca"]) ) {
                
                if($principal=="false"){
                $sql = "SELECT p.id,p.nombre,p.iva,p.precio_venta,p.imagen2,p.precio_promocion,p.caract 
                FROM productos p
                INNER JOIN categorias c ON (c.id = p.id_categoria)
                WHERE p.publicado = 'S' $filterEspe AND c.depende='$id_cat' AND p.id_fabricante='$id_marca' 
                ORDER BY p.id_fabricante,p.precio_venta DESC LIMIT " . $pager->limit;    
                $existe=Doo::db()->query($sql)->fetchAll();   
                    if(!$existe){
                        $sql = "SELECT id,nombre,iva,precio_venta,imagen2,precio_promocion,caract 
                        from productos p WHERE publicado='S' $filterEspe AND id_categoria=$id_cat AND id_fabricante=$id_marca 
                        ORDER BY id_fabricante,precio_venta DESC LIMIT " . $pager->limit;
                    }
                
                }
            } else if($principal=="true") {
                
                $sql = "SELECT p.id,p.nombre,p.iva,p.precio_venta,p.imagen2,p.precio_promocion,p.caract 
                FROM productos p
                INNER JOIN categorias c ON (c.`id`=p.id_categoria AND c.depende='$id_cat') 
                 WHERE p.publicado = 'S' $filterEspe
                ORDER BY p.id_fabricante,p.precio_venta DESC LIMIT " . $pager->limit;

                $existe=Doo::db()->query($sql)->fetchAll();
                if(!$existe){
                        $sql = "SELECT id,nombre,iva,precio_venta,imagen2,precio_promocion,caract from 
                 productos p WHERE publicado='S' $filterEspe  AND id_categoria=$id_cat 
                 ORDER BY id_fabricante,precio_venta DESC LIMIT " . $pager->limit;
                 
                }


            }else{
                
                 $sql = "SELECT id,nombre,iva,precio_venta,imagen2,precio_promocion,caract from 
                 productos p WHERE publicado='S' $filterEspe AND id_categoria=$id_cat 
                 ORDER BY id_fabricante,precio_venta DESC LIMIT " . $pager->limit;
                 
                 
            }

                // Contador de Marcas
            if($principal=='false'){
                $sqlmarcas = Doo::db()->query("SELECT DISTINCT c.id,c.nombre,COUNT(c.nombre) AS cantidad
                FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) 
                WHERE p.publicado='S' AND p.id_categoria='$id_cat' 
                GROUP BY c.id
                ORDER BY c.nombre")->fetchAll();
                if(!$sqlmarcas){
                $sqlmarcas = Doo::db()->query("SELECT DISTINCT c.id,c.nombre,COUNT(c.nombre) AS cantidad
                FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) 
                INNER JOIN categorias f ON (p.`id_categoria` = f.`id` AND f.depende='$id_cat' )
                WHERE p.publicado='S'  
                GROUP BY c.id
                ORDER BY c.nombre")->fetchAll();
                }

            }else  {
                
                $sqlmarcas = Doo::db()->query("SELECT DISTINCT c.id,c.nombre,COUNT(c.nombre) AS cantidad
                FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) 
                INNER JOIN categorias f ON (f.`id`=p.`id_categoria` AND f.depende='$id_cat') 
                WHERE p.publicado='S' 
                GROUP BY c.id
                ORDER BY c.nombre")->fetchAll();                
            }
            $sqldepende = Doo::db()->query("SELECT nombre,depende FROM categorias WHERE id = '$id_cat' AND estado = 1")->fetch();
            $ValidarHijos=Doo::db()->query("select count(id) as cantidad from categorias where depende='$id_cat' AND estado = 1")->fetch();
            if($principal=='false'){                
                if($ValidarHijos['cantidad']>=1){
                    $depende = $id_cat;
                }else{
                    $depende = $sqldepende["depende"];  
                }                           
            }else{
                $depende=$id_cat;
            }        
            $caracteristicas = Doo::db()->query("SELECT car.id,car.nombre FROM categorias ca,catacteristicas car
            WHERE ca.id='$depende' AND FIND_IN_SET(ca.id, car.id_categoria) AND  NOT FIND_IN_SET('$id_cat',excluir_in) GROUP BY car.id;")->fetchAll();
           $i = 0;
           foreach ($caracteristicas as $value) {
                $caracteristicas[$i]["especificaciones"] = Doo::db()->query("SELECT id,nombre FROM `especificacion` WHERE id_caracteristica = '$value[id]' order by nombre + 0 asc")->fetchAll();
                $i++;
            }
            $caracteristicas = $this->calculateFilters($caracteristicas,$principal,$id_cat,$id_marca, $filterEspe);
            $sqlcategorias = Doo::db()->query("SELECT c.id,c.nombre,c.depende ,(SELECT COUNT(t.id) FROM categorias t WHERE depende=c.id)AS cantidad
            FROM categorias c WHERE depende = '$depende' AND c.estado=1
            GROUP BY(id) order by orden")->fetchAll();

            $sqlcategoriafondo = Doo::db()->query("SELECT imagen_fondo FROM categorias WHERE id =(SELECT `depende` FROM categorias WHERE id=$id_cat LIMIT 1)")->fetch();
            if ($sqlcategoriafondo["imagen_fondo"] == '') {

                $imagen = Doo::db()->query("SELECT imagen_fondo FROM categorias 
                                    WHERE id=(SELECT `depende` FROM categorias WHERE id=(SELECT `depende` FROM categorias 
                                    WHERE id=$id_cat LIMIT 1) LIMIT 1) AND estado=1")->fetch();
                $categoriafondo = $imagen["imagen_fondo"];
            } else {
                $categoriafondo = $sqlcategoriafondo["imagen_fondo"];
            }
            $this->data['ValidarHijos']=$ValidarHijos['cantidad'];
         
            

            $s = Doo::db()->query($sql)->fetchAll();
            $this->configuracion();
            $this->buildMenu();
            $this->buildMenuH();
            $this->buildMenuV();

            $this->Aliados();
            $this->ProductosPromocion();
            $this->busqueda_avanzada();

            $nom_cag1 = Doo::db()->query("SELECT nombre,depende2 FROM categorias WHERE id=?", array($id_cat))->fetch();

            $nom_cag = $nom_cag1["nombre"];
            $depende2 =  $nom_cag1["depende2"];
            $this->data['texto'] = "";
           // $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" title="Pagina de inicio">Inicio</a></li><li class="active"><a href="' . Doo::conf()->APP_URL . 'categorias?id_cat=' . $id_cat . '" class="previous" title="' . $nom_cag . '">' . $nom_cag . '</a></li>';
           
           $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" title="Pagina de inicio">Inicio</a></li><li class="active"><a  class="previous" title="' . $nom_cag . '">' . $nom_cag . '</a></li>';
           
            $_SESSION["stak_url"] = $ruta;
            $this->data['stak_url'] = $ruta;
            $this->data["productos"] = $s;
            $this->data["id_categoria"] = $id_cat;
            $this->data["nombre_categoria"] = $nom_cag;
            $princ=Doo::db()->query("SELECT principal FROM categorias WHERE id = (SELECT depende FROM categorias WHERE id = '$id_cat')")->fetch();
            if($ValidarHijos['cantidad']>1 and $princ['principal']=='S'){
               $this->data['principal']='false';
            }elseif($ValidarHijos['cantidad']==0 and $princ['principal']=='N'){
                $this->data['principal']='false';
            }else{
                $this->data['principal']='true';
            }
            $this->data['principal'] = $principal;
            $this->data["selectedFeature"] = $selectedFeature;
            $this->data["caracteristicas"] = $caracteristicas;
            $this->data["depende2"] = $depende2;
            $this->data['marcas'] = $sqlmarcas;
            $this->data['categorias'] = $sqlcategorias;
            $this->data['fondo_categoria'] = $categoriafondo;
            $this->data['pager'] = $pager->output;
            $this->data['content'] = 'productos';
            $this->data['rootUrl'] = Doo::conf()->APP_URL;
            $this->renderc('home', $this->data, true);
        }
    }
    
    
    public function calculateFilters($caracteristicas, $principal, $id_cat, $id_marca, $filtro){
        $sql = "";
        $i = 0;
        $filterEspe = "";
        foreach ($caracteristicas as $value) {
            $j=0;
            foreach ($value["especificaciones"] as $especificacion) {
                //$filterEspe = "AND FIND_IN_SET('$especificacion[id]',p.especificaciones) $filtro";
                $filterEspe = "AND FIND_IN_SET('$especificacion[id]',p.especificaciones) ";
                $sql = "";
                if (isset($this->params["id_marca"]) ) {                
                    if($principal=="false"){
                    $sql = "SELECT COUNT(p.id) AS cantidad 
                    FROM productos p
                    INNER JOIN categorias c ON (c.id = p.id_categoria)
                    WHERE p.publicado = 'S' $filterEspe AND c.depende='$id_cat' AND p.id_fabricante='$id_marca' 
                    ORDER BY p.precio_venta ASC ";    
                    $existe=Doo::db()->query($sql)->fetchAll();   
                        if(!$existe){
                            $sql = "SELECT COUNT(p.id) AS cantidad
                            from productos p WHERE publicado='S' $filterEspe AND id_categoria=$id_cat AND id_fabricante=$id_marca 
                            ORDER BY precio_venta ASC ";
                        }
                    
                    }
                } else if($principal=="true") {            
                    $sql = "SELECT COUNT(p.id) AS cantidad
                    FROM productos p
                    INNER JOIN categorias c ON (c.`id`=p.id_categoria AND c.depende='$id_cat') 
                    WHERE p.publicado = 'S' $filterEspe ORDER BY p.precio_venta ASC ";

                    $existe=Doo::db()->query($sql)->fetchAll();
                    if(!$existe){
                            $sql = "SELECT COUNT(p.id) AS cantidad from 
                    productos p WHERE publicado='S' $filterEspe  AND id_categoria=$id_cat 
                    ORDER BY precio_venta ASC ";
                    
                    }
                }else{                
                    $sql = "SELECT COUNT(p.id) AS cantidad from 
                    productos p WHERE publicado='S' $filterEspe AND id_categoria=$id_cat 
                    ORDER BY precio_venta ASC ";             
                }
                $cantidad = Doo::db()->query($sql)->fetch();
                $caracteristicas[$i]["especificaciones"][$j]["cantidad"] = $cantidad["cantidad"];
                $j++;
            }
            $i++;
        }
      return $caracteristicas;
    }
    
    public function imprimirProductos(){
        Doo::loadClass("pdf/PDF_ImageAlpha");
        Doo::loadClass("reportes/ImprimirProductos");
        $id_cat = $this->params["id_cat"];
        $selected = [];
        $filterEspe = "";
        $selectedFeature = "";
        $principal = "";
        if(isset($_POST["filterProducts"])){
            $selected = $_POST["filterProducts"];
            $index = 0;
            $totalElem = count($selected);
            $filterEspe = "AND (";
            foreach ($selected as $value) {
                $selectedFeature .= $index != 0 ? "," : "";
                $selectedFeature .= join(",", $value);
                $filterEspe .= "(";
                $idx = 0;
                foreach($value as $val){
                    $filterEspe .= $idx == 0 ? "" : "OR";
                    $filterEspe .= " FIND_IN_SET('$val',p.especificaciones) ";
                    $idx++;
                }
                $filterEspe .= ")";
                $filterEspe .= ($totalElem-1) == $index ? "" : " AND";
                $index++;
            }
            $filterEspe = "$filterEspe)";
        }
        if(isset($this->params["p"])){
            $principal = $this->params["p"];
        }      
     
        if (!$id_cat) {
            return Doo::conf()->APP_URL;
        } else {     
            Doo::loadHelper('DooPager');     
            if (isset($this->params["id_marca"])) {
                $id_marca = $this->params["id_marca"];
                $rst = Doo::db()->query("select count(*) as total FROM productos p WHERE  publicado='S' $filterEspe AND id_categoria=$id_cat AND id_fabricante=$id_marca", array("limit" => 1));
            }else if($principal=="true") {
                $rst = Doo::db()->query("SELECT COUNT(*) AS total FROM productos p
                INNER JOIN categorias c ON (c.id=p.id_categoria) AND c.`depende`=$id_cat where  p.publicado='S' $filterEspe", array("limit" => 1));
                }else{
                    $rst = Doo::db()->query("select count(*) as total FROM productos p WHERE publicado='S' $filterEspe
                    AND id_categoria=$id_cat", array("limit" => 1));
                 }     
                $t = $rst->fetch();
                if (count($t) > 0) {
                    $total = $t["total"];
                } else {
                    $total = 0;
                }
                if ($total == 0) {
                    $total = 1;
                }
                $pager = new DooPager(Doo::conf()->APP_URL."categorias/$id_cat/$principal", $total, 12, 10);
                if (isset($this->params['number'])) {
                    $pager->paginate(intval($this->params['number']."?id_cat=$id_cat&p=true"));
                } else {
                    $pager->paginate(1);
                }
     
                
                if (isset($this->params["id_marca"]) ) {     
                    if($principal=="false"){    
                    $sql = "SELECT p.id,p.nombre,p.iva,p.precio_venta,p.imagen2,p.precio_promocion,p.caract 
                            FROM productos p
                            INNER JOIN categorias c ON (c.id = p.id_categoria)
                            WHERE p.publicado = 'S' AND c.depende='$id_cat' AND p.id_fabricante='$id_marca' $filterEspe
                            ORDER BY p.id_fabricante,p.precio_venta DESC LIMIT " . $pager->limit;    
                    $existe=Doo::db()->query($sql)->fetchAll();   
                        if(!$existe){
                            $sql = "SELECT id,nombre,iva,precio_venta,imagen2,precio_promocion,caract 
                            from productos WHERE publicado='S' AND id_categoria=$id_cat AND id_fabricante=$id_marca $filterEspe
                            ORDER BY id_fabricante,precio_venta DESC LIMIT " . $pager->limit;
                        }
                    
                    }
                } else if($principal=="true") {                     
                    $sql = "SELECT p.id,p.nombre,p.iva,p.precio_venta,p.imagen2,p.precio_promocion,p.caract 
                    FROM productos p
                    INNER JOIN categorias c ON (c.`id`=p.id_categoria AND c.depende='$id_cat') 
                    WHERE p.publicado = 'S' $filterEspe
                    ORDER BY p.id_fabricante,p.precio_venta DESC LIMIT " . $pager->limit;
                    $existe=Doo::db()->query($sql)->fetchAll();
                    if(!$existe){
                        $sql =" SELECT id,nombre,iva,precio_venta,imagen2,precio_promocion,caract from 
                                productos WHERE publicado='S' $filterEspe AND id_categoria=$id_cat 
                                ORDER BY id_fabricante,precio_venta DESC LIMIT " . $pager->limit;
                    }  
                }else{
                    $sql = "SELECT id,nombre,iva,precio_venta,imagen2,precio_promocion,caract from 
                    productos p WHERE publicado='S' $filterEspe AND id_categoria=$id_cat 
                    ORDER BY id_fabricante,precio_venta DESC LIMIT " . $pager->limit;
                }    
                // Contador de Marcas
                if($principal=='false'){                    
                    $sqlmarcas = Doo::db()->query("SELECT DISTINCT c.id,c.nombre,COUNT(c.nombre) AS cantidad
                    FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) 
                    WHERE p.publicado='S' $filterEspe AND p.id_categoria='$id_cat' 
                    GROUP BY c.id
                    ORDER BY c.nombre")->fetchAll();
                    if(!$sqlmarcas){
                        $sqlmarcas =Doo::db()->query("SELECT DISTINCT c.id,c.nombre,COUNT(c.nombre) AS cantidad
                                    FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) 
                                    INNER JOIN categorias f ON (p.`id_categoria` = f.`id` AND f.depende='$id_cat' )
                                    WHERE p.publicado='S' $filterEspe GROUP BY c.id ORDER BY c.nombre")->fetchAll();
                    }
                 }else  {                     
                    $sqlmarcas = Doo::db()->query("SELECT DISTINCT c.id,c.nombre,COUNT(c.nombre) AS cantidad
                    FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) 
                    INNER JOIN categorias f ON (f.`id`=p.`id_categoria` AND f.depende='$id_cat') 
                    WHERE p.publicado='S' $filterEspe GROUP BY c.id ORDER BY c.nombre")->fetchAll();                
                 }
                 $sqldepende = Doo::db()->query("SELECT nombre,depende FROM categorias WHERE id = '$id_cat' AND estado = 1")->fetch();
                 $ValidarHijos=Doo::db()->query("select count(id) as cantidad from categorias where depende='$id_cat' AND estado = 1")->fetch();
                 if($principal=='false'){                
                     if($ValidarHijos['cantidad']>=1){
                         $depende = $id_cat;
                     }else{
                         $depende = $sqldepende["depende"];  
                     }                           
                 }else{
                     $depende=$id_cat;
                 }        
                 $sqlcategorias = Doo::db()->query("SELECT c.id,c.nombre,c.depende ,(SELECT COUNT(t.id) FROM categorias t WHERE depende=c.id)AS cantidad
                 FROM categorias c WHERE depende = '$depende' AND c.estado=1
                 GROUP BY(id)")->fetchAll();
     
                 $sqlcategoriafondo = Doo::db()->query("SELECT imagen_fondo FROM categorias WHERE id =(SELECT `depende` FROM categorias WHERE id=$id_cat LIMIT 1)")->fetch();
                 if ($sqlcategoriafondo["imagen_fondo"] == '') {
     
                     $imagen = Doo::db()->query("SELECT imagen_fondo FROM categorias 
                                         WHERE id=(SELECT `depende` FROM categorias WHERE id=(SELECT `depende` FROM categorias 
                                         WHERE id=$id_cat LIMIT 1) LIMIT 1) AND estado=1")->fetch();
                     $categoriafondo = $imagen["imagen_fondo"];
                 } else {
                     $categoriafondo = $sqlcategoriafondo["imagen_fondo"];
                 }
                 $this->data['ValidarHijos']=$ValidarHijos['cantidad'];
                 $s = Doo::db()->query($sql)->fetchAll();     
                 $nom_cag1 = Doo::db()->query("SELECT nombre,depende2 FROM categorias WHERE id=?", array($id_cat))->fetch();
                 $nom_cag = $nom_cag1["nombre"];
                 $depende2 =  $nom_cag1["depende2"];
                // $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" title="Pagina de inicio">Inicio</a></li><li class="active"><a href="' . Doo::conf()->APP_URL . 'categorias?id_cat=' . $id_cat . '" class="previous" title="' . $nom_cag . '">' . $nom_cag . '</a></li>';
                $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" title="Pagina de inicio">Inicio</a></li><li class="active"><a  class="previous" title="' . $nom_cag . '">' . $nom_cag . '</a></li>';
                
            $this->data["productos"] = $s;
            $this->data["nombre_categoria"] = $nom_cag;
            $princ=Doo::db()->query("SELECT principal FROM categorias WHERE id = (SELECT depende FROM categorias WHERE id = '$id_cat')")->fetch();
            if($ValidarHijos['cantidad']>1 and $princ['principal']=='S'){
                $this->data['principal']='false';
            }elseif($ValidarHijos['cantidad']==0 and $princ['principal']=='N'){
                $this->data['principal']='false';
            }else{
                $this->data['principal']='true';
            }                
            $this->data["depende2"] = $depende2;
            $this->data['marcas'] = $sqlmarcas;
            $this->data['categorias'] = $sqlcategorias;
            $this->data['fondo_categoria'] = $categoriafondo;
            $this->data['pager'] = $pager->output;
            $this->data['content'] = 'productos';
            $this->data['rootUrl'] = Doo::conf()->APP_URL;
            $this->data['rootUrl'] = Doo::conf()->APP_URL;
            $this->renderc("imprimir_productos", $this->data, true);
            /*$pdf = new ImprimirProductos();
            $pdf->AliasNbPages();
            $pdf->AddPage();
            $pdf->body($this->data);
            $pdf->Output();*/
        }
    }

    public function getCategoriasPrincipal() {
        Doo::loadHelper('DooPager');
        $id = $this->params['id'];
        $rst = Doo::db()->query("SELECT COUNT(*) AS total FROM productos p INNER JOIN categorias c ON (p.id_categoria = c.id) WHERE c.depende=$id AND p.publicado='S' ", array("limit" => 1));
        $t = $rst->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        }
        if ($total == 0) {
            $total = 1;
        }
        $pager = new DooPager("#", $total, 12, 10);
        if (isset($this->params['number'])) {
            $pager->paginate(intval($this->params['number']));
        } else {
            $pager->paginate(1);
        }

        $sql = "SELECT p.id,p.nombre,p.caract,p.precio_venta,p.precio_promocion,p.imagen2 "
                . "FROM productos p  INNER JOIN categorias c ON (p.id_categoria = c.id)"
                . " WHERE p.publicado='S' AND  c.depende=$id "
                . "ORDER BY p.id_fabricante,p.precio_venta DESC LIMIT " . $pager->limit;
        $s = Doo::db()->query($sql)->fetchAll();

        $this->configuracion();

        $sqlmarcas = Doo::db()->query("SELECT DISTINCT c.id,c.nombre,COUNT(c.nombre) AS cantidad
        FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) 
        INNER JOIN categorias ctg 
        ON (p.`id_categoria` = ctg.`id`)
        WHERE p.publicado='S' AND ctg.`depende` = $id
        GROUP BY c.id
        ORDER BY c.nombre")->fetchAll();

        $sqlcategorias = Doo::db()->query("SELECT id,nombre,depende FROM categorias WHERE depende = '$id'")->fetchAll();

        $sqlcategoriafondo = Doo::db()->query("SELECT imagen_fondo FROM categorias WHERE id = $id")->fetchAll();
        $categoriafondo = $sqlcategoriafondo[0]["imagen_fondo"];

        $this->buildMenu();
        $this->buildMenuH();
        $this->buildMenuV();
        $this->busqueda_avanzada();
        $nom_cag1 = Doo::db()->query("SELECT nombre FROM categorias c WHERE c.id=?", array($id))->fetch();

        $nom_cag = $nom_cag1["nombre"];
        $this->data['texto'] = "";
        $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" class="previous" title="Pagina de inicio">Inicio</a></li><li><a href="' . Doo::conf()->APP_URL . 'categoria/' . $id . '" class="previous" title="' . $nom_cag . '">' . $nom_cag . '</a></li>';
        $_SESSION["stak_url"] = $ruta;
        $this->data['stak_url'] = $ruta;
        $this->data["productos"] = $s;
        $this->data["id_categoria"] = $id;
        $this->data["nombre_categoria"] = $nom_cag;
        $this->data['marcas'] = $sqlmarcas;
        $this->data['categorias'] = $sqlcategorias;
        $this->data['fondo_categoria'] = $categoriafondo;
        $this->data['pager'] = $pager->output;
        $this->data['content'] = 'productos';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function getFabricantes() {
        Doo::loadHelper('DooPager');
        $id = $this->params['id'];
        $rst = Doo::db()->query("select count(*) as total FROM productos WHERE publicado='S'  AND id_fabricante=$id  ", array("limit" => 1));
        $t = $rst->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        }
        if ($total == 0) {
            $total = 1;
        }
        $pager = new DooPager("#", $total, 12, 10);
        if (isset($this->params['number'])) {
            $pager->paginate(intval($this->params['number']));
        } else {
            $pager->paginate(1);
        }

        $sql = "SELECT id,nombre,precio_venta,imagen2,iva,precio_promocion,caract from productos WHERE publicado='S'  AND id_fabricante=$id LIMIT " . $pager->limit;
        $s = Doo::db()->query($sql)->fetchAll();



        $sqlcategorias = Doo::db()->query("SELECT DISTINCT c.id,c.nombre
            FROM productos p
            INNER JOIN `categorias` c
            ON (p.`id_categoria`=c.`id`)
            WHERE p.publicado='S' AND p.id_fabricante=$id AND c.`depende`=0 ")->fetchAll();

        $sqlmarcas = Doo::db()->query("SELECT DISTINCT m.id,m.nombre,COUNT(m.nombre) AS cantidad
            FROM productos p
            INNER JOIN `fabricantes` m
            ON (p.`id_fabricante`=m.`id`)
            WHERE p.publicado='S' AND p.id_fabricante=$id AND CURDATE() <= p.fecha_vencimiento
            GROUP BY m.id")->fetchAll();

        $this->configuracion();
        $this->buildMenu();

        $nom_fab1 = Doo::db()->query("SELECT nombre FROM fabricantes WHERE id=?", array($id))->fetch();
        $nom_fab = $nom_fab1["nombre"];

        $this->data['texto'] = "";
        $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" title="Pagina de inicio">Inicio</a></li><li class="active"><a href="' . Doo::conf()->APP_URL . 'fabricante/' . $id . '" class="previous" title="' . $nom_fab . '">' . $nom_fab . '</a></li>';
        $_SESSION["stak_url"] = $ruta;
        $this->data['stak_url'] = $ruta;
        $this->data["productos"] = $s;
        $this->data["id_categoria"] = $id;
        $this->data["nombre_categoria"] = $nom_fab;
        $this->data['fondo_categoria'] = "";
        $this->data['marcas'] = $sqlmarcas;
        $this->data['categorias'] = $sqlcategorias;
        $this->data['pager'] = $pager->output;
        $this->data['content'] = 'productos';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function getFabricantesAndCategoria() {
        Doo::loadHelper('DooPager');
        $id_fabricante = $this->params['fabricante'];
        $id_categoria = $this->params['categoria'];
        $rst = Doo::db()->query("SELECT count(*) AS total FROM productos WHERE publicado='S' AND id_fabricante=$id_fabricante AND id_categoria=$id_categoria ", array("limit" => 1));
        $t = $rst->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        }
        if ($total == 0) {
            $total = 1;
        }
        $pager = new DooPager("#", $total, 12, 10);
        if (isset($this->params['number'])) {
            $pager->paginate(intval($this->params['number']));
        } else {
            $pager->paginate(1);
        }

        $sql = "SELECT id,nombre,precio_venta,imagen2,precio_promocion,caract from productos WHERE publicado='S' AND id_fabricante=$id_fabricante AND id_categoria=$id_categoria LIMIT " . $pager->limit;
        $s = Doo::db()->query($sql)->fetchAll();
        $this->configuracion();
        $this->buildMenu();
        $this->buildMenuH();
        $this->buildMenuV();
        $this->Banner();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        $nom_fab1 = Doo::db()->query("SELECT nombre FROM fabricantes WHERE id=?", array($id_fabricante))->fetch();
        $nom_fab = $nom_fab1["nombre"];

        $nom_cag1 = Doo::db()->query("SELECT nombre FROM categorias WHERE id=?", array($id_categoria))->fetch();
        $nom_cag = $nom_cag1["nombre"];
        $this->data['texto'] = "";
        $ruta = '<a href="' . Doo::conf()->APP_URL . '" class="previous" title="Pagina de inicio">Inicio</a><a href="' . Doo::conf()->APP_URL . 'fabricante/' . $id_fabricante . '" class="previous" title="' . $nom_fab . '">' . $nom_fab . '</a><a href="' . Doo::conf()->APP_URL . 'busqueda/' . $id_fabricante . '/' . $id_categoria . '" class="previous" title="' . $nom_cag . '">' . $nom_cag . '</a>';
        $_SESSION["stak_url"] = $ruta;
        $this->data['stak_url'] = $ruta;
        $this->data["productos"] = $s;
        $this->data["id_categoria"] = $id_categoria;
        $this->data['pager'] = $pager->output;
        $this->data['content'] = 'inicio';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function getCategoryAjax() {
        if (isset($_POST["marca"])) {
            $marca = $_POST["marca"];
        } else {
            $marca = "";
        }
        if (isset($_POST["categoria"])) {
            $categoria = $_POST["categoria"];
        } else {
            $categoria = "";
        }
        if (isset($_POST["texto"])) {
            $texto = $_POST["texto"];
        } else {
            $texto = "";
        }
        $where = " publicado='S' ";
        if ($marca != "") {
            $where.=" AND id_fabricante=$marca ";
        }
        if ($categoria != "") {
            $where.=" AND id_categoria=$categoria ";
        }
        if ($texto != "") {
            $where.=" AND ( nombre LIKE '%$texto%' OR caract LIKE '%$texto%' )";
        }
        $tipo = Doo::db()->query("SELECT depende FROM categorias WHERE id=$categoria")->fetch();


        if ($tipo["depende"] == 0) {
            $t = Doo::db()->query("SELECT COUNT(*) AS total FROM productos p INNER JOIN categorias c ON (p.id_categoria = c.id) WHERE c.depende=$categoria AND p.publicado='S'")->fetch();
        } else {
            $t = Doo::db()->query("select count(*) as total FROM productos where " . $where)->fetch();
        }

        $total = $t["total"];
        if ($total == 0) {
            $total = 1;
        }
        Doo::loadHelper('DooPager');
        $pager = new DooPager("#", $total, 12, 10);
        if (isset($_POST["page"])) {
            $pager->paginate(intval($_POST["page"]));
        } else {
            $pager->paginate(1);
        }

        if ($tipo["depende"] == 0) {
            $s = Doo::db()->query("SELECT p.id,p.iva,p.nombre,p.caract,p.precio_venta,p.precio_promocion,p.imagen2 FROM productos p  INNER JOIN categorias c ON (p.id_categoria = c.id)  WHERE p.publicado='S' AND c.depende=$categoria ORDER BY p.id_fabricante,p.precio_venta DESC LIMIT $pager->limit")->fetchAll();
        } else {
            $s = Doo::db()->query("SELECT nombre,iva,precio_venta,caract,precio_promocion,id,imagen2 FROM productos WHERE " . $where . " ORDER BY id_fabricante,precio_venta DESC LIMIT $pager->limit")->fetchAll();
        }
        $this->data['texto'] = "";
        $this->data['id_categoria'] = $categoria;
        $this->data['content'] = 'itemsbusqueda';
        $this->data['productos'] = $s;
        $this->data['pager'] = $pager->output;
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('itemsbusqueda', $this->data, true);
    }

    public function getGalerias() {
        $galeri = Doo::db()->find('Galerias', array("select" => "id,nombre,foto,id_ctgaleria", "where" => "estado=1", "desc" => "nombre"));
        $this->data['galeri'] = $galeri;
        $this->buildMenu();
        $this->Menu();
        $this->CargarArray();
        $this->NoticiasyAseguradoras();
        $this->buildOptionfotter();
        $this->data['content'] = 'galerias';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function getLista_precio() {
        $catg = Doo::db()->find('Categorias', array("select" => "id,nombre", "where" => "depende='0' and estado= 1", "ORDER" => "orden", "asc" => "orden"));
        $this->data['categoriaslis'] = $catg;
        $this->buildMenu();
        $this->buildMenuH();
        $this->busqueda_avanzada();
        $this->configuracion();
        $this->data['content'] = 'lista_precio';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function ViewCart() {
        $this->configuracion();
        $this->buildMenu();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
      
        $departamentos = Doo::db()->query("SELECT * FROM departamentos ")->fetchAll();
        
        $this->data['departamentos'] = $departamentos;
        $this->data['texto'] = '';
        $this->data['content'] = 'checkout';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function AddCart() {
       
        if (isset($_SESSION["carrito"])) {
            $canasta = unserialize($_SESSION["carrito"]);
        } else {
            $canasta = array();
        }
        
        $id = $_POST["id"];
        $existe = false;
        foreach ($canasta as $producto) {
            if ($producto["id"] == $id) {
                $existe = true;
            }
        }
        if ($existe) {
            $np = $canasta[$id];
            if (isset($_POST["cantidad_add"])) {
                $np["cantidad"] = $np["cantidad"] + $_POST["cantidad_add"];
            } else {
                $np["cantidad"] = $np["cantidad"] + 1;
            }
            $canasta[$id] = $np;
        } else {
            $p = Doo::db()->find("Productos", array("select" => "nombre,codigo,caract,precio_venta,precio_promocion,id,imagen2,iva", 'limit' => 1, "where" => " id=? ", "param" => array($id)));
//            $valor_tomar = ($p->iva >0 ? $p->precio_venta=($p->precio_venta+($p->precio_venta*$p->iva)) : $p->precio_venta ) ;
//            "valor_total"=>$valor_tomar,
       
            $canasta[$id] = array("nombre" => $p->nombre,"caract"=>$p->caract , "codigo" => $p->codigo, "valor" => $p->precio_venta, "valor2" => $p->precio_promocion, "cantidad" => $_POST["cantidad_add"], "id" => $p->id, "id_cotizacion" => "", "imagen2" => $p->imagen2, "iva" => $p->iva);
            
//           
//var_dump($canasta);
//            exit();
        }
        $_SESSION["carrito"] = serialize($canasta);
        
       // echo count($canasta);
    }

    public function delete_product() {
        $sql = "SELECT id,nombre,fondo_pagina,footer_1,footer_2,footer_3,footer_4,title_fot_1,title_fot_2,title_fot_3,title_fot_4 from plantilla where estado=1";
        $rs = Doo::db()->query($sql)->fetch();
        $this->data['planti'] = $rs;
        $id = $this->params['id'];
        $a = unserialize($_SESSION["carrito"]);
        unset($a[$id]);
        $_SESSION["carrito"] = serialize($a);
        $this->ViewCart();
    }

    function change_cnt_producto() {
        $this->configuracion();
        if (isset($_SESSION["carrito"])) {
            $array = unserialize($_SESSION["carrito"]);
        }
        $envio = $_POST['envio'];
        $id = $_POST['index'];
        $item = $array[$id];
        $item['cantidad'] = $_POST['cantidad'];
        $item['valor'] = $_POST['valor'];
        $item['valor2'] = $_POST['valor'];
        $array[$id] = $item;

//        var_dump( $array[$id]);
        $_SESSION["carrito"] = serialize($array);
        //var_dump($_SESSION["carrito"]);
        echo number_format($this->Totalizar($array,$envio), 0);
    }

    public function calculate(){
        $valor = 0;
        $municipio = $_POST["municipio"];
        $departamento = $_POST["departamento"];
        $sumatorias = 0;
        if (isset($_SESSION["carrito"])) {
            $carro = unserialize($_SESSION["carrito"]);
            foreach ($carro as $c) {
                if ($c["valor2"] > 0) {
                    $valort = $c["valor2"];
                }else{
                    $valort = $c["valor"];
                }
                if (isset($_SESSION["login_cliente"])) {
                    $login = $_SESSION['login_cliente'];
                    if ($login->rol != "1") {
                        if ($c["iva"] > 0) {
                            $valor = (($valort * $c["iva"]) + $valort);
                        } else {
                            $valor = $valort;
                        }
                    }else{
                        $valor = $valort; 
                    }
                }else{
                    if ($c["iva"] > 0) {
                        $valor = (($valort * $c["iva"]) + $valort);
                    } else {
                        $valor = $valort;
                    } 
                }
                $sumatorias = $sumatorias + ($valor * $c["cantidad"]);
            }
        }
       
        $totalp = 0;
        $costo = $this->calculateCostos($departamento,$municipio);
        $totalp=$costo+$sumatorias;
        return array(
            "total" => $totalp,
            "envio"=> $costo
            );
    }
    
     public function calculatePrecio(){
        $values = $this->calculate();    
       
        echo json_encode(array(
            "total" =>number_format( $values["total"]),
            "envio"=> $values["envio"]
            ));
    } 
    
    public function calculateCostos($departamento,$municipio){
        $costo = 0;
        if($departamento == 13){
            if($municipio==171){
                $costo = 10000;
            }else{
                $costo = 35000;
            }
        }else{
            $costo = 35000;
        }
        return $costo;
    }

    public function insert() {
        $regis = true;
        if (isset($_SESSION["itement"])) {
            $array = unserialize($_SESSION["itement"]);
            foreach ($array as $a) {
                if ($a["id_catig"] == $_POST["select2"] && $a["id_fab"] == $_POST["select3"]) {
                    $regis = false;
                }
            }
        } else {
            $array = array();
        }
        if ($regis) {
            $id_categoria = $_POST["select3"];
            $id_categoria2 = $_POST["select2"];
            $id_marca = $_POST["select4"];
            $id_marca2 =  $_POST["select3"];
            
            if ($id_categoria != 0 && $id_marca !='0') {
                if ($id_marca == "all") {
                    $nom_categ = Doo::db()->query("SELECT id,nombre FROM categorias WHERE id=$id_categoria")->fetch();
                    $n = array("id_catig" => $_POST["select3"], "id_fab" => $_POST["select4"], "nom_categ" => $nom_categ["nombre"], "nom_fabri" => "Todos", "idcateg" => $nom_categ["id"], "idfabr" => "all");
                    $array[] = $n;
                } else {
                    $nom_fabri = Doo::db()->query("SELECT id,nombre FROM fabricantes WHERE id=$id_marca")->fetch();
                    $nom_categ = Doo::db()->query("SELECT id,nombre FROM categorias WHERE id=$id_categoria")->fetch();
                    $n = array("id_catig" => $_POST["select3"], "id_fab" => $_POST["select4"], "nom_categ" => $nom_categ["nombre"], "nom_fabri" => $nom_fabri["nombre"], "idcateg" => $nom_categ["id"], "idfabr" => $nom_fabri["id"]);
                    $array[] = $n;
                }
            }else if( $id_categoria2!=0 && $id_marca==0){
                
                if ($id_marca2 == 0) {
                    $nom_categ = Doo::db()->query("SELECT id,nombre FROM categorias WHERE id=$id_categoria2")->fetch();
                    $n = array("id_catig" => $_POST["select2"], "id_fab" => $_POST["select3"], "nom_categ" => $nom_categ["nombre"], "nom_fabri" => "Todos", "idcateg" => $nom_categ["id"], "idfabr" => "all");
                    $array[] = $n;
                }else{
                    $nom_fabri = Doo::db()->query("SELECT id,nombre FROM fabricantes WHERE id=$id_marca2")->fetch();
                    $nom_categ = Doo::db()->query("SELECT id,nombre FROM categorias WHERE id=$id_categoria2")->fetch();
                    $n = array("id_catig" => $_POST["select2"], "id_fab" => $_POST["select3"], "nom_categ" => $nom_categ["nombre"], "nom_fabri" => $nom_fabri["nombre"], "idcateg" => $nom_categ["id"], "idfabr" => $nom_fabri["id"]);
                    $array[] = $n;
                }
                 
            }else{
               $nom_categ = Doo::db()->query("SELECT id,nombre FROM categorias WHERE id=$id_categoria2")->fetch();
               $n = array("id_catig" => $_POST["select2"], "id_fab" => $_POST["select2"], "nom_categ" => $nom_categ["nombre"], "nom_fabri" => "Todos", "idcateg" => $nom_categ["id"], "idfabr" => "all");
               $array[] = $n; 
            }
        }

        $_SESSION["itement"] = serialize($array);
        $this->data['entdasarray'] = $array;
        $this->renderc("items", $this->data, true);
    }

    public function load() {
        $array = array();
        if (isset($_SESSION["itement"])) {
            $array = unserialize($_SESSION["itement"]);
        }
        $this->data['entdasarray'] = $array;
        $this->renderc("items", $this->data, true);
    }

    public function loadcatg() {
        $id = $_POST["id_categoria"];
        $out = "";
        if ($id != "") {
            $sql = "SELECT id,nombre FROM categorias WHERE depende='$id' and estado=1 ORDER BY nombre";
            $rs = Doo::db()->query($sql)->fetchAll();
            if($rs){
                $out.="<option value=\"0\">Seleccione</option>";
                foreach ($rs as $r) {
                $id_c = $r["id"];
                $nom_c = $r["nombre"];
                $out.="<option value=\"$id_c\">$nom_c</option>";
                }
            }
            
        } else {
            $out.="<option value=\"\">No hay categorias</option>";
        }
        echo $out;
    }
    
    public function loadcatg2() {
        $id = $_POST["id_categoria"];
        $out = "";
        if ($id != "") {
            $sql = "SELECT id,nombre FROM categorias WHERE depende='$id' and estado=1 ORDER BY nombre";
            $rs = Doo::db()->query($sql)->fetchAll();
            if($rs==null){
               $sql = "SELECT DISTINCT f.id,f.nombre FROM productos p INNER JOIN fabricantes f ON(f.id=p.id_fabricante) WHERE p.publicado='S' AND p.id_categoria='$id' and estado=1 ORDER BY f.nombre";
               $rs = Doo::db()->query($sql)->fetchAll();
            }
            if($rs){
             $out.="<option value=\"0\">Seleccione</option>";
            foreach ($rs as $r) {
                $id_c = $r["id"];
                $nom_c = $r["nombre"];
                $out.="<option value=\"$id_c\">$nom_c</option>";
            }
            }
           
        } else {
            $out.="<option value=\"\">No hay categorias</option>";
        }
        echo $out;
    }

    public function loadfab() {
        $id_fab = $_POST["id_marca"];
        $out = "";
        $all = "";
        $t = "";
        if ($id_fab != "") {
            $sql = "SELECT DISTINCT f.id,f.nombre FROM productos p INNER JOIN fabricantes f ON(f.id=p.id_fabricante) WHERE p.publicado='S' AND p.id_categoria='$id_fab' and estado=1 ORDER BY f.nombre";
            $rs = Doo::db()->query($sql)->fetchAll();
            if($rs){
                foreach ($rs as $r) {
                $id_c = $r["id"];
                $nom_c = $r["nombre"];
                $out.="<option value=\"$id_c\">$nom_c</option>";
                 }
                 $t.="<option value=\"all\">Todos</option>";
            }else{
                $t.="";
            }
            
        }
        $all.=$t;
        echo $out . $all;
    }

    public function Cargarcatgs() {
        $id_fab = $_POST["id_categoria"];
        $out = "";
        $all = "";
        if ($id_fab != "") {
            $sql = "SELECT DISTINCT c.id,c.nombre FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) WHERE p.publicado='S' AND p.id_categoria='$id_fab' ORDER BY c.nombre";
            $rs = Doo::db()->query($sql)->fetchAll();
            foreach ($rs as $r) {
                $id_c = $r["id"];
                $nom_c = $r["nombre"];
                $out.="<option value=\"$id_c\">$nom_c</option>";
            }
        } else {
            $sql = "SELECT DISTINCT c.id,c.nombre FROM productos p INNER JOIN fabricantes c ON(c.id=p.id_fabricante) WHERE p.publicado='S'  ORDER BY c.nombre";
            $rs = Doo::db()->query($sql)->fetchAll();
            foreach ($rs as $r) {
                $id_c = $r["id"];
                $nom_c = $r["nombre"];
                $out.="<option value=\"$id_c\">$nom_c</option>";
            }
        }
        $all.="<option value=\"0\">Elige una Marca..</option>";
        echo $all . $out;
    }

    function deleteitem() {
        $array = array();
        if (isset($_SESSION["itement"])) {
            $array = unserialize($_SESSION["itement"]);
        }
        $i = $_POST['index'] - 1;
        array_splice($array, $i, 1);
        $_SESSION["itement"] = serialize($array);
        $this->data['entdasarray'] = $array;
        $this->renderc("items", $this->data, true);
    }

    public function getImprimirLista() {

        if (!isset($_SESSION["itement"])) {
            $this->data['rootUrl'] = Doo::conf()->APP_URL;
            $this->renderc("error2", $this->data, true);
        } else {
            $array = unserialize($_SESSION["itement"]);
            if (count($array) <= 0) {
                $this->data['rootUrl'] = Doo::conf()->APP_URL;
                $this->renderc("error2", $this->data, true);
            } else {
                $array = unserialize($_SESSION["itement"]);
                $sql2 = "SELECT p.nombre,p.caract,p.id_categoria,p.imagen2,c.nombre AS Categoria,f.nombre AS Marca,p.precio_venta,p.precio_promocion FROM productos p INNER JOIN categorias c ON(p.id_categoria=c.id) INNER JOIN fabricantes f ON(p.id_fabricante=f.id) WHERE p.publicado='S' ";
                $i = 0;
                foreach ($array as $s) {
                    $id_categoria = $s["idcateg"];
                    $id_marcas = $s["idfabr"];
                    if ($id_marcas == "all") {
                        if (count($array) > 1) {
                            if ($i == 0) {
                                $sql2.=" AND ( p.id_categoria='$id_categoria'";
                            } else {
                                $sql2.=" OR p.id_categoria='$id_categoria'";
                            }
                        } else {
                            $sql2.="AND p.id_categoria='$id_categoria'";
                        }
                    } else {
                        if (count($array) > 1) {
                            if ($i == 0) {
                                $sql2.=" AND ( (p.id_categoria='$id_categoria' AND p.id_fabricante='$id_marcas')";
                            } else {
                                $sql2.=" OR (p.id_categoria='$id_categoria' AND p.id_fabricante='$id_marcas')";
                            }
                        } else {
                            $sql2.=" AND (p.id_categoria='$id_categoria' AND p.id_fabricante='$id_marcas')";
                        }
                    }
                    $i++;
                }
                if (count($array) > 1) {
                    $sql2.=" )";
                }
                if ($id_categoria == "") {
                    echo "No Hay Productos";
                } else {
                    $sql3 = "SELECT imagen FROM combos WHERE id_categoria = $id_categoria";
                    $j = 0;
                    foreach ($array as $d) {
                        $id_categoria = $d["idcateg"];
                        $sql3.=" OR id_categoria = $id_categoria";
                        $j++;
                    }
                    $rs3 = Doo::db()->query($sql3 . "  ORDER BY id_categoria")->fetchAll();
                    $this->data['imagen'] = $rs3;
                }

                $rs = Doo::db()->query($sql2 . "  ORDER BY p.id_categoria,p.id_fabricante")->fetchAll();
                $this->data['productos'] = $rs;
                $this->data['rootUrl'] = Doo::conf()->APP_URL;
                $this->renderc("Imprimir_lista", $this->data, true);
            }
        }
    }

    public function Totalizar($canasta,$envio=0) {
        $sumatoria = 0;
        foreach ($canasta as $d) {

            if (isset($_SESSION["login_cliente"])) {
                $login = $_SESSION['login_cliente'];
                if ($login->rol != "1") {
                    $vl = (($d["valor"] * $d["iva"]) + $d["valor"]);
                } else {
                    $vl = ($d["valor"]);
                }
            } else {
                $vl = (($d["valor"] * $d["iva"]) + $d["valor"]);
            }

            $st = $d["cantidad"] * $vl;
            $sumatoria = $sumatoria + $st;
        }
        return $sumatoria+$envio;
    }

    public function FormComprar() {
        $this->configuracion();

        $login = $_SESSION['login_cliente'];
        $idusuario = $login->id_cliente;

        $sqlp = "SELECT * FROM personas WHERE id = $idusuario";
        $rsp = Doo::db()->query($sqlp)->fetchAll();

        $this->data["identificacion"] = $rsp[0]["identificacion"];
        $this->data["nombre"] = $rsp[0]["nombre"];
        $this->data["apellidos"] = $rsp[0]["apellidos"];
        $this->data["direccion"] = $rsp[0]["direccion"];
        $this->data["telefono"] = $rsp[0]["telefono"];
        $this->data["celular"] = $rsp[0]["celular"];
        $this->data["email"] = $rsp[0]["email"];
        $this->data["id"] = $rsp[0]["id"];


        $this->buildMenu();
        $this->data['texto'] = "";
        $this->data['content'] = "formulariocomprar";
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function FormCotizacion() {
        $this->configuracion();
        $this->buildMenu();
        $this->data['texto'] = "";
        $this->data['content'] = "formulariocotizacion";
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function getClientes() {
        $id = $_POST["cod"];
        $rs = Doo::db()->query("select id,identificacion,nombre,apellidos,direccion,telefono,celular,email from personas WHERE identificacion= '$id' ");
        $cliente = $rs->fetchAll();
        if (count($cliente) > 0) {
            echo json_encode(array("identificacion" => $cliente[0]['identificacion'], "id" => $cliente[0]['id'], "nombre" => $cliente[0]['nombre'], "apellidos" => $cliente[0]['apellidos'],
                "direccion" => $cliente[0]['direccion'], "telefono" => $cliente[0]['telefono'], "celular" => $cliente[0]['celular'],
                "email" => $cliente[0]['email']));
        } else {
            echo '0';
        }
    }

    public function getSendComprar() {
        try {
            $this->configuracion();
            $this->buildMenu();
            $this->buildMenuH();
            $this->Banner();
            $this->ProductosPromocion();
        
            if (isset($_SESSION["carrito"]) && count(unserialize($_SESSION["carrito"])) > 0) {
                $array = unserialize($_SESSION["carrito"]);
        
                $cantidad = 0;
                $sumatoria2 = 0;
                $departamentos = $_POST['departamentos'];
                $municipios = $_POST['municipios'];

                $departamentos = Doo::db()->query("SELECT * FROM departamentos WHERE id_departamento = '$departamentos'")->fetch();
                $departametos_municipios = Doo::db()->query("SELECT * FROM departametos_municipios WHERE id_municipio = '$municipios'")->fetch();
                
                Doo::loadModel("Pedidos");
                $datos = new Pedidos($_POST);
                $datos->papellido = $_POST['apellidos'];
                $datos->sapellido = "";
                $datos->tipo_docto = $_POST['tipo_documento'];
                $datos->nodocumento = $_POST['identificacion'];
                $datos->telecasa = $_POST['referencia'];
                $datos->teloficina = $_POST['telefono'];
                $datos->celular = $_POST['telefono'];
                $datos->email = $_POST['email'];
                $datos->ciudad = $departametos_municipios['municipio'];
                $datos->departamento = $departamentos['departamento'];
                $datos->estado = "Pendiente";
                $datos->fecha = date("Y-m-d H:i:s");
                $datos->subtotal = 0;
                $datos->id_persona = 0;
                $datos->costoenvio = $this->calculateCostos($departamentos['id_departamento'], $departametos_municipios['id_municipio']);
                $datos->id = Doo::db()->insert($datos);
                
                Doo::loadModel("PedidoProductos");
                $totaliva = 0;
                $subtotal = 0;
                $baseiva = 0;
                foreach ($array AS $k => $it) {
                    if ($it["valor2"] > 0) {
                        $valort = $it["valor2"];
                    } else {
                        $valort = $it["valor"];
                    }
                    $cantidad = $cantidad + $it["cantidad"];
                    $subtotal = ($valort * $it["cantidad"]);
                    $sumatoria2 = $sumatoria2 + $subtotal;

                    if ($it["iva"] > 0.00) {
                        $baseiva = $baseiva + ($subtotal / ($it["iva"] + 1));
                        $totaliva = ($subtotal - $baseiva);
                    }
                    $codigoP = $k;
                    $datos2 = new PedidoProductos();
                    $datos2->cantidad = $it["cantidad"];
                    $datos2->cod_prod = $codigoP;
                    $datos2->id_pedido = $datos->id;
                    $datos2->nom_prod = $it["nombre"];
                    $datos2->valor = $valort;
                    Doo::db()->Insert($datos2);
                }
                Doo::db()->query("UPDATE pedidos SET subtotal = $sumatoria2, total = $sumatoria2 WHERE id = '$datos->id'");

                $this->data['num_pedido'] = $datos->id;
                $_POST["total"] = $sumatoria2;
                $_POST["cantidad"] = $cantidad;
                $_POST["totalIva"] = $totaliva;
                $_POST["baseIva"] = $baseiva;
                $this->data["costoenvio"] = $datos->costoenvio;
                $this->data['car'] = $array;
                $this->data['municipio'] = $departametos_municipios['id_municipio'];
                $this->data['departamento'] = $departamentos['id_departamento'];
                $this->data['content'] = 'prev_pago';
                $this->data['cliente'] = $datos;
                $this->data['texto'] = '';
                $this->data['rootUrl'] = Doo::conf()->APP_URL;
                $this->renderc('prev_pago', $this->data, true);
            } else {
                echo json_encode(array('message' => 'No hay elementos en el carrito'));
            }
        } catch (Exception $ex) {
            echo json_encode(array('message' => $ex->getMessage()));
        }
    }
    
    public function getDeparmentos(){
        $id=$_POST['id'];   
        $sqlp = Doo::db()->query("SELECT * FROM departametos_municipios where departamento_id='$id' ")->fetchAll();
        $html="<option value='X'>[Selecciona]</option>";
        foreach($sqlp as $q){
            $html.="<option value='$q[id_municipio]'> $q[municipio] </option>";
        }
        echo $html;
    }

    public function Pagar() {

        $login = $_SESSION['login_cliente'];
        $idusuario = $login->id_cliente;

        $sqlp = "SELECT * FROM personas WHERE id = $idusuario";
        $rsp = Doo::db()->query($sqlp)->fetchAll();

        $array = array();
        $array = unserialize($_SESSION["carrito"]);
        $totaliva = 0;
        $subtotal = 0;
        $baseiva = 0;
        $cantidad = 0;
        $sumatoria2 = 0;
        $valor = 0;
        foreach ($array AS $k => $it) {
            $cons = Doo::db()->query("SELECT codigo from productos where id=$k")->fetch();
            if ($it["valor2"] > 0) {
                $valort = $it["valor2"];
            } else {
                $valort = $it["valor"];
            }
            $cantidad = $cantidad + $it["cantidad"];
            $subtotal = ($valort * $it["cantidad"]);
            $sumatoria2 = $sumatoria2 + $subtotal;

            if ($it["iva"] > 0.00) {
                $baseiva = $baseiva + ($subtotal / ($it["iva"] + 1));
                $totaliva = ($subtotal - $baseiva);
            }
//            $codigoP = $cons["codigo"];
//            $datos2 = new PedidoProductos();
//            $datos2->cantidad = $it["cantidad"];
//            $datos2->cod_prod = $codigoP;
//            $datos2->id_pedido = $id;
//            $datos2->nom_prod = $it["nombre"];
//            //$datos2->valor = $it["valor"];
//            $datos2->valor = $valort;
            // Doo::db()->Insert($datos2);
        }
        $rs2 = Doo::db()->query("SELECT MAX(id) AS id FROM pedidos FOR UPDATE")->fetch();
        $id = $rs2["id"];

        Doo::db()->query("UPDATE pedidos SET subtotal=$sumatoria2,total=$sumatoria2 WHERE id=$id");
        $this->data['num_pedido'] = $id;

        $_POST["total"] = $sumatoria2;
        $_POST["cantidad"] = $cantidad;
        $_POST["totalIva"] = $totaliva;
        $_POST["baseIva"] = $baseiva;

        $this->data["identificacion"] = $rsp[0]["identificacion"];
        $this->data["nombre"] = $rsp[0]["nombre"];
        $this->data["apellidos"] = $rsp[0]["apellidos"];
        $this->data["direccion"] = $rsp[0]["direccion"];
        $this->data["telefono"] = $rsp[0]["telefono"];
        $this->data["celular"] = $rsp[0]["celular"];
        $this->data["email"] = $rsp[0]["email"];
        $this->data["id"] = $rsp[0]["id"];
        $this->buildMenu();
        $this->configuracion();
        $this->data['cliente'] = $_POST;
        $this->data['content'] = 'pagar';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function Payment() {

        $sql = "SELECT id,nombre,fondo_pagina,footer_1,footer_2,footer_3,footer_4,title_fot_1,title_fot_2,title_fot_3,title_fot_4 from plantilla where estado=1";
        $rs = Doo::db()->query($sql)->fetch();
        $this->data['planti'] = $rs;
        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $sw = true;

        $llave = "1324f30c00b";
        $usuario_id = $_REQUEST['usuario_id'];
        $ref_venta = $_REQUEST['ref_venta'];
        $valor = $_REQUEST['valor'];
        $moneda = $_REQUEST['moneda'];
        $estado_pol = $_REQUEST['estado_pol'];
        $firma_cadena = "$llave~$usuario_id~$ref_venta~$valor~$moneda~$estado_pol";
        $firmacreada = md5($firma_cadena);
        $firma = $_REQUEST['firma'];
        $fecha_procesamiento = $_REQUEST['fecha_procesamiento'];
        $ref_pol = $_REQUEST['ref_pol'];
        $cus = $_REQUEST['cus'];
        $banco_pse = $_REQUEST['banco_pse'];

        if ($_REQUEST['estado_pol'] == 6 && $_REQUEST['codigo_respuesta_pol'] == 5) {
            $estadoTx = "Fallida";
        } else if ($_REQUEST['estado_pol'] == 6 && $_REQUEST['codigo_respuesta_pol'] == 4) {
            $estadoTx = "Rechazada";
        } else if ($_REQUEST['estado_pol'] == 12 && $_REQUEST['codigo_respuesta_pol'] == 9994) {
            $estadoTx = "En proceso";
        } else if ($_REQUEST['estado_pol'] == 4 && $_REQUEST['codigo_respuesta_pol'] == 1) {
            $estadoTx = "Aprobada";
        } else {
            $estadoTx = $_REQUEST['mensaje'];
            $sw = false;
        }
        if (strtoupper($firma) == strtoupper($firmacreada)) {

            if ($sw) {
                unset($_SESSION['carrito']);
            }

            $this->data['fecha_procesamiento'] = $fecha_procesamiento;
            $this->data['moneda'] = $moneda;
            $this->data['valor'] = $valor;
            $this->data['ref_venta'] = $ref_venta;
            $this->data['estadoTx'] = $estadoTx;
            $this->data['ref_pol'] = $ref_pol;
            $this->data['estado_pol'] = $estado_pol;

            $this->data['texto'] = "";
            $this->data['sw'] = $sw;
            $this->data['content'] = "confirmacionrespuesta";
            $this->data['rootUrl'] = Doo::conf()->APP_URL;
            $this->renderc('home', $this->data, true);
        }
    }

    public function conf_pago() {

        $sw = true;

        $llave = "1324f30c00b";
        $usuario_id = $_REQUEST['usuario_id'];
        $ref_venta = $_REQUEST['ref_venta'];
        $valor = $_REQUEST['valor'];
        $moneda = $_REQUEST['moneda'];
        $estado_pol = $_REQUEST['estado_pol'];
        $firma_cadena = "$llave~$usuario_id~$ref_venta~$valor~$moneda~$estado_pol";
        $firmacreada = md5($firma_cadena);
        $firma = $_REQUEST['firma'];
        $fecha_procesamiento = $_REQUEST['fecha_procesamiento'];
        $ref_pol = $_REQUEST['ref_pol'];
        $cus = $_REQUEST['cus'];
        $banco_pse = $_REQUEST['banco_pse'];

        if ($_REQUEST['estado_pol'] == 6 && $_REQUEST['codigo_respuesta_pol'] == 5) {
            $estadoTx = "Fallida";
        } else if ($_REQUEST['estado_pol'] == 6 && $_REQUEST['codigo_respuesta_pol'] == 4) {
            $estadoTx = "Rechazada";
        } else if ($_REQUEST['estado_pol'] == 12 && $_REQUEST['codigo_respuesta_pol'] == 9994) {
            $estadoTx = "En proceso";
        } else if ($_REQUEST['estado_pol'] == 4 && $_REQUEST['codigo_respuesta_pol'] == 1) {
            $estadoTx = "Aprobada";
        } else {
            $estadoTx = $_REQUEST['mensaje'];
            $sw = false;
        }
        if (strtoupper($firma) == strtoupper($firmacreada)) {
            if ($sw) {
                Doo::db()->query("UPDATE pedidos SET estado=$estadoTx");
            }
        } else {
            echo "acceso denegado";
        }
    }

    /*
      public function conf_pago() {
      Doo::loadModel("Pedidos");
      $_POST["estado"]="Aprobada";
      $datos = new Pedidos($_POST);
      Doo::db()->Insert($datos);

      $rs = Doo::db()->query("SELECT MAX(id) AS id FROM pedidos FOR UPDATE")->fetch();
      $id = $rs["id"];
      Doo::loadModel("PedidoProductos");
      $items = unserialize($_SESSION["carrito"]);

      foreach ($items AS $k => $it) {
      $cons = Doo::db()->query("SELECT codigo from productos where id=$k")->fetch();
      $codigoP = $cons["codigo"];
      $datos2 = new PedidoProductos();
      $datos2->cantidad = $it["cantidad"];
      $datos2->cod_prod = $codigoP;
      $datos2->id_pedido = $id;
      $datos2->nom_prod = $it["nombre"];
      $datos2->valor = $it["valor"];
      Doo::db()->Insert($datos2);
      }
      }
     */

    public function sendCotizarCarrito() {
        $this->configuracion();
        $id = $_POST['id'];
        $this->buildMenu();
        $array = array();
        $array = unserialize($_SESSION["carrito"]);
        $this->data['car'] = $array;
        $msj = "";
        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        $mail->addTo($_POST['email']);
        $mail->setSubject('Cotizacion del Carrito');
        $encabzado = "<table style='width:80%;'><tr>"
                . "<td style='width:30%; text-align:center; background-color:#D92527; color:#fff; font-size:1.2em;'>&nbsp;</td>"
                . "<td style='width:40%; text-align:center; background-color:#D92527; color:#fff; font-size:1.2em;'>Descripcion del Producto</td>"
                . "<td style='width:15%; text-align:center; background-color:#D92527; color:#fff; font-size:1.2em;'>Cantidad</td>"
                . "<td style='width:15%; text-align:center; background-color:#D92527; color:#fff; font-size:1.2em;'>Valor</td>"
                . "</tr>";

        $sumatoria = 0;
        foreach ($array as $s) {
            if ($s["valor2"] > 0) {
                $valorunitario = $s["valor2"];
            } else {
                $valorunitario = $s["valor"];
            }
            $cantidad = $s["cantidad"];
            $descripcion = $s["nombre"];
            $imagen = $s["imagen2"];
            $msj = $msj . "<tr>"
                    . "<td style='width:30%; text-align:center; padding:5px; border-bottom:1px solid #f2f2f2; font-size:1.2em;'><img style='width:150px; height:150px;' src='http://computerworking.com.co/uploads/productos/" . $imagen . "'/></td>"
                    . "<td style='width:40%; text-align:center; padding:5px; border-bottom:1px solid #f2f2f2; font-size:1.2em;'>" . $descripcion . "</td>"
                    . "<td style='width:15%; text-align:center; padding:5px; border-bottom:1px solid #f2f2f2; font-size:1.2em;'> " . $cantidad . "</td>"
                    . "<td style='width:15%; text-align:center; padding:5px; border-bottom:1px solid #f2f2f2; font-size:1.2em;'>$ " . number_format($valorunitario, 0) . "</td>"
                    . "</tr>";
            $sumatoria = $sumatoria + ($valorunitario * $s["cantidad"]);
        }
        $footer = "<tr><td colspan='4' style='text-align:right'></td></tr>"
                . "<tr><td colspan='4' style='text-align:right; color:#D92527; font-size:1.3em;'>Total: $ " . number_format($sumatoria, 0) . "</td></tr></table>"
                . "<div style='width:80%; margin-right:auto; margin-left:auto;'><img style='width: 300px; height: auto' src='http://computerworking.com.co/global/img/logo.png'/></div>";
        $mail->setBodyHtml($encabzado . $msj . $footer);
        $mail->setFrom('ventasmayoristas@computerworking.net', 'Computerworking');
        echo "Mensaje Enviado con Exito";
        $mail->send();
        $this->Banner();
        $this->ProductosPromocion();
        $this->data['content'] = 'confirmacion';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
    }

    private function buildMenuV() {
        $sql = "SELECT id,nombre,depende,orden FROM categorias WHERE estado=1 AND depende=0 ORDER BY orden,nombre ASC";
        $rs = Doo::db()->query($sql);
        $parentMenu = $rs->fetchAll();
        $this->data["htmlmenu2"] = '<ul>';
        $this->buildChildMenuV($parentMenu, false);
        $this->data["htmlmenu2"].= '</ul>';
    }

    private function buildChildMenuV($parentMenu, $sub) {
        foreach ($parentMenu as $row) {
            $id = $row["id"];
            $etiqueta = $row["nombre"];
            $url = "categorias?id_cat=" . $row["id"];
            $url2 = "principalproducto/" . $row["id"];
            $submenu = $row["depende"];
            if ($submenu == '0') {
                $this->data["htmlmenu2"].= '<li class="has-sub"><a title="" href="' . Doo::conf()->APP_URL . $url2 . '">' . $etiqueta . '</a>';
                $sql = "SELECT id,nombre,depende FROM categorias WHERE estado=1 AND depende='$id' ORDER BY nombre ASC";
                $rs = Doo::db()->query($sql);
                $childMenu = $rs->fetchAll();
                $this->data["htmlmenu2"].= '<ul>';
                $this->buildChildMenuV($childMenu, true);
                $this->data["htmlmenu2"].= '</ul>';
            } else {
                $this->data["htmlmenu2"].= '<li>';
                $this->data["htmlmenu2"].= '<a href="' . Doo::conf()->APP_URL . $url . '">' . $etiqueta . '</a>';
                $this->data["htmlmenu2"].= '</li>';
            }
        }
    }

    private function buildMenuH() {
        $sql = "SELECT id,etiqueta,url,destino,submenu,alto FROM direcciones WHERE istop='S' AND dependencia='0' ORDER BY ordercolumn2";
        $rs = Doo::db()->query($sql);
        $parentMenu = $rs->fetchAll();
        $this->data["htmlmenuH"] = '<ul class="nav3">';
        $this->buildChildMenuH($parentMenu, false);
        $this->data["htmlmenuH"].= '</ul>';
    }

    private function buildChildMenuH($parentMenu, $sub) {
        foreach ($parentMenu as $row) {
            $id = $row["id"];
            $submenu = $row["submenu"];
            $etiqueta = $row["etiqueta"];
            $alto = $row["alto"];
            $url = $row["url"];
            $destino = $row["destino"];
            if ($submenu == 'S') {
                $this->data["htmlmenuH"].= '<li class="drop"><a href="#">' . $etiqueta . '</a>';
                $sql = "SELECT id,etiqueta,url,destino,submenu,alto FROM direcciones WHERE istop='S' AND dependencia='$id' ORDER BY ordercolumn2";
                $rs = Doo::db()->query($sql);
                $childMenu = $rs->fetchAll();
                $this->data["htmlmenuH"].= ' <div class="dropdownContain">
                <div class="dropOut">
                    <div class="triangle"></div><ul class="nav3">';
                $this->buildChildMenuH($childMenu, true);
                $this->data["htmlmenuH"].= '</ul ></div>
            </div></li><li></li>';
            } else {
                $this->data["htmlmenuH"].= '<li>';
                if ($destino == 'E') {
                    //style="font-size: 10px;' . ($alto > 0 ? 'height:' . $alto . 'px;' : '') . '"
                    $this->data["htmlmenuH"].= '<a target="_black" href="' . $url . '">' . $etiqueta . '</a>';
                } else {
                    $this->data["htmlmenuH"].= '<a href="' . Doo::conf()->APP_URL . $url . '">' . $etiqueta . '</a>';
                }
                $this->data["htmlmenuH"].= '</li><li>';
                if (!$sub) {
                    $this->data["htmlmenuH"].= '</li>';
                }
            }
        }
    }

    public function getEmpleadosMes() {

        $this->configuracion();

        $empleados = Doo::db()->find('Vendedores', array("select" => "id,nombre,foto,sucursal,cargo", "where" => "publicado='S'", "ORDER BY" => "nombre"));
        $this->data['empleados'] = $empleados;
        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        $this->data['content'] = 'vendedores_del_mes';
        $this->data['texto'] = '';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function sendCotizarArticulo() {
        $this->configuracion();
        $id = $_POST['id_producto'];

        $sql2 = Doo::db()->query("SELECT c.nombre,c.id_categoria,c.imagen AS imgcombo FROM combos c INNER JOIN productos p ON (p.id_categoria=c.id_categoria) WHERE p.id='$id' LIMIT 1")->fetch();
        $imgcombo = $this->data['img_combos'] = $sql2['imgcombo'];

        $n = Doo::db()->find('Productos', array("select" => "id,nombre,codigo,imagen,imagen2,precio_venta,precio_promocion,caract,descripcion", "where" => 'id=?', 'limit' => 1, 'param' => array($id)));
        $nombres = $this->data['titulo'] = $n->nombre;
        $precio_promocion = $this->data['precio_promocion'] = $n->precio_promocion;
        $precio_venta = $this->data['precio_venta'] = $n->precio_venta;
        $imagen = $this->data['imagen'] = $n->imagen;
        $caracteristica = $this->data['caracteristica'] = $n->caract;
        $descripcion = $this->data['descripcion'] = $n->descripcion;
        $this->buildMenu();


        $pp = number_format($this->data['precio_promocion'], 0);
        $pv = number_format($this->data['precio_venta'], 0);

        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        $mail->addTo($_POST['email']);

        if ($precio_promocion > 0) {
            $msj_precio = "<div class='clear'></div>"
                    . "<div style='float: left;'>"
                    . "<h4 style='color: #333; font-size: 30px; padding: 0; margin-top: 40px;'>" . $pp . "</h4>"
                    . "</div>"
                    . "<div style'float:right;'>"
                    . "<span style='color: #333;'>Antes:</span>"
                    . "<h4 style='color: #C41717; font-size: 30px; text-decoration: line-through; margin: 0;'>$" . $pv . "</h4>"
                    . "</div>";
        } else {
            $msj_precio = "<div style'float:right;'>"
                    . "<h4 style='color: #333; font-size: 30px; margin-top: 40px;'>$" . $pv . "</h4>"
                    . "</div>";
        }
        $confirmacion = "<h3 style='font-size:12px; color:#3d3d3d; text-align:center'>Cotizacion enviada Llegara al correo:" . $_POST['email'] . "</h3>";
        echo $confirmacion;
        $mail->setSubject('Cotizacion del Producto :' . $nombres . '');
        $msj = "<div style='width: 800px; margin-left: auto; margin-right: auto; border: 1px solid #ebebeb; padding: 10px;'> "
                . "<div style='padding: 10px; border: 1px solid #ebebeb; padding: 10px;'>"
                . "<div style='font-size: 20px; font-weight: bold; width: 100%;'>"
                . "<div style='margin-left: auto; margin-right: auto; width: 414px; margin-bottom: 70px;'>"
                . "<img style='margin-left: auto; margin-right: auto;' src='http://computerworking.com.co/global/img/logo.png'/>"
                . "</div>"
                . "<div style='font-size: 20px; font-weight: bold; float: left; width: 50%; font-size: 23px;'>" . $nombres . "</div>"
                . "<div style='width: 300px; float: right;'>" . $msj_precio . "</div>"
                . "<div style='clear: both;'></div>"
                . " </div>"
                . "<div style='clear: both;'></div>"
                . "<div style='width: 100%'>"
                . "<div style='width: 300px; float: left;'>"
                . "<img style='height: auto; width: 300px; float: left;' src='http://computerworking.com.co/uploads/productos/big/" . $imagen . " '/>"
                . "</div>"
                . "<div style='float: right; width: 470px; text-align: justify; margin-top: 43px;'>" . $caracteristica . "</div> "
                . "</div>"
                . "<div style='clear: both;'></div>"
                . "<div style='border: 1px solid #b8b8b8; padding: 10px; border-radius: 4px; text-align: justify;'>" . $descripcion . ""
                . "</div>"
                . "<div><img style='margin-left: auto; margin-right: auto;display: block;max-width: 100%;height: auto;' src='http://computerworking.com.co/uploads/combos/" . $imgcombo . "'/>"
                . "</div>"
                . "</div>"
                . "</div>"
                . "</div>";

        $mail->setBodyHtml($msj);
        $mail->setFrom($_POST['email']);
        $mail->send();
        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $this->data['content'] = 'confirmacion';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
    }

    public function getCategoriaPrincipal() {
        $id = $_REQUEST['id'];
        $catgprincipal = Doo::db()->find('Categorias', array("select" => "id,nombre,imagen", "where" => "depende=$id AND estado=1", "asc" => "nombre"));
        $this->data['ctgprincipal'] = $catgprincipal;
        $ticatg = Doo::db()->find('Categorias', array("select" => "id,nombre", "where" => 'id=?', 'limit' => 1, 'param' => array($id)));
        $this->data['titulo'] = $ticatg->nombre;
        $this->configuracion();
        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        $this->data['content'] = 'catgprincipal';
        $this->data['texto'] = '';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function getCategoriaPrincipalProducto() {

        $id = $_REQUEST['id'];
//        $catgproducto = Doo::db()->query("SELECT p.nombre,p.imagen,p.codigo FROM productos p INNER JOIN categorias c ON (p.id_categoria = c.id) WHERE c.depende = $id")->fetchAll();
//        $this->data['ctgproducto']=$catgproducto;



        $where = "p.publicado='S'  AND c.depende=$id  ORDER BY p.id_fabricante,p.precio_venta DESC";
        $rst = Doo::db()->query("SELECT COUNT(*) AS total FROM productos p INNER JOIN categorias c ON (p.id_categoria = c.id) where " . $where);
        $t = $rst->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        }
        if ($total == 0) {
            $total = 1;
        }
        Doo::loadHelper('DooPager');
        $pager = new DooPager("#", $total, 12, 10);
        if (isset($this->params['number'])) {
            $pager->paginate(intval($this->params['number']));
        } else {
            $pager->paginate(1);
        }
        $sql = "SELECT p.id,p.nombre,p.caract,p.precio_venta,p.precio_promocion,p.imagen2 FROM productos p  INNER JOIN categorias c ON (p.id_categoria = c.id) WHERE " . $where;
        $this->data['ctgproducto'] = Doo::db()->query($sql . " LIMIT $pager->limit")->fetchAll();
        $this->data['pager'] = $pager->output;



        $this->configuracion();

        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        $this->data['content'] = 'catgprincipalproducto';
        $this->data['texto'] = '';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function newbusqueda() {
        if (isset($_POST["marca"])) {
            $marca = $_POST["marca"];
        } else {
            $marca = "";
        }
        if (isset($_POST["categoria"])) {
            $categoria = $_POST["categoria"];
        } else {
            $categoria = "";
        }
        $where = " publicado='S' ";
        if ($marca != "" && $marca != "0") {
            $where.=" AND id_fabricante=$marca ";
        }
        if ($categoria != "") {
            $where.=" AND id_categoria=$categoria ";
        }

        if (isset($_POST["novedoso"])) {
            $where.=" AND novedoso='S' ";
        }
        //echo $where;
        $t = Doo::db()->query("select count(*) as total FROM productos where " . $where)->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        }
        if ($total == 0) {
            $total = 1;
        }
        Doo::loadHelper('DooPager');
        $pager = new DooPager("#", $total, 12, 10);
        if (isset($_POST["page"]))
            $pager->paginate(intval($_POST["page"]));
        else
            $pager->paginate(1);
        $s = Doo::db()->query("SELECT nombre,precio_venta,caract,precio_promocion,id,imagen2 FROM productos WHERE " . $where . " ORDER BY id_fabricante,precio_venta DESC LIMIT $pager->limit")->fetchAll();
        $this->data['texto'] = "";
        $this->data['content'] = 'itemsbusqueda';
        $this->data['productos'] = $s;
        $this->data['principal'] = 'avanzada';
        $this->data['pager'] = $pager->output;
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        //print_r($s);
        $this->renderc('itemsbusqueda', $this->data, true);
    }

    public function getRuta() {
        $out = '<a href="' . Doo::conf()->APP_URL . '" class="previous" title="Pagina de inicio">Inicio</a>';
        $catg = $_POST["categoria"];
        $marca = $_POST["marca"];
        if ($catg != "" && $catg != "0") {
            $nom_cag1 = Doo::db()->query("SELECT nombre FROM categorias WHERE id=?", array($catg))->fetch();
            $nom_cag = $nom_cag1["nombre"];
            $out.='<a href="' . Doo::conf()->APP_URL . 'categorias?id_cat=' . $catg . '&id_marca=' . $marca . '" class="previous" title="' . $nom_cag . '">' . $nom_cag . '</a>';
        } else {
            $out.='<a href="' . Doo::conf()->APP_URL . 'fabricante/Todos" class="previous" title="Todos">Todos</a>';
        }
        if ($marca != "0") {
            $nom_fab1 = Doo::db()->query("SELECT nombre FROM fabricantes WHERE id=?", array($marca))->fetch();
            $nom_fab = $nom_fab1["nombre"];
            $out.='<a href="' . Doo::conf()->APP_URL . 'fabricante/' . $marca . '" class="previous" title="' . $nom_fab . '">' . $nom_fab . '</a>';
        }
        $_SESSION["stak_url"] = $out;
        echo $out;
    }

    //

    public function indexCotizaciones(){
        $this->plantilla();
        $this->buildMenu();
        $this->configuracion();
        $this->data['content'] = 'cotizaciones';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }
    public function activeCotizaciones(){
        $id=$this->params["pindex"];
        $cotizacion =Doo::db()->query("SELECT cd.id_prod as id,cd.cantidad,valor FROM cotizacion_detalle cd   INNER JOIN cotizacion co on (co.id=cd.id_cotizacion) where  co.id='$id';")->fetchAll();
        foreach($cotizacion as $cotizacion){
            $p = Doo::db()->find("Productos", array("select" => "nombre,codigo,precio_venta,precio_promocion,id,imagen2,iva", 
                                                    'limit' => 1, 
                                                    "where" => " id=? ", 
                                                    "param" => array($cotizacion['id'])));
            $canasta[$p->id] = array( "nombre" => $p->nombre, 
                                "codigo" => $p->codigo, 
                                "valor" => $cotizacion['valor'], 
                                "valor2" => $p->precio_promocion, 
                                "cantidad" => $cotizacion['cantidad'],
                                "id" => $p->id, 
                                "id_cotizacion" => "",
                                "imagen2" => $p->imagen2, 
                                "iva" => $p->iva);
           
        }
        $_SESSION["carrito"] = serialize($canasta);
        return Doo::conf()->APP_URL.'ver_carro/';
    }
    public function searchCotizaciones(){
        $id=$_POST['id'];
        $html='';
        $data=Doo::db()->query("SELECT numero,subtotal,total,c.id,id_persona,nombre,fecha_registro,apellidos,email,celular FROM cotizacion c INNER JOIN personas p ON (p.id=c.id_persona) WHERE p.identificacion='$id';")->fetchAll();
        foreach ($data  as $key) {
            $html.='<tr >
                        <td>'.$key["numero"].'</td>                        
                        <td>'.$key["fecha_registro"].'</td>
                        <td>'.$key["nombre"].' '.$key["apellidos"].'</td>
                        <td>'.$key["celular"].'</td>
            
                        <td>'.$key["email"].'</td>
                        <td>'.number_format($key["total"],2).'</td>
                        <td><a style="color:#3b3b3b; font-size:25px;" href='.Doo::conf()->APP_URL.'cotizaciones/active/'.$key['id'] .'><i class="fa fa-cart-plus" aria-hidden="true"></i></a></td>
                    </tr>';
        }
        echo $html;
    }

    // Imprimir Carrito de compras
    public function print_cart() {
        if (isset($_SESSION["carrito"])) {
            $array = unserialize($_SESSION["carrito"]);
        } else {
            $array = array();
        }

        Doo::loadClass("pdf/PDF_ImageAlpha");
        Doo::loadClass("reportes/ImprimirCarrito");
        $pdf = new ImprimirCarrito();
        $pdf->AliasNbPages();
        $pdf->AddPage();
        $pdf->body($array);
        $pdf->Output();
    }
    public function redirect(){
        if($_POST){
              return Doo::conf()->APP_URL.'search/'.$_POST['texto'].'/1';
        }else{
             return Doo::conf()->APP_URL;
        }
       
    }

    public function searchBytext() {
        $pst = filter_input_array(INPUT_POST);
        if (!isset($pst["texto"])) {
            if (!isset($this->params['texto'])) {
                $texto = "";
            } else {
                $texto = $this->params['texto'];
            }
        } else {
            $texto = $pst["texto"];
        }
        $texto=urldecode($texto);      
        $where="";
        $where2="";
        if($texto!=""){
            
            //$where.= " match(nombre) against('+$texto' IN BOOLEAN MODE) AND id_categoria IN (select id from categorias where depende in (select id from categorias ct where match(nombre) against('+$texto' IN BOOLEAN MODE) and principal='S')) OR nombre LIKE '%$texto%' AND publicado='S' ORDER BY coincidencias desc;";
            //$where2.= "match(nombre) against('+$texto' IN BOOLEAN MODE) AND id_categoria IN (select id from categorias where depende in (select id from categorias ct where match(nombre) against('+$texto' IN BOOLEAN MODE) and principal='S')) OR nombre LIKE '%$texto%' AND publicado='S' ORDER BY coincidencias desc;";
            $where.=  "(publicado='S' and id_categoria IN (SELECT id from categorias ct where match(nombre) against('+$texto' WITH QUERY EXPANSION)) 
                        OR publicado='S'  AND id_categoria IN (select id from categorias ctg where depende in (select id from categorias ct where match(nombre) against('+$texto' WITH QUERY EXPANSION)))
                        OR publicado='S' AND nombre LIKE '%$texto%' ) ORDER BY coincidencias desc";
                        
            $where2.= "(publicado='S' and id_categoria IN (SELECT id from categorias ct where match(nombre) against('+$texto' WITH QUERY EXPANSION)) 
                        OR publicado='S'  AND id_categoria IN (select id from categorias ctg where depende in (select id from categorias ct where match(nombre) against('+$texto' WITH QUERY EXPANSION)))
                        OR publicado='S' AND nombre LIKE '%$texto%' ) ORDER BY coincidencias desc";
            
        }
        $rst = Doo::db()->query("select count(*) as total,id,nombre,caract,iva,precio_venta,precio_promocion,imagen2,match(nombre) against('$texto' WITH QUERY EXPANSION)  as coincidencias FROM productos where " . $where);
        $t = $rst->fetch();
        if (count($t) > 0) {
            $total = $t["total"];
        } else {
            $total = 0;
        } 
        if ($total == 0) {
            $total = 1;
        }
        Doo::loadHelper('DooPager');
        $pager = new DooPager(Doo::conf()->APP_URL."search/$texto",$total,12,10);
        if (isset($this->params['number'])) {
            $pager->paginate(intval($this->params['number']));
        } else {
            $pager->paginate(1);
        }
        $sql = "SELECT id,nombre,caract,iva,precio_venta,precio_promocion,imagen2,match(nombre) against('+$texto' WITH QUERY EXPANSION)  as coincidencias ,fecha_vencimiento FROM productos WHERE   " . $where2;
        
        //var_dump(Doo::db()->query($sql . " LIMIT $pager->limit"));
        $this->data['productos'] = Doo::db()->query($sql . " LIMIT $pager->limit")->fetchAll();
        $this->data['pager'] = $pager->output;
        $this->data['texto'] = $texto;
        $this->data['id_categoria']="";
        $this->configuracion();
        $this->buildMenu();
        $this->buildMenuV();
        $this->buildMenuH();
        $this->Banner();
        $this->ProductosPromocion();
        $this->busqueda_avanzada();
        $ruta = '<li><a href="' . Doo::conf()->APP_URL . '" title="Pagina de inicio">Inicio</a></li><li class="active"><a class="previous" title="' . $texto . '">' . $texto . '</a></li>';
        $_SESSION["stak_url"] = $ruta;
        $this->data['stak_url'] = $ruta;
        $this->data['content'] = 'page_product_search';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    function setDisponibilidades() {
        $codigo = $_POST["codigo"];
        $dp = $_POST["dispo"];
        Doo::db()->query("DELETE FROM disponibilidades WHERE codigo='$codigo'");
        foreach ($dp as $d) {
            $depd = $d["Dependencia"];
            $cnt = $d["Cantidad"];
            Doo::db()->query("INSERT INTO disponibilidades (codigo,dependencia,cantidad) VALUES ('$codigo','$depd','$cnt')");
        }
    }

    function getDisponibilidades() {
        $codigo = $_POST["codigo"];
        $lista = Doo::db()->query("SELECT dependencia,cantidad FROM disponibilidades WHERE codigo='$codigo'")->fetchAll();
        echo json_encode($lista);
    }

    // Nuevos Metodos

    public function SaveRegistro() {
        Doo::loadModel("Personas");
        $persona = new Personas($_POST);

        $persona->estado = "1";

        if ($persona->id == "") {
            $persona->id = NULL;
            $persona->estado = "1";
            $persona->rol = 4;
            Doo::db()->Insert($persona);
            ///$this->sendClient($persona);
            $this->login($persona);
            //$this->sendAdmin($cliente);
        } else {
            $sql = "update personas set nombre = '$persona->nombre', apellidos = '$persona->apellidos',"
                    . " identificacion = '$persona->identificacion', direccion = '$persona->direccion', "
                    . "telefono = '$persona->telefono', celular = '$persona->celular',"
                    . "email = '$persona->email', estado='1'   where id = $persona->id";
            $rs = Doo::db()->query($sql);
            
            print_r($rs);
            
            
            $login = new stdclass();
            $login->usuario = $persona->nombre;
            $login->apellidos = $persona->apellidos;
            $login->identificacion = $persona->identificacion;
            $login->direccion = $persona->direccion;
            $login->telefono = $persona->telefono;
            $login->email = $persona->email;
            $login->id_cliente = $persona->id;
            $login->rol = $persona->rol;
            $_SESSION['login_cliente'] = $login;
        }
        return Doo::conf()->APP_URL;
    }

    public function SavePersona() {
        Doo::loadModel("Personas");
        $persona = new Personas($_POST);

        $persona->estado = "1";

        if ($persona->id == "") {
            $persona->id = NULL;
            $persona->identificacion = $_POST["identificacion"];
            $persona->nombre = $_POST["nombre"];
            $persona->apellidos = $_POST["apellidos"];
            $persona->email = $_POST["email"];
            $persona->direccion = $_POST["direccion"];
            $persona->telefono = $_POST["telefono"];
            $persona->celular = $_POST["celular"];
            $persona->estado = "1";
            $persona->rol = 4;
            $persona->id = Doo::db()->Insert($persona);
        } else {
            $sql = "update personas set id= '$persona->id',nombre = '$persona->nombre', apellidos = '$persona->apellidos',"
                    . " identificacion = '$persona->identificacion', direccion = '$persona->direccion', "
                    . "telefono = '$persona->telefono', celular = '$persona->celular',"
                    . "email = '$persona->email', estado='1'  where id = $persona->id";
            Doo::db()->query($sql);
        }
        $this->Preview($persona->id);
    }

    public function Preview($id) {
        $this->plantilla();
        $sql = Doo::db()->query("SELECT * FROM personas WHERE id = $id")->fetch();
        $this->data["id_persona"] = $sql["id"];
        $this->data["nombre_persona"] = $sql["nombre"];
        $this->data["apellidos_persona"] = $sql["apellidos"];
        $this->data["identificacion_persona"] = $sql["identificacion"];
        $this->data["direccion_persona"] = $sql["direccion"];
        $this->data["telefono_persona"] = $sql["telefono"];
        $this->data["celular_persona"] = $sql["celular"];
        $this->data["email_persona"] = $sql["email"];
        $this->buildMenu();
        $this->configuracion();
        $this->data['content'] = 'prevcotizacion';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    public function GuardarCotizacion() {

        Doo::loadModel("Cotizacion");
        $c = new Cotizacion($_POST);

        $login = $_SESSION['login_cliente'];
        $user_id = $login->id_cliente;

        $id_persona = filter_input(INPUT_POST, "id_persona");
        $subtotal = filter_input(INPUT_POST, "subtotal");
        $total = filter_input(INPUT_POST, "total");


        if ($c->id == NULL) {
            $c->id = NULL;
            $c->subtotal = $subtotal;
            $c->total = $total;
            $c->fecha = date("Y-m-d");
            $c->estado = "1";
            $c->id_usuario = $user_id;
            $c->id_persona = $id_persona;
            $c->fecha_registro = date("Y-m-d h:i:s");

            $sql = Doo::db()->query("SELECT numero FROM cotizacion ORDER BY id DESC LIMIT 1")->fetchAll();
            if (count($sql) > 0) {
                $numero = $sql[0]["numero"];
                $numero = $numero + 1;
            } else {
                $numero = 1;
            }
            $c->numero = $numero;

            $c->id = Doo::db()->insert($c);
        } else {
            //$c->fecha_registro = date("Y-m-d h:i:s");
            Doo::db()->Update($c);
        }

        if (isset($_SESSION["carrito"])) {
            $array = unserialize($_SESSION["carrito"]);

            Doo::loadModel("CotizacionDetalle");
            foreach ($array as $a) {
                if ($a["id_cotizacion"] == "") {
                    $s = new CotizacionDetalle();
                    $s->id_cotizacion = $c->id;
                    $s->id_prod = $a["id"];
                    $s->cod_prod = $a["codigo"];
                    $s->nombre_prod = $a["nombre"];
                    $s->cantidad = $a["cantidad"];
                    $s->valor = $a["valor"];
                    $s->id_usuario = $user_id;
                    $s->id = Doo::db()->insert($s);
                } else {
                    $cantidad = $a["cantidad"];
                    $items = $a['id'];
                    Doo::db()->query("UPDATE cotizacion_detalle SET cantidad=$cantidad WHERE id_prod = $items");
                }
            }
        }
        if (isset($_SESSION["items_detalles_del"])) {
            $itemsBorrar = unserialize($_SESSION["items_detalles_del"]);
            foreach ($itemsBorrar as $i) {
                $id = $i['id'];
                Doo::db()->query("DELETE FROM cotizacion_items_tasas  WHERE id_tasa = $id ");
            }
            $_SESSION["items_detalles_del"] = null;
        }
        //echo $c->id;
        $this->generarPDFCotizacion($c->numero, $c->id);
        $_SESSION['carrito'] = NULL;
        //return Doo::conf()->APP_URL . "estimates";
    }

    // Crear un PDF de cotizacion Y guardarlo en el servidor
    public function generarPDFCotizacion($numero, $id) {
        if (isset($_SESSION["carrito"])) {
            $array = unserialize($_SESSION["carrito"]);
        } else {
            $array = array();
        }

        //Doo::loadClass("pdf/fpdf");
        Doo::loadClass("pdf/PDF_ImageAlpha");
        Doo::loadClass("reportes/ReporteCotizacion");
        $pdf = new ReporteCotizacion();
        $pdf->AliasNbPages();
        $pdf->AddPage();
        $pdf->body($id, $array);
        $pdf->Output('global/documentos/pdf_cotizacion/Cotizacion_N_' . $numero . '.pdf', 'F');
        $this->SendCotizacionemail($id, $numero);
    }

    // Envio del PDF de cotizacion por Email
    public function SendCotizacionemail($id, $numero) {

        $sql = Doo::db()->query("SELECT p.nombre,p.apellidos,p.identificacion,
            p.direccion,p.telefono,p.celular,p.email,c.`fecha_registro`,c.numero
        FROM cotizacion c
        INNER JOIN personas p
        ON (c.`id_persona`= p.`id`)
        WHERE c.`id` = $id")->fetchAll();

        $email = $sql[0]["email"];

        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        $mail->addTo($email);
        $mail->setSubject('Cotizacion N°' . $numero . ' [Computerworking]');
        $mail->setBodyHtml("");
        $mail->setFrom('soporte@computerworking.com.co', 'Computer Working');
        //echo "Mensaje Enviado con Exito";
        $mail->addAttachment('global/documentos/pdf_cotizacion/Cotizacion_N_' . $numero . '.pdf');
        $mail->send();
    }

    // Iprimir Carrito de Cotizacion (PDF)
    public function imprimirCotizacion() {
        $id = $this->params["pindex"];

        if (isset($_SESSION["carrito"])) {
            $array = unserialize($_SESSION["carrito"]);
        } else {
            $array = array();
        }

        Doo::loadClass("pdf/fpdf");
        Doo::loadClass("pdf/PDF_ImageAlpha");
        Doo::loadClass("reportes/ReporteCotizacion");
        $pdf = new ReporteCotizacion();
        $pdf->AliasNbPages();
        $pdf->AddPage();
        $pdf->body($id, $array);
        ob_end_clean();
        $pdf->Output();
    }

    // Crear un PDF Y guardarlo en el servidor
    public function generarPDF($id) {
        if (isset($_SESSION["carrito"])) {
            $array = unserialize($_SESSION["carrito"]);
        } else {
            $array = array();
        }

        Doo::loadClass("pdf/PDF_ImageAlpha");
        Doo::loadClass("reportes/ImprimirCarrito");
        $pdf = new ImprimirCarrito();
        $pdf->AliasNbPages();
        $pdf->AddPage();
        $pdf->body($array);
        $pdf->Output('global/documentos/pdf_carrito_compra/CarritoCompra_' . $id . '.pdf', 'F');
    }

    public function SendCarritoemail() {
        $login = $_SESSION['login_cliente'];
        $id = $login->id_cliente;
        
        $this->generarPDF($id);

        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        $mail->addTo($_POST["email"]);
        $mail->setSubject('Carrito de Compras [Computer Working]');
        $mail->setBodyHtml("");
        $mail->setFrom('ventas4@compuworking.com.co', 'Computer Working');
        //echo "Mensaje Enviado con Exito";
        $mail->addAttachment('global/documentos/pdf_carrito_compra/CarritoCompra_' . $id . '.pdf');
        $mail->send();
        
        var_dump($_POST["email"]);
    }
    public function SendPQR() {      
        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        $mail->addTo("ventas4@compuworking.com.co");
        $mail->setSubject('DUDAS O COMENTARIOS');
        $mail->setBodyHtml("Nombre: $_POST[nombre]<br/>Telefono: $_POST[telefono]<br/>Correo: $_POST[NOMBRE]<br/>Requerimiento: $_POST[req]<br/>");
        $mail->setFrom('ventas4@compuworking.com.co', 'Computer Working');
        $mail->send();
    }

    public function validarRegistro() {
        $identificacion = $_POST["identificacion"];
        $email = $_POST["email"];
        $id = $_POST["id"];
        $count = Doo::db()->query("SELECT * FROM personas where identificacion = '$identificacion' OR email = '$email' AND id <> '$id' ")->rowCount();
        if ($count > 0) {
            echo true;
        } else {
            echo false;
        }
    }
    
    public function validarRegistro2() {
        $identificacion = $_POST["identificacion"];
        $email = $_POST["email"];
        $id = $_POST["id"];
        $count = Doo::db()->query("SELECT * FROM personas where identificacion = '$identificacion' AND email = '$email' AND id <> '$id' ")->rowCount();
        if ($count > 0) {
            echo true;
        } else {
            echo false;
        }
    }

    // Pagina de Iniciar Sesion
    public function IniciarSesion() {
        $this->buildMenu();
        $this->buildMenuH();
        $this->busqueda_avanzada();
        $this->configuracion();
        $this->data['content'] = 'login';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    // Pagina de Recuperar Contraseña
    public function PageRecuperar() {
        $this->buildMenu();
        $this->buildMenuH();
        $this->busqueda_avanzada();
        $this->configuracion();
        $this->data['content'] = 'recuperar';
        $this->data['rootUrl'] = Doo::conf()->APP_URL;
        $this->renderc('home', $this->data, true);
    }

    // Login Automatico con Registro
    public function login() {
        if (isset($_POST['email']) && isset($_POST['identificacion'])) {
            if (!empty($_POST['email']) && !empty($_POST['identificacion'])) {
                $user = trim($_POST['email']);
                $pass = trim($_POST['identificacion']);
                $u = $this->db()->find("Personas", array("where" => "email = ? and identificacion = ?", "limit" => 1, "param" => array($user, $pass)));
                $this->data['rootUrl'] = Doo::conf()->APP_URL;

                if ($u == Null) { // o $u == false
                    $this->data['error'] = "Acceso denegado";
                    return Doo::conf()->APP_URL . 'login';
                } else {
                    unset($_SESSION['login_cliente']);
                   
                    $login = new stdclass();
                    $login->usuario = $u->nombre;
                    $login->apellidos = $u->apellidos;
                    $login->identificacion = $u->identificacion;
                    $login->direccion = $u->direccion;
                    $login->telefono = $u->telefono;
                    $login->email = $u->email;
                    $login->id_cliente = $u->id;
                    $login->rol = $u->rol;
                    $_SESSION['login_cliente'] = $login;
                    if (isset($_SESSION["carrito"])) {
                        return Doo::conf()->APP_URL . 'ver_carro';
                    }else{
                        return Doo::conf()->APP_URL;
                    }
                    
                }
            } else {
                return Doo::conf()->APP_URL . 'login';
            }
        } else {
            return Doo::conf()->APP_URL . 'login';
        }
    }

    // Login Automatico con Registro
    public function loginUsuario() {
        if (isset($_POST['email']) && isset($_POST['password'])) {
            if (!empty($_POST['email']) && !empty($_POST['password'])) {
                $user = trim($_POST['email']);
                $pass = md5(trim($_POST['password']));
                $u = $this->db()->find("Usuarios", array("where" => "usuario = ? and password = ?", "limit" => 1, "param" => array($user, $pass)));


                $this->data['rootUrl'] = Doo::conf()->APP_URL;

                if ($u == Null) { // o $u == false
                    $this->data['error'] = "Acceso denegado";
                    return Doo::conf()->APP_URL . 'iniciarsesion';
                } else {
                    unset($_SESSION['login_cliente']);

                    $id = $u->id_persona;
                    
                    $p = $this->db()->find("Personas", array("where" => "id = ?", "limit" => 1, "param" => array($id)));

                    $login = new stdclass();
                  
                    $login->usuario = $p->nombre;
                    $login->apellidos = $p->apellidos;
                    $login->identificacion = $p->identificacion;
                    $login->direccion = $p->direccion;
                    $login->telefono = $p->telefono;
                    $login->celular = $p->celular;
                    $login->email = $p->email;
                    $login->id_cliente = $u->id_persona;
                    $login->rol = $u->role;
                    $_SESSION['login_cliente'] = $login;

                    if (isset($_SESSION["carrito"])) {
                        return Doo::conf()->APP_URL . 'ver_carro';
                    }else{
                        return Doo::conf()->APP_URL;
                    }
                }
            } else {
                return Doo::conf()->APP_URL . 'iniciarsesion';
            }
        } else {
            return Doo::conf()->APP_URL . 'iniciarsesion';
        }
    }

    public function logout() {
        $_SESSION['login_cliente'] = NULL;
        //session_unset();
        // Destruir la session PHP
        //session_destroy();
        // retornar al sitio de inicio
        return Doo::conf()->APP_URL;
    }

    public function plantilla() {
        $sql = "SELECT id,nombre,fondo_pagina,footer_1,footer_2,footer_3,footer_4,title_fot_1,title_fot_2,title_fot_3,title_fot_4 from plantilla where estado=1";
        $rs = Doo::db()->query($sql)->fetch();
        $this->data['planti'] = $rs;
    }
    
    

    public function sendClient($persona) {
        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        $msj = "<html xmlns='http://www.w3.org/1999/xhtml'>
    <head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Compuworking</title>

    <style type='text/css'>
        .ReadMsgBody {width: 100%; background-color: #ffffff;}
        .ExternalClass {width: 100%; background-color: #ffffff;}
        body     {width: 100%; background-color: #ffffff; margin:0; padding:0; -webkit-font-smoothing: antialiased;font-family: Arial, Helvetica, sans-serif}
        table {border-collapse: collapse;}

        @media only screen and (max-width: 640px)  {
                        body[yahoo] .deviceWidth {width:440px!important; padding:0;}
                        body[yahoo] .center {text-align: center!important;}
                }

        @media only screen and (max-width: 479px) {
                        body[yahoo] .deviceWidth {width:280px!important; padding:0;}
                        body[yahoo] .center {text-align: center!important;}
                }
    </style>
    </head>
    <body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0' yahoo='fix' style='font-family: Arial, Helvetica, sans-serif'>
    <table width='100%' border='0' cellpadding='0' cellspacing='0' align='center'>
        <tr>
            <td width='100%' valign='top' bgcolor='#ffffff' style='padding-top:20px'>
            <table width='700' bgcolor='#fff' border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                <tr bgcolor='#3C8DBC'>
                    <td style='padding: 6px 0px 0px'>
                        <table width='650' border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                            <tr>
                                <td width='100%' >
                                    <table  border='0' cellpadding='0' cellspacing='0' align='left' class='deviceWidth'>
                                        <tr>
                                            <td class='center' style='padding: 20px 0px 10px 0px'>
                                                <h1 style='color: #fff;'>Compuworking</h1>
                                            </td>
                                        </tr>
                                    </table>
                                </td>
                            </tr>
                        </table>
                   </td>
                </tr>
            </table>
                <table width='700' border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                    <tr>
                        <td width='100%' valign='top' style='padding: 0px ' class='center'>
                          <br/>
                            <h2 style='text-align:center;'>¡Gracias por usar Compuworking para sus compras!</h2>
                            <h4>Hola, " . $_POST['nombre'] . ", ¡bienvenido! </h4>
                        </td>
                    </tr>
                </table>
                <table width='700' border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                    <tr>
                        <td width='100%' style=' padding: 20px 0;' align='center' bgcolor='#f7f7f7'>
                            <table   border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                                <tr>
                                    <td valign='top' class='left' style='font-size: 16px; color: #303030; font-weight: bold; text-align: center; font-family: Arial, Helvetica, sans-serif; line-height: 25px; vertical-align: middle; padding: 0 20px 10px 20px;'>
                                      Te agradecemos que hayas confiado en nosotros para realizar tus compras.
                                      En Compuworking encuentras un mundo de tecnologia.
                                      <br/>
                                      Tu usuario para acceder:
                                      <br/>
                                      Email:" . $_POST["email"] . "
                                       <br/>
                                       Password:" . $_POST["identificacion"] . "
                                    </td>
                                </tr>
                            </table>
                            <table>
                                <tbody><tr>
                                    <td valign='top' style='padding: 7px 15px;  background-color: #3498db; ' class='center'>
                                        <a style='color: #fff; font-size: 12px; font-weight: bold; text-decoration: none; font-family: Arial, sans-serif; text-alight: center;' href='http://computerworking.com.co'>Acceder</a>
                                    </td>
                                 </tr>
                            </tbody>
                          </table>
                        </td>
                    </tr>
                </table>
                <table width='700'  border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                      <tr>
                        <td class='center' style='font-size: 12px; color: #687074; font-weight: bold; text-align: center; font-family: Arial, Helvetica, sans-serif; line-height: 25px; vertical-align: middle; padding: 20px 50px 0px 50px; '>
                            Copyright © Compuworking 2016
                        </td>
                    </tr>
                </table>
                <div style='height:15px'>&nbsp;</div>
            </td>
        </tr>
    </table>
    </body>
    </html>";
        $mail->addTo($_POST['email']);
        $mail->setSubject('[Computer Working]');
        $mail->setBodyHtml($msj);
        $mail->setFrom('soporte@computerworking.com.co');
        $mail->send();
    }

    public function generarCodigo($longitud) {
        $key = '';
        $pattern = '1234567890abcdefghijklmnopqrstuvwxyz';
        $max = strlen($pattern) - 1;
        for ($i = 0; $i < $longitud; $i++)
            $key .= $pattern[mt_rand(0, $max)];
        return $key;
    }

    public function recuperar() {
        $email = $_POST["email"];
        $newpas = $this->generarCodigo(8);
        Doo::db()->query("UPDATE usuarios SET PASSWORD = MD5('$newpas') WHERE usuario='$email'");
        $this->data['emailrecuperar'] = $email;
        echo $email;


        $msj = "<html xmlns='http://www.w3.org/1999/xhtml'>
    <head>
    <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
    <title>Computerworking S.A.S - Trabajamos Por tu Futuro</title>

    <style type='text/css'>
        .ReadMsgBody {width: 100%; background-color: #ffffff;}
        .ExternalClass {width: 100%; background-color: #ffffff;}
        body     {width: 100%; background-color: #ffffff; margin:0; padding:0; -webkit-font-smoothing: antialiased;font-family: Arial, Helvetica, sans-serif}
        table {border-collapse: collapse;}

        @media only screen and (max-width: 640px)  {
                        body[yahoo] .deviceWidth {width:440px!important; padding:0;}
                        body[yahoo] .center {text-align: center!important;}
                }

        @media only screen and (max-width: 479px) {
                        body[yahoo] .deviceWidth {width:280px!important; padding:0;}
                        body[yahoo] .center {text-align: center!important;}
                }
    </style>
    </head>
    <body leftmargin='0' topmargin='0' marginwidth='0' marginheight='0' yahoo='fix' style='font-family: Arial, Helvetica, sans-serif'>
    <table width='100%' border='0' cellpadding='0' cellspacing='0' align='center'>
        <tr>
            <td width='100%' valign='top' bgcolor='#ffffff' style='padding-top:20px'>
            <table width='700' bgcolor='#fff' border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                <tr bgcolor='#f7f7f7'>
                    <td style='padding: 6px 0px 0px'>
                        <table width='650' border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                            <tr>
                                <td width='100%' >
                                    <table  border='0' cellpadding='0' cellspacing='0' align='left' class='deviceWidth'>
                                        <tr>
                                            <td class='center' style='padding: 20px 0px 10px 0px'>
                                                <a href='#'><img src='http://www.computerworking.com.co/global/img/logo.png'></a>
                                            </td>
                                        </tr>
                                    </table>
                                    <table  border='0' cellpadding='0' cellspacing='0' align='right' class='deviceWidth'>
                                        <tr>
                                            <td  class='center' style='font-size: 13px; color: #272727; font-weight: light; text-align: center; font-family: Arial, Helvetica, sans-serif; line-height: 25px; vertical-align: middle; padding: 20px 0px 10px 0px;'>
                                                <a href='#' style='text-decoration: none; color: #3b3b3b;'>T&eacute;rminos y Condiciones</a>
                                                &nbsp; &nbsp;
                                                <a href='#' style='text-decoration: none; color: #3b3b3b;'>Guia R&aacute;pida</a>
                                                &nbsp; &nbsp;
                                                <a href='http://www.computerworking.com.co' style='text-decoration: none; color: #3b3b3b;'>Soporte</a>
                                                &nbsp; &nbsp;
                                           </td>
                                        </tr>
                                    </table><!--End nav-->
                                </td>
                            </tr>
                        </table>
                   </td>
                </tr>
            </table>
                <table width='700' border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                    <tr>
                        <td width='100%' style=' padding: 20px 0;' align='center' bgcolor='#f7f7f7'>
                            <table   border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                                <tr>
                                    <td valign='top' class='left' style='font-size: 16px; color: #303030; font-weight: bold; text-align: center; font-family: Arial, Helvetica, sans-serif; line-height: 25px; vertical-align: middle; padding: 0 20px 10px 20px;'>
                                         Recuperaci&oacute;n de contrase&ntilde;a
                                    </td>
                                </tr>
                                <tr>
                                    <td valign='top' class='left' style='font-size: 16px; color: #303030;  text-align: center; font-family: sans-serif; line-height: 25px; vertical-align: middle; padding: 0 20px 10px 20px;'>
                                         
                                    </td>
                                </tr>
                                <tr>
                                    <td valign='top' class='left' style='font-size: 20px; color: #303030; font-weight: bold; text-align: center; font-family: Arial, Helvetica, sans-serif; line-height: 25px; vertical-align: middle; padding: 0 20px 10px 20px;'>
                                      <br/>
                                         Tu Nueva Contrase&ntilde;a es : " . $newpas . "
                                    </td>
                                </tr>
                                <tr>
                                    <td valign='top' class='left' style='font-size: 16px; color: #303030;  text-align: center; font-family: sans-serif; line-height: 25px; vertical-align: middle; padding: 0 20px 10px 20px;'>
                                         <b>Ingresa al link: </b> <a style='text-decoration: none'; href='http://www.computerworking.com.co/iniciarsesion'>http://www.computerworking.com.co/iniciarsesion</a>
                                    </td>
                                </tr>
                               
                                <tr>
                                  <td class='center' style='font-size: 12px; color: #303030; font-weight: bold; text-align: center; font-family: Arial, Helvetica, sans-serif; line-height: 25px; vertical-align: middle; padding: 20px 50px 0px 50px; '>
                                      *Recuerda por seguridad Cambiar la contrase&ntilde;a
                                  </td>
                              </tr>
                            </table>
                        </td>
                    </tr>
                </table>
                <table width='700'  border='0' cellpadding='0' cellspacing='0' align='center' class='deviceWidth'>
                      <tr>
                        <td class='center' style='font-size: 12px; color: #687074; font-weight: bold; text-align: center; font-family: Arial, Helvetica, sans-serif; line-height: 25px; vertical-align: middle; padding: 20px 50px 0px 50px; '>
                            Copyright © Computerworking 2016
                        </td>
                    </tr>
                </table>
                <div style='height:15px'>&nbsp;</div>
            </td>
        </tr>
    </table>
    </body>
    </html>";
        Doo::loadHelper('DooMailer');
        $mail = new DooMailer();
        $mail->addTo($email);
        $mail->setSubject('[Computerworking - Cambio contraseña');
        $mail->setBodyHtml($msj);
        $mail->setFrom('soporte@computerworking.com.co');
        $mail->send();
    }

}

?>





* Stack Trace...

  1. /home/computer/public_html/index.php(27) calling run()
  2. /home/computer/public_html/dooframework/app/DooWebApp.php(34) calling routeTo()
  3. /home/computer/public_html/dooframework/app/DooWebApp.php(117) calling getCategorias()


* Variables...  Conf .  GET  .  POST  .  Session  .  Cookie 

<?php //tempstart
object(DooConfig)#1 (33) {
  ["AUTOLOAD"]=>
  NULL
  ["SITE_PATH"]=>
  string(27) "/home/computer/public_html/"
  ["PROTECTED_FOLDER"]=>
  string(10) "protected/"
  ["BASE_PATH"]=>
  string(40) "/home/computer/public_html/dooframework/"
  ["LOG_PATH"]=>
  NULL
  ["APP_URL"]=>
  string(32) "https://www.compuworking.com.co/"
  ["SUBFOLDER"]=>
  string(1) "/"
  ["APP_MODE"]=>
  string(4) "prod"
  ["AUTOROUTE"]=>
  bool(true)
  ["DEBUG_ENABLED"]=>
  bool(true)
  ["ERROR_404_DOCUMENT"]=>
  NULL
  ["ERROR_404_ROUTE"]=>
  string(6) "/error"
  ["CACHE_PATH"]=>
  NULL
  ["AUTO_VIEW_RENDER_PATH"]=>
  string(22) "/categorias/:id_cat/:p"
  ["MEMCACHE"]=>
  NULL
  ["TEMPLATE_ENGINE"]=>
  string(7) "DooView"
  ["TEMPLATE_SHOW_COMMENT"]=>
  NULL
  ["TEMPLATE_ALLOW_PHP"]=>
  NULL
  ["TEMPLATE_COMPILE_ALWAYS"]=>
  NULL
  ["TEMPLATE_GLOBAL_TAGS"]=>
  NULL
  ["MODULES"]=>
  NULL
  ["APP_NAMESPACE_ID"]=>
  NULL
  ["RELATIVE_IMG_DIR"]=>
  string(13) "/uploads/img/"
  ["IMG_DIR"]=>
  string(39) "/home/computer/public_html/uploads/img/"
  ["IMG_DIRPR"]=>
  string(40) "/home/computer/public_html//img_product/"
  ["FILE_DIR"]=>
  string(34) "/home/computer/public_html//files/"
  ["PRODU_DIR"]=>
  string(38) "/home/computer/public_html//productos/"
  ["IMG_CATEGORIA"]=>
  string(43) "/home/computer/public_html//img_categorias/"
  ["DIR_INTERFACE"]=>
  string(13) "179.50.53.114"
  ["TEMPLATE"]=>
  string(8) "deepBlue"
  ["TEMPLATE2"]=>
  string(6) "custom"
  ["TITLE"]=>
  string(45) "Compuworking S.A.S - Trabajamos Por tu Futuro"
  ["HEADER"]=>
  string(6) "header"
}

<?php //tempstart
array(0) {
}

<?php //tempstart
array(0) {
}


BACK TO TOP