Ejemplo n.º 1
0
 /**
  * Método Fábrica para a abertura de pedidos
  * Cobre as seguintes regras de negócio
  * CC02, CC04
  * @param CWebUser $user
  * @return Pedido $pedido
  */
 public static function open(Cliente $cliente = null)
 {
     $today_date = date("Y-m-d H:i:s", time());
     $session_id = Yii::app()->getSession()->getSessionID();
     $pedido = Pedido::model()->find("id_session= '{$session_id}' AND status='ABERTO'");
     if (count($pedido) > 0 && !is_null($cliente)) {
         $pedido->setAttribute('id_cliente', $cliente->getPrimaryKey());
         $pedido->save();
     } else {
         if (is_null($cliente) && !count($pedido) > 0) {
             $pedido = new Pedido();
             $pedido->setAttribute("id_session", $session_id);
             $pedido->setAttribute("create_date", date("Y-m-d H:i:s"));
             $pedido->setAttribute("status", "ABERTO");
             $pedido->save();
         } else {
             if (!count($pedido) > 0 && !is_null($cliente)) {
                 // @todo Projetar query para calcular timestamp em total de horas
                 $pedido = Pedido::model()->find("id_cliente= '{$cliente->getPrimaryKey()}' AND DATE(create_date)= DATE('{$today_date}') AND status='ABERTO'");
                 if (!count($pedido) > 0) {
                     $pedido = new Pedido();
                     $pedido->setAttribute("id_session", $session_id);
                     $pedido->setAttribute("id_cliente", $cliente->getPrimaryKey());
                     $pedido->setAttribute("create_date", date("Y-m-d H:i:s"));
                     $pedido->setAttribute("status", "ABERTO");
                     $pedido->save();
                 }
             }
         }
     }
     return $pedido;
 }
 public function store()
 {
     $user = User::findOrFail(Input::get('cliente_id'));
     $input = Input::all();
     $pedido = new Pedido();
     $pedido->cliente_id = $user->id;
     $pedido->nome = $user->nome;
     $pedido->email = $user->email;
     $pedido->pedido_status_id = $input['status'];
     $produtos = $input['produtos'];
     foreach ($produtos as $id => $produto) {
         $pedido_itens[][63] = array('nome_br' => $produto['nome'], 'nome_en' => $produto['nome'], 'preco' => $produto['preco'], 'tipo' => '', 'quantidade' => $produto['quantidade']);
         $pedido->total += $produto['preco'] * $produto['quantidade'];
     }
     $pedido->save();
     $historico = new PedidoHistorico();
     $historico->pedido_id = $pedido->id;
     $historico->pedido_status_id = 12;
     $historico->save();
     if (isset($pedido_itens)) {
         foreach ($pedido_itens as $key => $iten) {
             $pedido->produtos()->attach($iten);
         }
     }
     return Redirect::to("admin/pedido/{$pedido->id}/edit")->with('success', array('Pedido gerado com produtos personalizados.'));
 }
 /**
  * Creates a new model.
  * If creation is successful, the browser will be redirected to the 'view' page.
  */
 public function actionCreate()
 {
     $model = new Pedido();
     // Uncomment the following line if AJAX validation is needed
     // $this->performAjaxValidation($model);
     if (isset($_POST['Pedido'])) {
         $model->attributes = $_POST['Pedido'];
         if ($model->save()) {
             $this->redirect(array('view', 'id' => $model->pedido_id));
         }
     }
     $this->render('create', array('model' => $model));
 }
 public function actionFinalizarPedido()
 {
     $this->layout = 'sitio';
     if (isset($_SESSION['Cliente'])) {
         if (count($_SESSION['carro']) > 0) {
             $pedido = new Pedido();
             $direccion = Direccion::model()->with('comuna')->findByPk($_POST['Pedido']['direcciones']);
             $formaPago = FormaPago::model()->findByPk($_POST['Pedido']['formaPago']);
             $tipoDocumento = TipoDocumento::model()->findByPk($_POST['Pedido']['tiposDocumento']);
             $pedido->pedido_fecha = new CDbExpression('NOW()');
             $pedido->pedido_cliente_nombre = $_SESSION['Cliente']['cliente_nombre'];
             $pedido->pedido_cliente_direccion = $direccion->direccion_descripcion;
             $pedido->pedido_cliente_comuna = $direccion->comuna->comuna_nombre;
             $pedido->pedido_cliente_telefono = $_SESSION['Cliente']['cliente_telefono'];
             $pedido->pedido_cliente_telefono_movil = $_SESSION['Cliente']['cliente_telefono_movil'];
             $pedido->pedido_total = $_SESSION['total_carro'];
             $pedido->cliente_id = $_SESSION['Cliente']['cliente_id'];
             $pedido->forma_pago_id = $formaPago->forma_pago_id;
             $pedido->tipo_documento_id = $tipoDocumento->tipo_documento_id;
             if ($pedido->save()) {
                 Yii::app()->user->setFlash('pedidoRealizadoCorrecto', "¡Gracias por comprar!<br/>Tu pedido es el número: #" . str_pad($pedido->pedido_id, 10, "0", STR_PAD_LEFT) . "<br />Recibirás un e-mail con los detalles de tu pedido.");
                 foreach ($_SESSION['carro'] as $key => $producto) {
                     $pedidoDetalle = new PedidoDetalle();
                     $pedidoDetalle->producto_codigo = $producto['producto_codigo'];
                     $pedidoDetalle->pedido_detalle_descripcion = $producto['producto_nombre'];
                     $pedidoDetalle->pedido_detalle_precio = $producto['producto_precio'];
                     $pedidoDetalle->pedido_detalle_cantidad = $producto['producto_cantidad'];
                     $pedidoDetalle->pedido_detalle_total = $producto['producto_precio'] * $producto['producto_cantidad'];
                     $pedidoDetalle->pedido_id = $pedido->pedido_id;
                     $pedidoDetalle->producto_id = $producto['producto_id'];
                     $pedidoDetalle->save();
                 }
                 unset($_SESSION['carro']);
                 $_SESSION['carro'] = array();
             } else {
                 //echo "<pre>"; print_r($pedido->getErrors()); echo "</pre>";
                 Yii::app()->user->setFlash('pedidoRealizadoError', "No es posible realizar tu pedido en este momento, favor intenta más tarde.");
             }
         } else {
             Yii::app()->user->setFlash('pedidoCarroVacio', "No es posible realizar tu pedido en este momento, agrega productos a tu carro.");
         }
     }
     $this->render('finalizarPedido');
 }
Ejemplo n.º 5
0
 public static function agregarPedido($numero, $nivel, $de, $seccion, $al_almacen, $para_uso, $pedido_por, $cargo_pedido_por, $aprobado_por, $cargo_aprobado_por, $autorizado_por, $cargo_autorizado_por, $referencia)
 {
     $p = new Pedido();
     $p->numero = $numero;
     $p->nivel = Session::get('nivel');
     $p->de = $de;
     $p->seccion = $seccion;
     $p->fecha = Pedidocompra::cambiarfecha();
     $p->al_almacen = $al_almacen;
     $p->para_uso_en = $para_uso;
     $p->pedido_por = $pedido_por;
     $p->cargo_pedido_por = $cargo_pedido_por;
     $p->aprobado_por = $aprobado_por;
     $p->cargo_aprobado_por = $cargo_aprobado_por;
     $p->autorizado_por = $autorizado_por;
     $p->cargo_autorizado_por = $cargo_autorizado_por;
     $p->referencia = $referencia;
     $p->confirmado = false;
     $p->save();
 }
 public function guardarPedidoCallCenter()
 {
     $responseCode = self::SUCCESS;
     $response = array();
     try {
         $data = Input::all();
         $pedido = new Pedido();
         $pedido->cliente = $data["cliente"];
         $pedido->creado_por = $data["creado_por"];
         $pedido->direccion_entrega = $data["direccion_entrega"];
         $pedido->nombre_recibe = $data["nombre_recibe"];
         $pedido->call_center = $data["call_center"];
         $pedido->status = $data["status"];
         $pedido->save();
         $response["id_pedido"] = $pedido->id;
     } catch (\Exception $ex) {
         Log::error($ex);
         $responseCode = self::FAIL;
     }
     $response["responseCode"] = $responseCode;
     return $response;
 }
Ejemplo n.º 7
0
 public static function Ajax($param)
 {
     switch ($param) {
         case 'confirm':
             // All method
             $pedido = Input::get('list');
             $x = new Pedido();
             $x->id = self::random();
             $x->user_id = User::AboutMe()->id;
             $x->user_data = User::AboutMe()->toJson();
             $x->pedido_data = self::ArrayToJSON($pedido);
             if ($x->save()) {
                 echo "true";
             } else {
                 echo "false";
             }
             // All method end
             break;
         default:
             # code...
             break;
     }
 }
Ejemplo n.º 8
0
 public function guardarPedido()
 {
     if (Request::ajax()) {
         $num_productos = count(Input::get('codigos'));
         $codigos = Input::get('codigos');
         $cantidades = Input::get('cantidades');
         $unidadManejo = Input::get('unidadManejo');
         $n_pedido = $this->tomarNumPedido();
         $pedido = new Pedido();
         $pedido->sede_id = Auth::user()->sede_id;
         $pedido->NumeroPedido = $n_pedido;
         $pedido->CodigoCliente = Auth::user()->Codigo_Cliente;
         $pedido->DescuentoNegociado = 0;
         $pedido->Status = 'PENDIENTE';
         $pedido->Enviado = 0;
         $pedido->save();
         /*$id_pedido = DB::table('pedidos')
                   ->insertGetId($nuevo_pedido);
           */
         $id_pedido = $pedido->id;
         if ($id_pedido) {
             for ($i = 0; $i < $num_productos; $i++) {
                 $producto = DB::table('productos')->where('Codigo', '=', $codigos[$i])->first();
                 $decremento = $cantidades[$i] * $unidadManejo[$i];
                 DB::table('inventarios')->where('user_id', '=', Auth::user()->id)->where('Codigo', '=', $codigos[$i])->decrement('Existencia', $decremento);
                 $detalle = new Detalle();
                 $detalle->pedido_id = $id_pedido;
                 $detalle->producto_id = $producto->id;
                 $detalle->Cantidad = $cantidades[$i];
                 $detalle->DescuentoNegociado = 0;
                 $detalle->save();
             }
             return Response::json(array("guardado" => true, "pedido_id" => $id_pedido));
         }
     }
 }
Ejemplo n.º 9
0
 public function actionAjaxSave()
 {
     if (Yii::app()->request->isAjaxRequest) {
         if (!$this->validaSituacao()) {
             echo false;
             Yii::app()->end();
         }
         $model = new Pedido();
         $model->_pizzas = isset($_POST['arrayPizza']) ? $_POST['arrayPizza'] : array();
         $model->_combinados = isset($_POST['arrayCombinado']) ? $_POST['arrayCombinado'] : array();
         $model->_produtos = isset($_POST['arrayProduto']) ? $_POST['arrayProduto'] : array();
         $model->_promocoes = isset($_POST['arrayPromocao']) ? $_POST['arrayPromocao'] : array();
         $model->attributes = $_POST['arrayPedido'];
         if (!Yii::app()->user->isGuest) {
             $model->usuario_id = Yii::app()->user->id;
         }
         $saved = $model->save() ? $model->codigo : false;
         echo $saved;
         Yii::app()->end();
     } else {
         throw new CHttpException(400);
     }
 }
 public function pedidoexistente($id)
 {
     if ($id == 0) {
         $idpro = json_decode(Input::get('aInfo'));
         $formapago = Input::get('formapago');
         $msjeria = Input::get('msjeria');
         $cotizar = Input::get('cotizar');
         $idusuario = Auth::user()->id;
         $resp = DB::table('cliente')->where('usuario_id', $idusuario)->pluck('id');
         $clienteformapago = new ClienteFormaPago();
         $clienteformapago->cliente_id = $resp;
         $clienteformapago->forma_pago_id = $formapago;
         $clienteformapago->save();
         $mensajeria = new Mensajeria();
         $mensajeria->id = Input::get('id');
         $mensajeria->nombre = $msjeria;
         $mensajeria->save();
         $pedido = new Pedido();
         $pedido->cliente_id = $resp;
         $pedido->mensajeria_id = $mensajeria['id'];
         $pedido->direccion_cliente_id = " ";
         $pedido->forma_pago_id = $formapago;
         $pedido->num_pedido = date('Y') . date('m') . date("d") . $resp . $mensajeria['id'];
         $pedido->fecha_registro = date('Y-m-d');
         $pedido->cotizar_envio = $cotizar;
         $pedido->observaciones = " ";
         $pedido->save();
         for ($i = 0; $i < count($idpro); $i++) {
             $p_detalle = new PedidoDetalle();
             $p_detalle->pedido_id = $pedido['id'];
             $p_detalle->producto_id = $idpro[$i]->idp;
             $p_detalle->cantidad = $idpro[$i]->cant;
             $p_detalle->save();
         }
     } else {
         $idpro = json_decode(Input::get('aInfo'));
         $idusuario = Auth::user()->id;
         $resp = DB::table('cliente')->where('usuario_id', $idusuario)->pluck('id');
         $formapago = Input::get('formapago');
         $msjeria = Input::get('msjeria');
         $cotizar = Input::get('cotizar');
         $clienteformapago = new ClienteFormaPago();
         $clienteformapago->cliente_id = $resp;
         $clienteformapago->forma_pago_id = $formapago;
         $clienteformapago->save();
         $mensajeria = new Mensajeria();
         $mensajeria->id = Input::get('id');
         $mensajeria->nombre = $msjeria;
         $mensajeria->save();
         $pedido = new Pedido();
         //$pedido->id = Input::get('id');
         $pedido->cliente_id = $resp;
         $pedido->mensajeria_id = $mensajeria['id'];
         $pedido->direccion_cliente_id = $id;
         $pedido->forma_pago_id = $formapago;
         $pedido->num_pedido = date('Y') . date('m') . date("d") . $mensajeria['id'] . $resp;
         $pedido->fecha_registro = date('Y-m-d');
         $pedido->cotizar_envio = $cotizar;
         $pedido->observaciones = " ";
         $pedido->save();
         for ($i = 0; $i < count($idpro); $i++) {
             $p_detalle = new PedidoDetalle();
             $p_detalle->pedido_id = $pedido['id'];
             $p_detalle->producto_id = $idpro[$i]->idp;
             $p_detalle->cantidad = $idpro[$i]->cant;
             $p_detalle->save();
         }
     }
     return Response::json($pedido['id']);
 }
Ejemplo n.º 11
0
 public function getFinalizar()
 {
     if (Auth::check()) {
         if (Session::has('carrinho')) {
             $carrinho = Session::get('carrinho');
             if (count($carrinho) > 0) {
                 $user = Auth::user();
                 $pedido = new Pedido();
                 $pedido->cliente_id = $user->id;
                 $pedido->nome = $user->nome;
                 $pedido->email = $user->email;
                 $pedido->pedido_status_id = 2;
                 foreach ($carrinho as $id => $p) {
                     $produto = Produto::find($id);
                     if ($produto['tipo'] != 'Boate') {
                         $pedido_itens[$id] = array('nome_br' => $produto->nome_br, 'nome_en' => $produto->nome_en, 'preco' => $produto->valor, 'tipo' => '', 'quantidade' => 1);
                         $pedido->total += $produto->valor;
                     } else {
                         if (isset($p['genero'])) {
                             if (isset($p['genero']['masculino'])) {
                                 if (isset($p['genero']['masculino']['inteira'])) {
                                     $pedido_itens2['masculino']['inteira'][$id] = array('nome_br' => $produto->nome_br, 'nome_en' => $produto->nome_en, 'preco' => $produto->valor_masculino, 'tipo' => 'Masculino - Inteira', 'quantidade' => $p['genero']['masculino']['inteira']);
                                     $pedido->total += $produto->valor_masculino * $p['genero']['masculino']['inteira'];
                                 }
                                 if (isset($p['genero']['masculino']['meia'])) {
                                     $pedido_itens2['masculino']['meia'][$id] = array('nome_br' => $produto->nome_br, 'nome_en' => $produto->nome_en, 'preco' => $produto->valor_masculino_meia, 'tipo' => 'Masculino - Meia', 'quantidade' => $p['genero']['masculino']['meia']);
                                     $pedido->total += $produto->valor_masculino_meia * $p['genero']['masculino']['meia'];
                                 }
                             }
                             if (isset($p['genero']['feminino'])) {
                                 if (isset($p['genero']['feminino']['inteira'])) {
                                     $pedido_itens2['feminino']['inteira'][$id] = array('nome_br' => $produto->nome_br, 'nome_en' => $produto->nome_en, 'preco' => $produto->valor_feminino, 'tipo' => 'Feminino - Inteira', 'quantidade' => $p['genero']['feminino']['inteira']);
                                     $pedido->total += $produto->valor_feminino * $p['genero']['feminino']['inteira'];
                                 }
                                 if (isset($p['genero']['feminino']['meia'])) {
                                     $pedido_itens2['feminino']['meia'][$id] = array('nome_br' => $produto->nome_br, 'nome_en' => $produto->nome_en, 'preco' => $produto->valor_feminino_meia, 'tipo' => 'Feminino - Meia', 'quantidade' => $p['genero']['feminino']['meia']);
                                     $pedido->total += $produto->valor_feminino_meia * $p['genero']['feminino']['meia'];
                                 }
                             }
                         }
                     }
                 }
                 $pedido->moeda = Session::get('moeda')->moeda;
                 $pedido->save();
                 $historico = new PedidoHistorico();
                 $historico->pedido_id = $pedido->id;
                 $historico->pedido_status_id = 2;
                 $historico->save();
                 if (isset($pedido_itens)) {
                     $pedido->produtos()->sync($pedido_itens);
                 }
                 if (isset($pedido_itens2)) {
                     if (isset($pedido_itens2['masculino']['inteira'])) {
                         $pedido->produtos()->attach($pedido_itens2['masculino']['inteira']);
                     }
                     if (isset($pedido_itens2['masculino']['meia'])) {
                         $pedido->produtos()->attach($pedido_itens2['masculino']['meia']);
                     }
                     if (isset($pedido_itens2['feminino']['inteira'])) {
                         $pedido->produtos()->attach($pedido_itens2['feminino']['inteira']);
                     }
                     if (isset($pedido_itens2['feminino']['meia'])) {
                         $pedido->produtos()->attach($pedido_itens2['feminino']['meia']);
                     }
                 }
                 Session::forget('carrinho');
             }
             return Redirect::to('cliente/pedido')->with('success', array('Seu pedido foi feito e esta sendo analizado. Em breve você receberá o valor do seu pedido e poderá pagar online.'));
         }
     } else {
         return Redirect::to('users/login')->with('warning', array('Você precisa estar logado para fazer um pedido!'));
     }
 }
Ejemplo n.º 12
0
    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $model = new Pedido();
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
        if (isset($_POST['Pedido'])) {
            $model->attributes = $_POST['Pedido'];
            if ($model->save()) {
                /*cambiar pagina de rredireccion*/
                $desde = "*****@*****.**";
                $adminemail = Yii::app()->params['adminEmail'];
                //////////////////////////////ENVIO DE EMAILS///////////////////////////////////////////////
                $name = "El Desguace de la red";
                $marca = $model->marca;
                $modelo = $model->modelo;
                $fechaF = $model->fecha_fab;
                $bastidor = $model->bastidor;
                $combustible = $model->combustible;
                $color = $model->color;
                $piezas = $model->piezas;
                $headers = "From: {$name} <{$adminemail}>\r\n" . "Reply-To: {$desde}\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: text/html; charset=UTF-8";
                $asunto = 'Pedido de Piezas desde el Desguacedelared.com';
                $body = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
       <html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
		<title>Mensaje desde El Desguace de la Red</title>
		

		<style>	@media only screen and (max-width: 300px){ 
				body {
					width:218px !important;
					margin:auto !important;
				}
				.table {width:195px !important;margin:auto !important;}
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;}		
				span.title{font-size:20px !important;line-height: 23px !important}
				span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;}		
				td.box p{font-size: 12px !important;font-weight: bold !important;}
				.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
					display: block !important; 
				}
				.table-recap{width: 200px!important;}
				.table-recap tr td, .conf_body td{text-align:center !important;}	
				.address{display: block !important;margin-bottom: 10px !important;}
				.space_address{display: none !important;}	
			}
	@media only screen and (min-width: 301px) and (max-width: 500px) { 
				body {width:308px!important;margin:auto!important;}
				.table {width:285px!important;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}	
				.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
					display: block !important; 
				}
				.table-recap{width: 293px !important;}
				.table-recap tr td, .conf_body td{text-align:center !important;}
				
			}
	@media only screen and (min-width: 501px) and (max-width: 768px) {
				body {width:478px!important;margin:auto!important;}
				.table {width:450px!important;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}			
			}
	@media only screen and (max-device-width: 480px) { 
				body {width:308px!important;margin:auto!important;}
				.table {width:285px;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
				
				.table-recap{width: 285px!important;}
				.table-recap tr td, .conf_body td{text-align:center!important;}	
				.address{display: block !important;margin-bottom: 10px !important;}
				.space_address{display: none !important;}	
			}
</style>

	</head>
	<body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
		<table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
			<tr>
				<td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
				<td align="center" style="padding:7px 0">
					<table class="table" bgcolor="#ffffff" style="width:100%">
						<tr>
							<td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
								<a title="El Desguace de la red" href="http://tienda.eldesguacedelared.com" style="color:#337ff1">
									<img src="http://eldesguacedelared.com/img/logo200.png" alt="El Desguace de la Red" />
								</a>
							</td>
						</tr>

<tr>
	<td align="center" class="titleblock" style="padding:7px 0">
		<font size="2" face="Open-sans, sans-serif" color="#555454">
			<span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Hola,</span><br/>
			<span class="subtitle" style="font-weight:500;font-size:16px;text-transform:uppercase;line-height:25px">Nos ponemos en contacto con vosotros para la peticion de piezas</span>
		</font>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
		<table class="table" style="width:100%">
			<tr>
				<td width="10" style="padding:7px 0">&nbsp;</td>
				<td style="padding:7px 0">
					<font size="2" face="Open-sans, sans-serif" color="#555454">
						<p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
							Pedido desde El desguace de la red						</p>
						<span style="color:#777">
							Detalles:<br /> 
							<span style="color:#333"><strong>Piezas y Observaciones : </strong></span>' . $piezas . '<br />
                            <span style="color:#333"><strong>Marca: </strong></span>' . $marca . '<br />
                            <span style="color:#333"><strong>Modelo: </strong></span>' . $modelo . '<br />
                            <span style="color:#333"><strong>Fecha de Fabricacion: </strong></span>' . $fechaF . '<br />
                            <span style="color:#333"><strong>Bastidor: </strong></span>' . $bastidor . '<br />
                            <span style="color:#333"><strong>Combustible: </strong></span>' . $combustible . '
                           
						</span>
					</font>
				</td>
				<td width="10" style="padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
		<table class="table" style="width:100%">
			<tr>
				<td width="10" style="padding:7px 0">&nbsp;</td>
				<td style="padding:7px 0">
					<font size="2" face="Open-sans, sans-serif" color="#555454">
						<p style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">Consejos:</p>
						<ol style="margin-bottom:0">
							<li>Contacte con nosotros lo antes posible</li>
							<li>Adjunte fotos de las piezas para que al cliente le quede claro el estado de las mismas.</li>
						
						</ol>
					</font>
				</td>
				<td width="10" style="padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="linkbelow" style="padding:7px 0">
		<font size="2" face="Open-sans, sans-serif" color="#555454">
			<span>Juan Fernandez - CEO de <a href="http://eldesguacedelared.com" style="color:#337ff1">El Desguace de la Red</a></span>
		</font>
	</td>
</tr>

						<tr>
							<td class="space_footer" style="padding:0!important">&nbsp;</td>
						</tr>
						<tr>
							<td class="footer" style="border-top:4px solid #333333;padding:7px 0">
								<span><a href="http://eldesguacedelared.com" style="color:#337ff1">El Desguace de la red</a> Desarrollado creado por <a href="http://www.benyapps.com" style="color:#337ff1">Benyapps&trade;</a></span>
							</td>
						</tr>
					</table>
				</td>
				<td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</body>
</html>';
                /////////////ENVIO EMAILS DESGUACES
                $models = Desguace::model()->findAll();
                if ($models) {
                    foreach ($models as $em) {
                        mail($em->email, $asunto, $body, $headers);
                    }
                }
                ////////////////////////////////////TRIGGER ///////////////////////////////////////
                //
                //
                $link = mysqli_connect("juanDesguace.db.11252623.hostedresource.com", "juanDesguace", "Polencito1!", "juanDesguace");
                //////////////pasword generado
                $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
                $cad = "";
                for ($i = 0; $i < 8; $i++) {
                    $cad .= substr($str, rand(0, 62), 1);
                }
                /////concatenar cookie key y transformar a md5
                $cookiekey = "jYI1XwMsZtPyP8k2N0IhZMDaO9FgcJmBqOZhguzmBC5iVEHu881wLJCF";
                $cookiekey .= $cad;
                $passAuto = md5($cookiekey);
                $email = $model->email;
                $nombre = $model->nombre;
                $apellidos = $model->apellidos;
                $ahora = date('Y-m-d H:i:s');
                $active = 1;
                $is_guest = 0;
                $securekey = md5(uniqid(rand(), true));
                $max_payments = 0;
                $id_lang = 1;
                $id_default_group = 3;
                $id_risk = 0;
                $id_country = 6;
                $id_state = $model->provincia;
                $direccion = $model->direccion;
                $postcode = $model->cp;
                $city = $model->ciudad;
                $phone = $model->telefono;
                $alias = "Casa";
                //////////////////////////////////////////FIN DECLARACION VARIABLES
                ////busca si el email esta en bd
                $sql = "SELECT COUNT(*) AS esta FROM ps_customer WHERE email='{$email}'";
                $result = mysqli_query($link, $sql);
                $data = mysqli_fetch_assoc($result);
                ////si no esta introducir en tabla clientes
                if ($data['esta'] == 0) {
                    $sql1 = "INSERT INTO ps_customer(id_lang,id_default_group,id_risk,firstname,lastname,email,passwd,active,is_guest,date_add,date_upd,last_passwd_gen,secure_key,max_payment_days) VALUES('{$id_lang}','{$id_default_group}','{$id_risk}','{$nombre}','{$apellidos}','{$email}','{$passAuto}','{$active}','{$is_guest}','{$ahora}','{$ahora}','{$ahora}','{$securekey}','{$max_payments}')";
                    $result1 = mysqli_query($link, $sql1);
                    ////despues de insertar datos personales insertar datos de la direccion
                    ///////////////primero buscar id del cliente
                    $sql3 = "SELECT id_customer FROM ps_customer WHERE email='{$email}'";
                    $result3 = mysqli_query($link, $sql3);
                    $id_cl_array = mysqli_fetch_assoc($result3);
                    $idcliente = $id_cl_array['id_customer'];
                    ////////////ahora insertar
                    $sql2 = "INSERT INTO ps_address (id_country,id_state,id_customer,alias,lastname,firstname,address1,postcode,phone,city,date_add,date_upd,active) VALUES('{$id_country}','{$id_state}','{$idcliente}','{$alias}','{$apellidos}','{$nombre}','{$direccion}','{$postcode}','{$phone}','{$city}','{$ahora}','{$ahora}','{$active}')";
                    $result2 = mysqli_query($link, $sql2);
                    /////////////ahora insertar grupos pertenece
                    $sql4 = "INSERT INTO ps_customer_group(id_customer,id_group) VALUES('{$idcliente}',1)";
                    $result4 = mysqli_query($link, $sql4);
                    $sql5 = "INSERT INTO ps_customer_group(id_customer,id_group) VALUES('{$idcliente}',2)";
                    $result5 = mysqli_query($link, $sql5);
                    $sql6 = "INSERT INTO ps_customer_group(id_customer,id_group) VALUES('{$idcliente}',3)";
                    $result6 = mysqli_query($link, $sql6);
                    ////////////////////CORREO CLIENTE
                    $correoweb = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
       <html>
    <head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
		<title>Mensaje desde El Desguace de la Red</title>
		

		<style>	@media only screen and (max-width: 300px){ 
				body {
					width:218px !important;
					margin:auto !important;
				}
				.table {width:195px !important;margin:auto !important;}
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;}		
				span.title{font-size:20px !important;line-height: 23px !important}
				span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;}		
				td.box p{font-size: 12px !important;font-weight: bold !important;}
				.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
					display: block !important; 
				}
				.table-recap{width: 200px!important;}
				.table-recap tr td, .conf_body td{text-align:center !important;}	
				.address{display: block !important;margin-bottom: 10px !important;}
				.space_address{display: none !important;}	
			}
	@media only screen and (min-width: 301px) and (max-width: 500px) { 
				body {width:308px!important;margin:auto!important;}
				.table {width:285px!important;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}	
				.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
					display: block !important; 
				}
				.table-recap{width: 293px !important;}
				.table-recap tr td, .conf_body td{text-align:center !important;}
				
			}
	@media only screen and (min-width: 501px) and (max-width: 768px) {
				body {width:478px!important;margin:auto!important;}
				.table {width:450px!important;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}			
			}
	@media only screen and (max-device-width: 480px) { 
				body {width:308px!important;margin:auto!important;}
				.table {width:285px;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
				
				.table-recap{width: 285px!important;}
				.table-recap tr td, .conf_body td{text-align:center!important;}	
				.address{display: block !important;margin-bottom: 10px !important;}
				.space_address{display: none !important;}	
			}
</style>

	</head>
	<body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
		<table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
			<tr>
				<td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
				<td align="center" style="padding:7px 0">
					<table class="table" bgcolor="#ffffff" style="width:100%">
						<tr>
							<td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
								<a title="El Desguace de la red" href="http://tienda.eldesguacedelared.com" style="color:#337ff1">
									<img src="http://eldesguacedelared.com/img/logo200.png" alt="El Desguace de la Red" />
								</a>
							</td>
						</tr>

<tr>
	<td align="center" class="titleblock" style="padding:7px 0">
		<font size="2" face="Open-sans, sans-serif" color="#555454">
			<span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Hola ' . $nombre . ' ' . $apellidos . ',</span><br/>
			<span class="subtitle" style="font-weight:500;font-size:16px;text-transform:uppercase;line-height:25px">Gracias por crear una cuenta de cliente en El Desguace de la red.</span>
		</font>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
		<table class="table" style="width:100%">
			<tr>
				<td width="10" style="padding:7px 0">&nbsp;</td>
				<td style="padding:7px 0">
					<font size="2" face="Open-sans, sans-serif" color="#555454">
						<p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
							Detalles de su cuenta en El desguace de la red						</p>
						<span style="color:#777">
							Estos son sus datos de acceso:<br /> 
							<span style="color:#333"><strong>E-mail: ' . $email . ' </strong></span><br />
							<span style="color:#333"><strong>Password:</strong></span> ' . $cad . '
						</span>
                        Pronto recibira un email con las piezas que le hemos encontrado y podra valorarlas mediante fotos y comprarla si lo desea.
					</font>
				</td>
				<td width="10" style="padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
		<table class="table" style="width:100%">
			<tr>
				<td width="10" style="padding:7px 0">&nbsp;</td>
				<td style="padding:7px 0">
					<font size="2" face="Open-sans, sans-serif" color="#555454">
						<p style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">Consejos de Seguridad:</p>
						<ol style="margin-bottom:0">
							<li>Cambie su clave autogenerada al iniciar sesión</li>
							<li>Mantenga los datos de su cuenta en un lugar seguro.</li>
							<li>No comparta los detalles de su cuenta con otras personas.</li>
							<li>Cambie su clave regularmente.</li>
							<li>Si sospecha que alguien está usando ilegalmente su cuenta, avísenos inmediatamente.</li>
						</ol>
					</font>
				</td>
				<td width="10" style="padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="linkbelow" style="padding:7px 0">
		<font size="2" face="Open-sans, sans-serif" color="#555454">
			<span>Ahora podrá realizar pedidos en nuestra tienda: <a href="http://tienda.eldesguacedelared.com" style="color:#337ff1">El Desguace de la Red</a></span>
		</font>
	</td>
</tr>

						<tr>
							<td class="space_footer" style="padding:0!important">&nbsp;</td>
						</tr>
						<tr>
							<td class="footer" style="border-top:4px solid #333333;padding:7px 0">
								<span><a href="http://eldesguacedelared.com" style="color:#337ff1">El Desguace de la red</a> desarrollado por <a href="http://www.benyapps.com" style="color:#337ff1">Benyapps&trade;</a></span>
							</td>
						</tr>
					</table>
				</td>
				<td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</body>
</html>';
                    $asunto1 = "Alta de Usuario";
                    $headers1 = "From: {$desde}\r\n" . "Reply-To: {$adminemail}\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: text/html; charset=UTF-8";
                    mail($email, $asunto1, $correoweb, $headers1);
                    ///////////////////FINAL REDIRECCION Y REFRESH
                } else {
                    $headers2 = "From: {$desde}\r\n" . "Reply-To: {$adminemail}\r\n" . "MIME-Version: 1.0\r\n" . "Content-Type: text/html; charset=UTF-8";
                    $asunto2 = "Recordatorio Usuario";
                    $correoweb2 = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
       <html>
    <head>
    	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" />
		<title>Mensaje desde El Desguace de la Red</title>
		

		<style>	@media only screen and (max-width: 300px){ 
				body {
					width:218px !important;
					margin:auto !important;
				}
				.table {width:195px !important;margin:auto !important;}
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto !important;display: block !important;}		
				span.title{font-size:20px !important;line-height: 23px !important}
				span.subtitle{font-size: 14px !important;line-height: 18px !important;padding-top:10px !important;display:block !important;}		
				td.box p{font-size: 12px !important;font-weight: bold !important;}
				.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
					display: block !important; 
				}
				.table-recap{width: 200px!important;}
				.table-recap tr td, .conf_body td{text-align:center !important;}	
				.address{display: block !important;margin-bottom: 10px !important;}
				.space_address{display: none !important;}	
			}
	@media only screen and (min-width: 301px) and (max-width: 500px) { 
				body {width:308px!important;margin:auto!important;}
				.table {width:285px!important;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}	
				.table-recap table, .table-recap thead, .table-recap tbody, .table-recap th, .table-recap td, .table-recap tr { 
					display: block !important; 
				}
				.table-recap{width: 293px !important;}
				.table-recap tr td, .conf_body td{text-align:center !important;}
				
			}
	@media only screen and (min-width: 501px) and (max-width: 768px) {
				body {width:478px!important;margin:auto!important;}
				.table {width:450px!important;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}			
			}
	@media only screen and (max-device-width: 480px) { 
				body {width:308px!important;margin:auto!important;}
				.table {width:285px;margin:auto!important;}	
				.logo, .titleblock, .linkbelow, .box, .footer, .space_footer{width:auto!important;display: block!important;}
				
				.table-recap{width: 285px!important;}
				.table-recap tr td, .conf_body td{text-align:center!important;}	
				.address{display: block !important;margin-bottom: 10px !important;}
				.space_address{display: none !important;}	
			}
</style>

	</head>
	<body style="-webkit-text-size-adjust:none;background-color:#fff;width:650px;font-family:Open-sans, sans-serif;color:#555454;font-size:13px;line-height:18px;margin:auto">
		<table class="table table-mail" style="width:100%;margin-top:10px;-moz-box-shadow:0 0 5px #afafaf;-webkit-box-shadow:0 0 5px #afafaf;-o-box-shadow:0 0 5px #afafaf;box-shadow:0 0 5px #afafaf;filter:progid:DXImageTransform.Microsoft.Shadow(color=#afafaf,Direction=134,Strength=5)">
			<tr>
				<td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
				<td align="center" style="padding:7px 0">
					<table class="table" bgcolor="#ffffff" style="width:100%">
						<tr>
							<td align="center" class="logo" style="border-bottom:4px solid #333333;padding:7px 0">
								<a title="El Desguace de la red" href="http://tienda.eldesguacedelared.com" style="color:#337ff1">
									<img src="http://eldesguacedelared.com/img/logo200.png" alt="El Desguace de la Red" />
								</a>
							</td>
						</tr>

<tr>
	<td align="center" class="titleblock" style="padding:7px 0">
		<font size="2" face="Open-sans, sans-serif" color="#555454">
			<span class="title" style="font-weight:500;font-size:28px;text-transform:uppercase;line-height:33px">Hola ' . $nombre . ' ' . $apellidos . ',</span><br/>
			<span class="subtitle" style="font-weight:500;font-size:16px;text-transform:uppercase;line-height:25px">Usted ya tiene una cuenta en El Desguace de la red. Debido a que no es el primer pedido que realiza</span>
		</font>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
		<table class="table" style="width:100%">
			<tr>
				<td width="10" style="padding:7px 0">&nbsp;</td>
				<td style="padding:7px 0">
					<font size="2" face="Open-sans, sans-serif" color="#555454">
						<p data-html-only="1" style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">
							Detalles de su cuenta en El desguace de la red						</p>
						<span style="color:#777">
							Sus datos de acceso estan relacionados con el siguiente email:<br /> 
							<span style="color:#333"><strong>E-mail: ' . $email . ' </strong></span><br /><br />
							<span style="color:#333"><strong>Si no recuerda su contraseña pulse en el siguiente link para restablecerla.</strong></span><a href="http://tienda.eldesguacedelared.com/index.php?controller=password">Restablecer contraseña</a>
						</span>
                        Pronto recibira un email con las piezas que le hemos encontrado y podra valorarlas mediante fotos y comprarla si lo desea.
					</font>
				</td>
				<td width="10" style="padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="box" style="border:1px solid #D6D4D4;background-color:#f8f8f8;padding:7px 0">
		<table class="table" style="width:100%">
			<tr>
				<td width="10" style="padding:7px 0">&nbsp;</td>
				<td style="padding:7px 0">
					<font size="2" face="Open-sans, sans-serif" color="#555454">
						<p style="border-bottom:1px solid #D6D4D4;margin:3px 0 7px;text-transform:uppercase;font-weight:500;font-size:18px;padding-bottom:10px">Consejos de Seguridad:</p>
						<ol style="margin-bottom:0">
							
							<li>Mantenga los datos de su cuenta en un lugar seguro.</li>
							<li>No comparta los detalles de su cuenta con otras personas.</li>
							<li>Cambie su clave regularmente.</li>
							<li>Si sospecha que alguien está usando ilegalmente su cuenta, avísenos inmediatamente.</li>
						</ol>
					</font>
				</td>
				<td width="10" style="padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</td>
</tr>
<tr>
	<td class="space_footer" style="padding:0!important">&nbsp;</td>
</tr>
<tr>
	<td class="linkbelow" style="padding:7px 0">
		<font size="2" face="Open-sans, sans-serif" color="#555454">
			<span>Ahora podrá realizar pedidos en nuestra tienda: <a href="http://tienda.eldesguacedelared.com" style="color:#337ff1">El Desguace de la Red</a></span>
		</font>
	</td>
</tr>

						<tr>
							<td class="space_footer" style="padding:0!important">&nbsp;</td>
						</tr>
						<tr>
							<td class="footer" style="border-top:4px solid #333333;padding:7px 0">
								<span><a href="http://eldesguacedelared.com" style="color:#337ff1">El Desguace de la red</a> desarrollado por <a href="http://www.benyapps.com" style="color:#337ff1">Benyapps&trade;</a></span>
							</td>
						</tr>
					</table>
				</td>
				<td class="space" style="width:20px;padding:7px 0">&nbsp;</td>
			</tr>
		</table>
	</body>
</html>';
                    mail($email, $asunto2, $correoweb2, $headers2);
                }
                mysqli_close($link);
                $this->redirect(array('view', 'id' => $model->id));
                $this->refresh();
            }
        }
        $this->render('create', array('model' => $model));
    }