<?php
final class Modelos_Movimientos_ImportExport extends Modelo {
	protected $_db = null;
	public $mensajes = array();

	public function iniciarDb($db) {
    	if (!$this->_db) {
			$this->_db = $db;
        }
    }

    public function mostrarOrdenesCompra() {
		try {
			// $qryContador = "SELECT COUNT(id) FROM ordenes_compra";
			// $qry = "SELECT c.alfanumerico, c.id, CONCAT(u.nombre, ' ', u.apellidos) AS agente, cts.razon_social AS codigo, c.total, c.pais, c.xf, c.id_integracion
			// 	FROM ordenes_compra c
			// 	JOIN usuarios u
			// 	ON u.id = c.id_agente
			// 	JOIN clientes cts
			// 	ON cts.id = c.id_proveedor
			// 	WHERE (pais = 2 OR pais = 3)
			// 	ORDER BY id DESC";
			// $limite = 10;
			// $adyacentes = 6;
			// $paginaLink = STASIS . '/reportes/ordenescompra/usa/?p=';

			// $paginacion = Modelos_Contenedor::crearModelo('paginacion');
			// $paginacion->crear($qryContador, $qry, $limite, $adyacentes, $paginaLink);
			// $this->paginacionHtml = $paginacion->mostrar();

			// $sth = $this->_db->query($paginacion->query());
			// if(!$sth->execute()) throw New Exception();

			// $datosVista = array();
			// while ($datos = $sth->fetch()) {
			// 	switch($datos['pais']) {
			// 		case 2: $pais = 'USA'; break;
			// 		case 3: $pais = 'Internacional'; break;
			// 	}

			// 	switch($datos['id_integracion']) {
			// 		case 0: $integracion = 'Matriz'; break;
			// 		case 2: $integracion = 'Welch Allyn'; break;
			// 		case 3: $integracion = 'Teleflex'; break;
			// 		case 4: $integracion = 'SMK Electronics'; break;
			// 		case 5: $integracion = 'Thermofisher'; break;
			// 	}

			// 	$arreglo = array('id' => $datos['id'],
			// 					 'alfanumerico' => $datos['alfanumerico'],
			// 					 'agente' => $datos['agente'],
			// 					 'codigo' => $datos['codigo'],
			// 					 'pais' => $pais,
			// 					 'integracion' => $integracion,
			// 					 'xf' => $datos['xf'],
			// 					 'total' => $datos['total']);
			// 	$datosVista[] = $arreglo;
			// }

	  // 		return $datosVista;
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function getOrdenesCompra() {
		try {
			$id = $_POST['oc'];
			$html = '';
			if ((strlen($id) == 4 || strlen($id) == 5) && is_numeric($id)) {
					$sth = $this->_db->prepare("SELECT c.alfanumerico, c.id, CONCAT(u.nombre, ' ', u.apellidos) AS agente, cts.razon_social AS codigo, c.total, c.pais, c.xf, c.id_integracion
						FROM ordenes_compra c
						JOIN usuarios u
						ON u.id = c.id_agente
						JOIN clientes cts
						ON cts.id = c.id_proveedor
						WHERE (pais = 2 OR pais = 3) AND c.id = ?
						ORDER BY id DESC");
					$sth->bindParam(1, $id);
				} else {
					$sth = $this->_db->prepare("SELECT c.alfanumerico, c.id, CONCAT(u.nombre, ' ', u.apellidos) AS agente, cts.razon_social AS codigo, c.total, c.pais, c.xf, c.id_integracion
						FROM ordenes_compra c
						JOIN usuarios u
						ON u.id = c.id_agente
						JOIN clientes cts
						ON cts.id = c.id_proveedor
						WHERE (pais = 2 OR pais = 3) AND (codigo LIKE '%" . $id . "%' OR u.nombre LIKE '%" . $id . "%')
						ORDER BY id DESC
						LIMIT 300");
				}
			if(!$sth->execute()) throw New Exception();

			while ($datos = $sth->fetch()) {
				switch($datos['pais']) {
					case 2: $pais = 'USA'; break;
					case 3: $pais = 'Internacional'; break;
				}

				switch($datos['id_integracion']) {
					case 0: $integracion = 'Matriz'; break;
					case 2: $integracion = 'Welch Allyn'; break;
					case 3: $integracion = 'Teleflex'; break;
					case 4: $integracion = 'SMK Electronics'; break;
					case 5: $integracion = 'Thermofisher'; break;
				}

				if ((strlen($id) == 4 || strlen($id) == 5) && is_numeric($id)) {
					$checked = 'checked';
				} else {
					$checked = '';
				}

				$html .= '<tr class="ordenes-compra ' . $datos['id_integracion'] . '-' . $datos['codigo'] . '">
						<td class="text-center input-0">
							<input class="fila-verde facturacion-ordenes-compra" id="' . $datos['id'] . '-' . $datos['id_integracion'] . '-' . $datos['codigo'] . '" type="checkbox" ' . $checked . ' name="ordenescompra[]" value="' . $datos['id'] . '" />
						</td>
						<td>' . $datos['alfanumerico'] . '-' . $datos['id'] . '</td>
						<td>Normal</td>
						<td>' . $datos['agente'] . '</td>
						<td>' . $datos['codigo'] . '</td>
						<td>' . $integracion . '</td>
						<td>$' . $datos['total'] . '</td>
					</tr>';
			}

	  		return $html;
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function listadoCargaSeleccion() {
		try {
			$qryContador = "SELECT COUNT(id) FROM import_export WHERE status = 0";
			$qry = "SELECT id, fecha, total FROM import_export WHERE status = 0 ORDER BY fecha DESC";
			$limite = 500;
			$adyacentes = 6;
			$paginaLink = STASIS . '/reportes/import_export_abiertas/?p=';

			$paginacion = Modelos_Contenedor::crearModelo('paginacion');
			$paginacion->crear($qryContador, $qry, $limite, $adyacentes, $paginaLink);
			$this->paginacionHtml = $paginacion->mostrar();

			$sth = $this->_db->query($paginacion->query());
			if(!$sth->execute()) throw New Exception();

			$datosVista = array();
			while ($datos = $sth->fetch()) {
				// Pendiente
				if ($datos['status'] == 0) {
					$status = 'Abierta';
				}

				// Parcialmente recibido en Xpress
				if ($datos['status'] == 1) {
					$status = 'Cerrada';
				}

				$arreglo = array('id' => $datos['id'],
								 'fecha' => Modelos_Fecha::formatearFecha($datos['fecha']),
								 'status' => $status,
								 'total' => $datos['total']);
				$datosVista[] = $arreglo;
			}

	  		$this->pendientes = $datosVista;
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function modificarMostrarOrdenesCompra($id) {
		try {
			$html = '';

			// Seleccionar los IDs de las ordenes de compra que ya habian sido seleccionadas
			$sth = $this->_db->prepare("SELECT DISTINCT id_orden_compra FROM import_export_partes WHERE id_factura = ? AND id_orden_compra != ''");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();
			while ($datos = $sth->fetch()) {
				$arregloOrdenesCompra[] = $datos['id_orden_compra'];
			}

			$sth = $this->_db->prepare("SELECT c.alfanumerico, c.id, CONCAT(u.nombre, ' ', u.apellidos) AS agente, cts.razon_social AS codigo, c.total, c.pais, c.xf, c.id_integracion
				FROM ordenes_compra c
				JOIN usuarios u
				ON u.id = c.id_agente
				JOIN clientes cts
				ON cts.id = c.id_proveedor
				WHERE (pais = 2 OR pais = 3) AND c.id IN (" . implode(',',$arregloOrdenesCompra) . ")
				ORDER BY id DESC");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();

			while ($datos = $sth->fetch()) {
				switch($datos['pais']) {
					case 2: $pais = 'USA'; break;
					case 3: $pais = 'Internacional'; break;
				}

				switch($datos['id_integracion']) {
					case 0: $integracion = 'Matriz'; break;
					case 2: $integracion = 'Welch Allyn'; break;
					case 3: $integracion = 'Teleflex'; break;
					case 4: $integracion = 'SMK Electronics'; break;
					case 5: $integracion = 'Thermofisher'; break;
				}

				$html .= '<tr id="fila' . $datos['id'] . '"';
				$html .= 'class="columna-amarilla"';
				$html .= '><td class="text-center input-0">';
				$html .= '<input class="fila-verde" type="checkbox" id="' . $datos['id'] . '" name="ordenescompra[]" value="' . $datos['id'] . '" checked="checked" />';
				$html .= '</td><td>' . $datos['alfanumerico'] . '-' . $datos['id'] . '</td><td>';
				if ($datos['xf'] == 1) {
					$html .= '<img src="' . STASIS . '/img/icono-alerta_amarillo.png" /> XF Especificado(s)';
				} else {
					$html .= 'Normal';
				}
				$html .= '</td>
					<td>' . $datos['agente'] . '</td>
					<td>' . $datos['codigo'] . '</td>
					<td>' . $integracion . '</td>
					<td>$' . $datos['total'] . '</td>
				</tr>';
			}

	  		return $html;
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function mostrarNumerosParte($ordenesCompra) {
		try {
			$datosArray = array();
			$partesArray = array();

			$x = 1;
			foreach($ordenesCompra as $ordenCompra) {
				$sth = $this->_db->prepare("SELECT id_integracion FROM ordenes_compra WHERE id = ?");
				$sth->bindParam(1, $ordenCompra);
				if(!$sth->execute()) throw New Exception();
				$datos = $sth->fetch();

				if ($datos['id_integracion'] == 0) {
					$sth = $this->_db->prepare("SELECT oc.alfanumerico, p.id, cp.cantidad_pendiente, cp.xf, p.codigo, pm.nombre AS um, p.descripcion, cp.precio AS costo
					FROM ordenes_compra_partes cp
					JOIN partes p
					ON p.id = cp.id_parte
					JOIN partes_medidas pm
					ON pm.id = p.id_unidad_compra
					JOIN ordenes_compra oc
					ON oc.id = cp.id_orden_compra
					WHERE cp.id_orden_compra = ? ORDER BY cp.id ASC");
					$sth->bindParam(1, $ordenCompra);
					if(!$sth->execute()) throw New Exception();

					while ($datos = $sth->fetch()) {
						// Si toda  cantidad del numero de parte se especifico como XF, no mostrar la parte
						if ($datos['xf'] != $datos['cantidad_pendiente']) {
							$partesArray[$x]['alfanumerico'] = $datos['alfanumerico'];
							$partesArray[$x]['id'] = $datos['id'];
							$partesArray[$x]['ordenCompra'] = $ordenCompra;
							$partesArray[$x]['cantidad'] = $datos['cantidad_pendiente']-$datos['xf'];
							$partesArray[$x]['cantidadXf'] = $datos['xf'];
							$partesArray[$x]['codigo'] = $datos['codigo'];
							$partesArray[$x]['um'] = $datos['um'];
							$partesArray[$x]['costo'] = $datos['costo'];
							$partesArray[$x]['descripcion'] = $datos['descripcion'];
							$x++;
						}
					}
				} else {
					$sth = $this->_db->prepare("SELECT oc.alfanumerico, p.id, cp.cantidad_pendiente, cp.xf, p.id_parte, p.uom_compra AS um, p.descripcion, cp.precio AS costo
					FROM ordenes_compra_partes cp
					JOIN baselines p
					ON p.id = cp.id_parte
					JOIN ordenes_compra oc
					ON oc.id = cp.id_orden_compra
					WHERE cp.id_orden_compra = ? ORDER BY cp.id ASC");
					$sth->bindParam(1, $ordenCompra);
					if(!$sth->execute()) throw New Exception();

					while ($datos = $sth->fetch()) {
						// Si toda la cantidad del numero de parte se especifico como XF, no mostrar la parte
						if ($datos['xf'] != $datos['cantidad_pendiente']) {
							$partesArray[$x]['alfanumerico'] = $datos['alfanumerico'];
							$partesArray[$x]['id'] = $datos['id'];
							$partesArray[$x]['ordenCompra'] = $ordenCompra;
							$partesArray[$x]['cantidad'] = $datos['cantidad_pendiente']-$datos['xf'];
							$partesArray[$x]['cantidadXf'] = $datos['xf'];
							$partesArray[$x]['codigo'] = $datos['id_parte'];
							$partesArray[$x]['um'] = $datos['um'];
							$partesArray[$x]['costo'] = $datos['costo'];
							$partesArray[$x]['descripcion'] = $datos['descripcion'];
							$x++;
						}
					}
				}
			}

			$datosArray['partes'] = $partesArray;
			$datosArray['conteoPartes'] = $x-1;
			$datosArray['ordenesCompra'] = $ordenesCompra;
			
			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function modificarMostrarNumerosParte($post) {
		try {
			$ordenesCompra = $post['ordenescompra'];
			$ordenesCompraNuevas = $post['ordenescompranueva'];
			$folio = $post['folio'];
			$datosArray = array();
			$partesArray = array();

			$x = 1;

			foreach($ordenesCompra as $ordenCompra) {
				$sth = $this->_db->prepare("SELECT id_integracion FROM ordenes_compra WHERE id = ?");
				$sth->bindParam(1, $ordenCompra);
				if(!$sth->execute()) throw New Exception();
				$datos = $sth->fetch();

				if ($datos['id_integracion'] == 0) {
					$sth = $this->_db->prepare("SELECT oc.alfanumerico, p.id, cp.cantidad, cp.xf, p.codigo, pm.nombre AS um, p.descripcion, cp.precio AS costo
					FROM ordenes_compra_partes cp
					JOIN partes p
					ON p.id = cp.id_parte
					JOIN partes_medidas pm
					ON pm.id = p.id_unidad_compra
					JOIN ordenes_compra oc
					ON oc.id = cp.id_orden_compra
					WHERE cp.id_orden_compra = ? ORDER BY cp.id ASC");
					$sth->bindParam(1, $ordenCompra);
					if(!$sth->execute()) throw New Exception();

					while ($datos = $sth->fetch()) {
						// Si toda la cantidad del numero de parte se especifico como XF, no mostrar la parte
						if ($datos['xf'] != $datos['cantidad']) {
							$idParte = $datos['id'];
							$partesArray[$x]['alfanumerico'] = $datos['alfanumerico'];
							$partesArray[$x]['id'] = $datos['id'];
							$partesArray[$x]['ordenCompra'] = $ordenCompra;
							$partesArray[$x]['cantidad'] = $datos['cantidad']-$datos['xf'];
							$partesArray[$x]['cantidadXf'] = $datos['xf'];
							$partesArray[$x]['codigo'] = $datos['codigo'];
							$partesArray[$x]['um'] = $datos['um'];
							$partesArray[$x]['costo'] = $datos['costo'];
							$partesArray[$x]['descripcion'] = $datos['descripcion'];

							// Seleccionar cantidades
							$sth2 = $this->_db->prepare("SELECT cantidad_recibida_import_export AS cantidad_modificar FROM import_export_partes WHERE id_parte = ? AND id_orden_compra = ? AND id_factura = ?");
							$sth2->bindParam(1, $idParte);
							$sth2->bindParam(2, $ordenCompra);
							$sth2->bindParam(3, $folio);
							if(!$sth2->execute()) throw New Exception();
							$datos2 = $sth2->fetch();
							$partesArray[$x]['cantidad_modificar'] = $datos2['cantidad_modificar'];

							$x++;
						}
					}
				} else {
					// Detectar si el numero de parte no fue puesto varias veces en la orden de compra
					$sthC = $this->_db->prepare("SELECT p.id, COUNT(*) AS conteo
						FROM ordenes_compra_partes cp
						JOIN baselines p
						ON p.id = cp.id_parte
						JOIN ordenes_compra oc
						ON oc.id = cp.id_orden_compra
						WHERE cp.id_orden_compra = ?
						GROUP BY p.id
						ORDER BY cp.id ASC");
					$sthC->bindParam(1, $ordenCompra);
					if(!$sthC->execute()) throw New Exception();

					$ordenCompraResetArray = array();
					while ($datosC = $sthC->fetch()) {
						if (!in_array($ordenCompra, $ordenCompraResetArray)) {
							$idParteConteo = $datosC['conteo'];
							$idParteContada = $datosC['id'];

							// echo $idParteConteo . ' ' . $idParteContada . '<br />';

							// Si solo se uso una vez
							if ($idParteConteo == 1) {
								$sth = $this->_db->prepare("SELECT oc.alfanumerico, p.id, cp.cantidad, cp.xf, p.id_parte, p.id_parte_xpress, p.uom_compra AS um, p.descripcion, cp.precio AS costo
								FROM ordenes_compra_partes cp
								JOIN baselines p
								ON p.id = cp.id_parte
								JOIN ordenes_compra oc
								ON oc.id = cp.id_orden_compra
								WHERE cp.id_orden_compra = ? ORDER BY cp.id ASC");
								$sth->bindParam(1, $ordenCompra);
								if(!$sth->execute()) throw New Exception();

								while ($datos = $sth->fetch()) {
									// Si toda la cantidad del numero de parte se especifico como XF, no mostrar la parte
									if ($datos['xf'] != $datos['cantidad']) {
										$idParte = $datos['id'];
										$partesArray[$x]['alfanumerico'] = $datos['alfanumerico'];
										$partesArray[$x]['id'] = $datos['id'];
										$partesArray[$x]['ordenCompra'] = $ordenCompra;
										$partesArray[$x]['cantidad'] = $datos['cantidad']-$datos['xf'];
										$partesArray[$x]['cantidadXf'] = $datos['xf'];
										$partesArray[$x]['codigo'] = $datos['id_parte'];
										$partesArray[$x]['codigoXpress'] = $datos['id_parte_xpress'];
										$partesArray[$x]['um'] = $datos['um'];
										$partesArray[$x]['costo'] = $datos['costo'];
										$partesArray[$x]['descripcion'] = $datos['descripcion'];

										// Seleccionar cantidades
										$sth2 = $this->_db->prepare("SELECT cantidad_recibida_import_export AS cantidad_modificar FROM import_export_partes WHERE id_parte = ? AND id_orden_compra = ? AND id_factura = ?");
										$sth2->bindParam(1, $idParte);
										$sth2->bindParam(2, $ordenCompra);
										$sth2->bindParam(3, $folio);
										if(!$sth2->execute()) throw New Exception();
										$datos2 = $sth2->fetch();
										$partesArray[$x]['cantidad_modificar'] = $datos2['cantidad_modificar'];

										$x++;
										$ordenCompraResetArray[] = $ordenCompra;
									}
								}
							// Si se uso varias veces, jalar las cantidades en un arreglo
							} else {
								$cantidadesArreglo = array();
								$sth2 = $this->_db->prepare("SELECT cantidad_recibida_import_export AS cantidad_modificar FROM import_export_partes WHERE id_parte = ? AND id_orden_compra = ? AND id_factura = ?");
								$sth2->bindParam(1, $idParteContada);
								$sth2->bindParam(2, $ordenCompra);
								$sth2->bindParam(3, $folio);
								if(!$sth2->execute()) throw New Exception();
								while ($datos2 = $sth2->fetch()) {
									$cantidadesArreglo[] = $datos2['cantidad_modificar'];
								}
								$cantidadesContador = 0;

								$sth = $this->_db->prepare("SELECT oc.alfanumerico, p.id, cp.cantidad, cp.xf, p.id_parte, p.id_parte_xpress, p.uom_compra AS um, p.descripcion, cp.precio AS costo
								FROM ordenes_compra_partes cp
								JOIN baselines p
								ON p.id = cp.id_parte
								JOIN ordenes_compra oc
								ON oc.id = cp.id_orden_compra
								WHERE cp.id_orden_compra = ? ORDER BY cp.id ASC");
								$sth->bindParam(1, $ordenCompra);
								if(!$sth->execute()) throw New Exception();

								while ($datos = $sth->fetch()) {
									// Si toda la cantidad del numero de parte se especifico como XF, no mostrar la parte
									if ($datos['xf'] != $datos['cantidad']) {
										$idParte = $datos['id'];
										$partesArray[$x]['alfanumerico'] = $datos['alfanumerico'];
										$partesArray[$x]['id'] = $datos['id'];
										$partesArray[$x]['ordenCompra'] = $ordenCompra;
										$partesArray[$x]['cantidad'] = $datos['cantidad']-$datos['xf'];
										$partesArray[$x]['cantidadXf'] = $datos['xf'];
										$partesArray[$x]['codigo'] = $datos['id_parte'];
										$partesArray[$x]['codigoXpress'] = $datos['id_parte_xpress'];
										$partesArray[$x]['um'] = $datos['um'];
										$partesArray[$x]['costo'] = $datos['costo'];
										$partesArray[$x]['descripcion'] = $datos['descripcion'];

										// Seleccionar cantidades
										$sth2 = $this->_db->prepare("SELECT cantidad_recibida_import_export AS cantidad_modificar FROM import_export_partes WHERE id_parte = ? AND id_orden_compra = ? AND id_factura = ?");
										$sth2->bindParam(1, $idParte);
										$sth2->bindParam(2, $ordenCompra);
										$sth2->bindParam(3, $folio);
										if(!$sth2->execute()) throw New Exception();
										$datos2 = $sth2->fetch();
										$partesArray[$x]['cantidad_modificar'] = $cantidadesArreglo[$cantidadesContador];
										$cantidadesContador++;

										$x++;
									}
								}
							}
						}
					}
				}
			}

			// Nuevas
			foreach($ordenesCompraNuevas as $ordenCompra) {
				$sth = $this->_db->prepare("SELECT id_integracion FROM ordenes_compra WHERE id = ?");
				$sth->bindParam(1, $ordenCompra);
				if(!$sth->execute()) throw New Exception();
				$datos = $sth->fetch();

				if ($datos['id_integracion'] == 0) {
					$sth = $this->_db->prepare("SELECT oc.alfanumerico, p.id, cp.cantidad, cp.xf, p.codigo, pm.nombre AS um, p.descripcion, cp.precio AS costo
					FROM ordenes_compra_partes cp
					JOIN partes p
					ON p.id = cp.id_parte
					JOIN partes_medidas pm
					ON pm.id = p.id_unidad_compra
					JOIN ordenes_compra oc
					ON oc.id = cp.id_orden_compra
					WHERE cp.id_orden_compra = ? ORDER BY cp.id ASC");
					$sth->bindParam(1, $ordenCompra);
					if(!$sth->execute()) throw New Exception();

					while ($datos = $sth->fetch()) {
						// Si toda la cantidad del numero de parte se especifico como XF, no mostrar la parte
						if ($datos['xf'] != $datos['cantidad']) {
							$idParte = $datos['id'];
							$partesArray[$x]['nueva'] = 1;
							$partesArray[$x]['alfanumerico'] = $datos['alfanumerico'];
							$partesArray[$x]['id'] = $datos['id'];
							$partesArray[$x]['ordenCompra'] = $ordenCompra;
							$partesArray[$x]['cantidad'] = $datos['cantidad']-$datos['xf'];
							$partesArray[$x]['cantidadXf'] = $datos['xf'];
							$partesArray[$x]['codigo'] = $datos['codigo'];
							$partesArray[$x]['um'] = $datos['um'];
							$partesArray[$x]['costo'] = $datos['costo'];
							$partesArray[$x]['descripcion'] = $datos['descripcion'];

							// Seleccionar cantidades
							$sth2 = $this->_db->prepare("SELECT cantidad_recibida_import_export AS cantidad_modificar FROM import_export_partes WHERE id_parte = ? AND id_orden_compra = ? AND id_factura = ?");
							$sth2->bindParam(1, $idParte);
							$sth2->bindParam(2, $ordenCompra);
							$sth2->bindParam(3, $folio);
							if(!$sth2->execute()) throw New Exception();
							$datos2 = $sth2->fetch();
							$partesArray[$x]['cantidad_modificar'] = $datos2['cantidad_modificar'];

							$x++;
						}
					}
				} else {
					$sth = $this->_db->prepare("SELECT oc.alfanumerico, p.id, cp.cantidad_pendiente, cp.xf, p.id_parte, p.id_parte_xpress, p.uom_compra AS um, p.descripcion, cp.precio AS costo
					FROM ordenes_compra_partes cp
					JOIN baselines p
					ON p.id = cp.id_parte
					JOIN ordenes_compra oc
					ON oc.id = cp.id_orden_compra
					WHERE cp.id_orden_compra = ? ORDER BY cp.id ASC");
					$sth->bindParam(1, $ordenCompra);
					if(!$sth->execute()) throw New Exception();

					while ($datos = $sth->fetch()) {
						// Si toda la cantidad del numero de parte se especifico como XF, no mostrar la parte
						if ($datos['xf'] != $datos['cantidad_pendiente']) {
							$idParte = $datos['id'];
							$partesArray[$x]['nueva'] = 1;
							$partesArray[$x]['alfanumerico'] = $datos['alfanumerico'];
							$partesArray[$x]['id'] = $datos['id'];
							$partesArray[$x]['ordenCompra'] = $ordenCompra;
							$partesArray[$x]['cantidad'] = $datos['cantidad_pendiente']-$datos['xf'];
							$partesArray[$x]['cantidadXf'] = $datos['xf'];
							$partesArray[$x]['codigo'] = $datos['id_parte'];
							$partesArray[$x]['codigoXpress'] = $datos['id_parte_xpress'];
							$partesArray[$x]['um'] = $datos['um'];
							$partesArray[$x]['costo'] = $datos['costo'];
							$partesArray[$x]['descripcion'] = $datos['descripcion'];

							// Seleccionar cantidades
							$sth2 = $this->_db->prepare("SELECT cantidad_recibida_import_export AS cantidad_modificar FROM import_export_partes WHERE id_parte = ? AND id_orden_compra = ? AND id_factura = ?");
							$sth2->bindParam(1, $idParte);
							$sth2->bindParam(2, $ordenCompra);
							$sth2->bindParam(3, $folio);
							if(!$sth2->execute()) throw New Exception();
							$datos2 = $sth2->fetch();
							$partesArray[$x]['cantidad_modificar'] = $datos2['cantidad_modificar'];

							$x++;
						}
					}
				}
			}

			$datosArray['folio'] = $post['folio'];
			$datosArray['partes'] = $partesArray;
			$datosArray['conteoPartes'] = $x-1;
			$datosArray['ordenesCompra'] = $ordenesCompra;
			
			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function factura($post) {
		try {
			$datosArray = array();
			$partesArray = array();

			// Folio
			$sth = $this->_db->query("SELECT id FROM import_export ORDER BY id DESC LIMIT 1");
			$folio = $sth->fetchColumn()+1;
			
			// Fecha Actual
			$fecha = date('d/m/Y');

			// Nombre de Agente
			$sth = $this->_db->prepare("SELECT nombre, apellidos FROM usuarios WHERE id = ? LIMIT 1");
			$sth->bindParam(1, $_SESSION['login_id']);
			if(!$sth->execute()) throw New Exception();
			$datos = $sth->fetch();
			$agente = $datos['nombre'] . ' ' . $datos['apellidos'];

			$datosArray['folio'] = $folio;
			$datosArray['generar'] = $post['generar'];
			$datosArray['generarAmericana'] = $post['generarAmericana'];
			$datosArray['agente'] = $agente;

			// Datos de partes
			$conteoFilas = $post['filas'];

			for($x=1; $x<=$conteoFilas; $x++) {
				$sth = $this->_db->prepare("SELECT id_integracion FROM ordenes_compra WHERE id = ?");
				$sth->bindParam(1, $post["ordenCompra$x"]);
				if(!$sth->execute()) throw New Exception();
				$datos = $sth->fetch();

				if ($datos['id_integracion'] == 0) {
					$sth = $this->_db->prepare("SELECT p.id, p.codigo, p.ie_um, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo
						FROM ordenes_compra_partes ocp
						JOIN partes p
						ON p.id = ocp.id_parte
						WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ?");
					$sth->bindParam(1, $post["idParte$x"]);
					$sth->bindParam(2, $post["ordenCompra$x"]);
					if(!$sth->execute()) throw New Exception();

					while ($datos = $sth->fetch()) {
						$partesArray[$x]['cantidadSolicitada'] = $post["cantidadSolicitada$x"];
						$partesArray[$x]['cantidadRecibida'] = $post["cantidadRecibida$x"];
						$partesArray[$x]['idParte'] = $datos['id'];
						$partesArray[$x]['codigo'] = $datos['codigo'];
						$partesArray[$x]['um'] = $datos['ie_um'];
						$partesArray[$x]['descripcion'] = $datos['ie_descripcion'];
						$partesArray[$x]['descripcionIngles'] = $datos['ie_descripcion_ingles'];
						$partesArray[$x]['fraccion_arancelaria'] = $datos['fraccion_arancelaria'];
						$partesArray[$x]['peso'] = $datos['peso'];
						$partesArray[$x]['pais_origen'] = $datos['pais_origen'];
						$partesArray[$x]['costo'] = number_format((float)$datos['costo']*1.2, 4, '.', '');
					}
				} else {
					$sth = $this->_db->prepare("SELECT p.id, p.id_parte, p.ie_um, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo
						FROM ordenes_compra_partes ocp
						JOIN baselines p
						ON p.id = ocp.id_parte
						WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ?");
					$sth->bindParam(1, $post["idParte$x"]);
					$sth->bindParam(2, $post["ordenCompra$x"]);
					if(!$sth->execute()) throw New Exception();

					while ($datos = $sth->fetch()) {
						$partesArray[$x]['cantidadSolicitada'] = $post["cantidadSolicitada$x"];
						$partesArray[$x]['cantidadRecibida'] = $post["cantidadRecibida$x"];
						$partesArray[$x]['idParte'] = $datos['id'];
						$partesArray[$x]['codigo'] = $datos['id_parte'];
						$partesArray[$x]['um'] = $datos['ie_um'];
						$partesArray[$x]['descripcion'] = $datos['ie_descripcion'];
						$partesArray[$x]['descripcionIngles'] = $datos['ie_descripcion_ingles'];
						$partesArray[$x]['fraccion_arancelaria'] = $datos['fraccion_arancelaria'];
						$partesArray[$x]['peso'] = $datos['peso'];
						$partesArray[$x]['pais_origen'] = $datos['pais_origen'];
						$partesArray[$x]['costo'] = number_format((float)$datos['costo']*1.2, 4, '.', '');
					}
				}
			}
			$datosArray['partes'] = $partesArray;

			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function importacionActual() {
		try {
			$datosArray = array();
			$partesArray = array();
			
			$partesActuales = array();
			$idsActuales = array();
			$conteoPartes = 0;
			$x=1;

			// Seleccionar los folios de importacion que estan pendientes
			$sth = $this->_db->query("SELECT id FROM import_export WHERE status = 0");
			if(!$sth->execute()) throw New Exception();
			while ($datos = $sth->fetch()) {
				$idsActuales[] = $datos['id'];

				// Jalar los datos de las partes en un arreglo
				$sth2 = $this->_db->prepare("SELECT id_factura, id_orden_compra, id_parte, cantidad_recibida_import_export AS cantidad_recibida FROM import_export_partes WHERE id_factura = ?");
				$sth2->bindParam(1, $datos['id']);
				if(!$sth2->execute()) throw New Exception();
				while ($datos2 = $sth2->fetch()) {
					$partesActuales[$x]['id_factura'] = $datos2['id_factura'];
					$partesActuales[$x]['id_orden_compra'] = $datos2['id_orden_compra'];
					$partesActuales[$x]['id_parte'] = $datos2['id_parte'];
					$partesActuales[$x]['cantidad_recibida'] = $datos2['cantidad_recibida'];

					$x++;
				}

				// Hacer el conteo total de numeros de parte que se estan importando
				$sth2 = $this->_db->prepare("SELECT COUNT(*) AS conteo FROM import_export_partes WHERE id_factura = ?");
				$sth2->bindParam(1, $datos['id']);
				if(!$sth2->execute()) throw New Exception();
				$datos2 = $sth2->fetch();
				$conteoPartes += $datos2['conteo'];
			}

			$datosArray['conteoPartes'] = $conteoPartes;

			// Datos de partes
			for($x=1; $x<=$conteoPartes; $x++) {
				$sth = $this->_db->prepare("SELECT id_integracion FROM ordenes_compra WHERE id = ?");
				$sth->bindParam(1, $partesActuales[$x]['id_orden_compra']);
				if(!$sth->execute()) throw New Exception();
				$datos = $sth->fetch();

				if ($datos['id_integracion'] == 0) {
					$sth2 = $this->_db->prepare("SELECT p.id, ocp.id_orden_compra, ocp.cantidad AS cantidad_solicitada, iep.cantidad_recibida_import_export AS cantidad_recibida, p.codigo, p.ie_um, p.descripcion, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo, iep.caja
					FROM ordenes_compra_partes ocp
					JOIN partes p
					ON p.id = ocp.id_parte
					JOIN import_export_partes iep
					ON iep.id_orden_compra = ocp.id_orden_compra AND iep.id_parte = ocp.id_parte
					WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ? AND iep.id_factura = ?
					LIMIT 1");
					
					$sth2->bindParam(1, $partesActuales[$x]['id_parte']);
					$sth2->bindParam(2, $partesActuales[$x]['id_orden_compra']);
					$sth2->bindParam(3, $partesActuales[$x]['id_factura']);
					if(!$sth2->execute()) throw New Exception();

					while ($datos2 = $sth2->fetch()) {
						$partesArray[$x]['cantidadSolicitada'] = $datos2['cantidad_solicitada'];
						$partesArray[$x]['cantidadRecibida'] = $datos2['cantidad_recibida'];
						$partesArray[$x]['orden_compra'] = $datos2['id_orden_compra'];
						$partesArray[$x]['idParte'] = $datos2['id'];
						$partesArray[$x]['codigo'] = $datos2['codigo'];
						$partesArray[$x]['um'] = $datos2['ie_um'];
						$partesArray[$x]['caja'] = $datos2['caja'];
						$partesArray[$x]['descripcion'] = $datos2['descripcion'];
					}
				} else {
					$sth2 = $this->_db->prepare("SELECT p.id, ocp.id_orden_compra, ocp.cantidad AS cantidad_solicitada, iep.cantidad_recibida_import_export AS cantidad_recibida, p.id_parte, p.ie_um, p.descripcion, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo, iep.caja
					FROM ordenes_compra_partes ocp
					JOIN baselines p
					ON p.id = ocp.id_parte
					JOIN import_export_partes iep
					ON iep.id_orden_compra = ocp.id_orden_compra AND iep.id_parte = ocp.id_parte
					WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ? AND iep.id_factura = ?
					LIMIT 1");

					$sth2->bindParam(1, $partesActuales[$x]['id_parte']);
					$sth2->bindParam(2, $partesActuales[$x]['id_orden_compra']);
					$sth2->bindParam(3, $partesActuales[$x]['id_factura']);
					if(!$sth2->execute()) throw New Exception();

					while ($datos2 = $sth2->fetch()) {
						$partesArray[$x]['cantidadSolicitada'] = $datos2['cantidad_solicitada'];
						$partesArray[$x]['cantidadRecibida'] = $datos2['cantidad_recibida'];
						$partesArray[$x]['orden_compra'] = $datos2['id_orden_compra'];
						$partesArray[$x]['idParte'] = $datos2['id'];
						$partesArray[$x]['codigo'] = $datos2['id_parte'];
						$partesArray[$x]['um'] = $datos2['ie_um'];
						$partesArray[$x]['caja'] = $datos2['caja'];
						$partesArray[$x]['descripcion'] = $datos2['descripcion'];
					}
				}
			}
			$datosArray['partes'] = $partesArray;

			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function modificarFactura($post) {
		try {
			$datosArray = array();
			$partesArray = array();
			
			// Fecha Actual
			$fecha = date('d/m/Y');

			// Nombre de Agente
			$sth = $this->_db->prepare("SELECT nombre, apellidos FROM usuarios WHERE id = ? LIMIT 1");
			$sth->bindParam(1, $_SESSION['login_id']);
			if(!$sth->execute()) throw New Exception();
			$datos = $sth->fetch();
			$agente = $datos['nombre'] . ' ' . $datos['apellidos'];		

			$folio = $post['folio'];
			$datosArray['folio'] = $post['folio'];
			$datosArray['filas'] = $post['filas'];
			$datosArray['agente'] = $agente;

			// Datos de partes
			$conteoFilas = $post['filas'];

			for($x=1; $x<=$conteoFilas; $x++) {
				$sth = $this->_db->prepare("SELECT id_integracion FROM ordenes_compra WHERE id = ?");
				$sth->bindParam(1, $post["ordenCompra$x"]);
				if(!$sth->execute()) throw New Exception();
				$datos = $sth->fetch();

				if ($datos['id_integracion'] == 0) {
					if ($post["ordenCompraNueva$x"] == 1) {
						$sth2 = $this->_db->prepare("SELECT p.id, p.codigo, p.ie_um, p.ie_um_txt, p.descripcion, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo
						FROM ordenes_compra_partes ocp
						JOIN partes p
						ON p.id = ocp.id_parte
						WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ?
						LIMIT 1");
						$sth2->bindParam(1, $post["idParte$x"]);
						$sth2->bindParam(2, $post["ordenCompra$x"]);
						if(!$sth2->execute()) throw New Exception();
					} else {
						// Contador
						$sth2 = $this->_db->prepare("SELECT COUNT(*) AS conteo
							FROM ordenes_compra_partes ocp
							JOIN partes p
							ON p.id = ocp.id_parte
							JOIN import_export_partes iep
							ON iep.id_orden_compra = ocp.id_orden_compra AND iep.id_parte = ocp.id_parte
							WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ? AND iep.id_factura = ?");
						$sth2->bindParam(1, $post["idParte$x"]);
						$sth2->bindParam(2, $post["ordenCompra$x"]);
						$sth2->bindParam(3, $folio);
						if(!$sth2->execute()) throw New Exception();
						$conteo = $sth2->fetchColumn();

						if ($conteo >= 1) {
							$partesArray[$x]['ordenCompraVieja'] = 1;
							$sth2 = $this->_db->prepare("SELECT p.id, p.codigo, p.ie_um, p.ie_um_txt, p.descripcion, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo, iep.caja
								FROM ordenes_compra_partes ocp
								JOIN partes p
								ON p.id = ocp.id_parte
								JOIN import_export_partes iep
								ON iep.id_orden_compra = ocp.id_orden_compra AND iep.id_parte = ocp.id_parte
								WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ? AND iep.id_factura = ?
								LIMIT 1");
							$sth2->bindParam(1, $post["idParte$x"]);
							$sth2->bindParam(2, $post["ordenCompra$x"]);
							$sth2->bindParam(3, $folio);
							if(!$sth2->execute()) throw New Exception();
						} else {
							$partesArray[$x]['ordenCompraVieja'] = 1;
							$sth2 = $this->_db->prepare("SELECT p.id, p.codigo, p.ie_um, p.ie_um_txt, p.descripcion, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo
								FROM ordenes_compra_partes ocp
								JOIN partes p
								ON p.id = ocp.id_parte
								WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ?
								LIMIT 1");
							$sth2->bindParam(1, $post["idParte$x"]);
							$sth2->bindParam(2, $post["ordenCompra$x"]);
							if(!$sth2->execute()) throw New Exception();
						}
					}
					$sth2->bindParam(1, $post["idParte$x"]);
					$sth2->bindParam(2, $post["ordenCompra$x"]);
					$sth2->bindParam(3, $folio);
					if(!$sth2->execute()) throw New Exception();

					$datos2 = $sth2->fetch();
					$partesArray[$x]['cantidadSolicitada'] = $post["cantidadSolicitada$x"];
					$partesArray[$x]['cantidadRecibida'] = $post["cantidadRecibida$x"];
					$partesArray[$x]['idParte'] = $datos2['id'];
					$partesArray[$x]['codigo'] = $datos2['codigo'];
					$partesArray[$x]['um'] = Modelos_Caracteres::importacion($datos2['ie_um']);
					$partesArray[$x]['umTxt'] = $datos2['umTxt'];
					$partesArray[$x]['caja'] = Modelos_Caracteres::importacion($datos2['caja']);
					$partesArray[$x]['descripcionComprador'] = $datos2['descripcion'];
					$partesArray[$x]['descripcion'] = preg_replace('/\<[\/]?(table|tr|td)([^\>]*)\>/i', '', Modelos_Caracteres::importacion($datos2['ie_descripcion']));
					$partesArray[$x]['descripcionIngles'] = $datos2['ie_descripcion_ingles'];
					$partesArray[$x]['fraccion_arancelaria'] = strip_tags($datos2['fraccion_arancelaria']);
					$partesArray[$x]['peso'] = Modelos_Caracteres::importacion($datos2['peso']);
					$partesArray[$x]['pais_origen'] = Modelos_Caracteres::importacion($datos2['pais_origen']);
					$partesArray[$x]['costo'] = number_format((float)$datos2['costo']*1.2, 4, '.', '');
				} else {
					if ($post["ordenCompraNueva$x"] == 1) {
						$sth2 = $this->_db->prepare("SELECT p.id, p.id_parte, p.id_parte_xpress, p.ie_um, p.ie_um_txt, p.descripcion, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo
						FROM ordenes_compra_partes ocp
						JOIN baselines p
						ON p.id = ocp.id_parte
						WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ?
						LIMIT 1");
						$sth2->bindParam(1, $post["idParte$x"]);
						$sth2->bindParam(2, $post["ordenCompra$x"]);
						if(!$sth2->execute()) throw New Exception();
					} else {
						// Contador
						$sth2 = $this->_db->prepare("SELECT COUNT(*) AS conteo
						FROM ordenes_compra_partes ocp
						JOIN baselines p
						ON p.id = ocp.id_parte
						JOIN import_export_partes iep
						ON iep.id_orden_compra = ocp.id_orden_compra AND iep.id_parte = ocp.id_parte
						WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ? AND iep.id_factura = ?");
						$sth2->bindParam(1, $post["idParte$x"]);
						$sth2->bindParam(2, $post["ordenCompra$x"]);
						$sth2->bindParam(3, $folio);
						if(!$sth2->execute()) throw New Exception();
						$conteo = $sth2->fetchColumn();

						$partesArray[$x]['ordenCompraVieja'] = 1;
						if ($conteo >= 1) {
							$sth2 = $this->_db->prepare("SELECT p.id, p.id_parte, p.id_parte_xpress, p.ie_um, p.ie_um_txt, p.descripcion, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo, iep.caja
								FROM ordenes_compra_partes ocp
								JOIN baselines p
								ON p.id = ocp.id_parte
								JOIN import_export_partes iep
								ON iep.id_orden_compra = ocp.id_orden_compra AND iep.id_parte = ocp.id_parte
								WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ? AND iep.id_factura = ?
								LIMIT 1");
							$sth2->bindParam(1, $post["idParte$x"]);
							$sth2->bindParam(2, $post["ordenCompra$x"]);
							$sth2->bindParam(3, $folio);
							if(!$sth2->execute()) throw New Exception();
						} else {
							$sth2 = $this->_db->prepare("SELECT p.id, p.id_parte, p.id_parte_xpress, p.ie_um, p.ie_um_txt, p.ie_descripcion, p.ie_descripcion_ingles, p.fraccion_arancelaria, p.peso, p.pais_origen, ocp.precio AS costo
								FROM ordenes_compra_partes ocp
								JOIN baselines p
								ON p.id = ocp.id_parte
								WHERE ocp.id_parte = ? AND ocp.id_orden_compra = ?
								LIMIT 1");
							$sth2->bindParam(1, $post["idParte$x"]);
							$sth2->bindParam(2, $post["ordenCompra$x"]);
							if(!$sth2->execute()) throw New Exception();
						}
					}

					$datos2 = $sth2->fetch();
					$partesArray[$x]['cantidadSolicitada'] = $post["cantidadSolicitada$x"];
					$partesArray[$x]['cantidadRecibida'] = $post["cantidadRecibida$x"];
					$partesArray[$x]['idParte'] = $datos2['id'];
					$partesArray[$x]['codigo'] = $datos2['id_parte'];
					$partesArray[$x]['codigoXpress'] = $datos2['id_parte_xpress'];
					$partesArray[$x]['um'] = Modelos_Caracteres::importacion($datos2['ie_um']);
					$partesArray[$x]['umTxt'] = $datos2['ie_um_txt'];
					$partesArray[$x]['caja'] = Modelos_Caracteres::importacion($datos2['caja']);
					$partesArray[$x]['descripcionComprador'] = $datos2['descripcion'];
					$partesArray[$x]['descripcion'] = html_entity_decode($datos2['ie_descripcion'], ENT_QUOTES, "UTF-8");
					$partesArray[$x]['descripcionIngles'] = $datos2['ie_descripcion_ingles'];
					$partesArray[$x]['fraccion_arancelaria'] = strip_tags($datos2['fraccion_arancelaria']);
					$partesArray[$x]['peso'] = Modelos_Caracteres::importacion($datos2['peso']);
					$partesArray[$x]['pais_origen'] = Modelos_Caracteres::importacion($datos2['pais_origen']);
					$partesArray[$x]['costo'] = number_format((float)$datos2['costo']*1.2, 4, '.', '');
				}
			}
			$datosArray['partes'] = $partesArray;

			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function generar($post) {
		try {
			$folio = $_POST['folio'];
			$total = $_POST['total'];

			$sth = $this->_db->prepare("DELETE FROM import_export WHERE id = ?");
			$sth->bindParam(1, $folio);
			if(!$sth->execute()) throw New Exception();

			$sth = $this->_db->prepare("DELETE FROM import_export_partes WHERE id_factura = ?");
			$sth->bindParam(1, $folio);
			if(!$sth->execute()) throw New Exception();

			$sth = $this->_db->prepare("INSERT INTO import_export (id, total) VALUES (?, ?)");
			$sth->bindParam(1, $folio);
			$sth->bindParam(2, $total);
			if(!$sth->execute()) throw New Exception();
			$idFactura = $folio;

			$ordenesCompraPendientes = array();
			$ordenesCompra = array();

			// Por cada linea
			for($x=1; $x<=$_POST['filas']; $x++) {
				// ID de la orden de compra
				$ordenesCompra[] = $_POST["ordenCompra$x"];

				// Si la cantidad que se recibio es diferente a la solicitada en la orden de compra, se agregan los IDs de las ordenes de compra pendientes a un arreglo
				if ($_POST["cantidad$x"] != $_POST["cantidadSolicitada$x"]) {
					if (!in_array($_POST["ordenCompra$x"], $ordenesCompraPendientes)) {
						$ordenesCompraPendientes[] = $_POST["ordenCompra$x"];
					}
				}

				// Se checa de que integracion es la orden de compra
				$sth = $this->_db->prepare("SELECT id_integracion FROM ordenes_compra WHERE id = ?");
				$sth->bindParam(1, $_POST["ordenCompra$x"]);
				if(!$sth->execute()) throw New Exception();
				$datos = $sth->fetch();

				// Se agrega la linea a la tabla de import_export_partes
				$sth = $this->_db->prepare("INSERT INTO import_export_partes (id_factura, id_orden_compra, id_parte, caja, costo, id_parte_integracion, cantidad_recibida_import_export, cantidad_pendiente, descripcion_espanol) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
				$sth->bindParam(1, $idFactura);
				$sth->bindParam(2, $_POST["ordenCompra$x"]);
				$sth->bindParam(3, $_POST["idParte$x"]);
				$sth->bindParam(4, $_POST["caja$x"]);
				$sth->bindParam(5, $_POST["costo$x"]);
				$sth->bindParam(6, $datos["id_integracion"]);
				$sth->bindParam(7, $_POST["cantidad$x"]);
				$sth->bindParam(8, $_POST["cantidad$x"]);
				$sth->bindParam(9, html_entity_decode($_POST["descripcion$x"]));
				if(!$sth->execute()) throw New Exception();
				$idPartida = $this->_db->lastInsertId();

				// Se disminuyen las partes pendientes
				$sth = $this->_db->prepare("UPDATE ordenes_compra_partes SET cantidad_pendiente = cantidad_pendiente - ? WHERE id_orden_compra = ? AND id_parte = ?");
				$sth->bindParam(1, $_POST["cantidad$x"]);
				$sth->bindParam(2, $_POST["ordenCompra$x"]);
				$sth->bindParam(3, $_POST["idParte$x"]);
				if(!$sth->execute()) throw New Exception();

				// Si es de matriz
				if ($datos['id_integracion'] == 0) {
					// Actualizar la descripcion, fraccion, peso y pais de la parte
					$sth = $this->_db->prepare("UPDATE partes SET ie_descripcion = ?, ie_descripcion_ingles = ?, fraccion_arancelaria = ?, peso = ?, pais_origen = ?, ie_um = ?, ie_um_txt = ? WHERE id = ?");
					$sth->bindParam(1, html_entity_decode($_POST["descripcion$x"]));
					$sth->bindParam(2, strtoupper($_POST["descripcionIngles$x"]));
					$sth->bindParam(3, $_POST["fraccionArancelaria$x"]);
					$sth->bindParam(4, $_POST["peso$x"]);
					$sth->bindParam(5, strtoupper($_POST["origen$x"]));
					$sth->bindParam(6, strtoupper($_POST["um$x"]));
					$sth->bindParam(7, $_POST["umTxt$x"]);
					$sth->bindParam(8, $_POST["idParte$x"]);
					if(!$sth->execute()) throw New Exception();
				// Si es integracion
				} else {
					// Actualizar la descripcion, fraccion, peso y pais de la parte
					$sth = $this->_db->prepare("UPDATE baselines SET ie_descripcion = ?, ie_descripcion_ingles = ?, fraccion_arancelaria = ?, peso = ?, pais_origen = ?, ie_um = ?, ie_um_txt = ? WHERE id = ?");
					$sth->bindParam(1, html_entity_decode($_POST["descripcion$x"]));
					$sth->bindParam(2, strtoupper($_POST["descripcionIngles$x"]));
					$sth->bindParam(3, $_POST["fraccionArancelaria$x"]);
					$sth->bindParam(4, $_POST["peso$x"]);
					$sth->bindParam(5, strtoupper($_POST["origen$x"]));
					$sth->bindParam(6, strtoupper($_POST["um$x"]));
					$sth->bindParam(7, $_POST["umTxt$x"]);
					$sth->bindParam(8, $_POST["idParte$x"]);
					if(!$sth->execute()) throw New Exception();
				}
			}

			foreach($ordenesCompraPendientes as $ordenCompra) {
				$sth = $this->_db->prepare("UPDATE ordenes_compra SET pendiente = 1 WHERE id = ?");
				$sth->bindParam(1, $ordenCompra);
				if(!$sth->execute()) throw New Exception();
			}

			foreach($ordenesCompra as $ordenCompra) {
				$sth = $this->_db->prepare("UPDATE ordenes_compra SET import_export = 1 WHERE id = ?");
				$sth->bindParam(1, $ordenCompra);
				if(!$sth->execute()) throw New Exception();
			}

			return $idFactura;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function descargar($datos) {
		$idFacturaGenerada = $this->generar($datos);
		$this->excel($idFacturaGenerada);
	}

	public function visualizar($id) {
		$this->pdf($id,0,1);
	}

	public function pdf($id, $descargar = null, $visualizar = null) {
		$sth = $this->_db->prepare("SELECT id, total, fecha FROM import_export WHERE id = ?");
		$sth->bindParam(1, $id);
		if(!$sth->execute()) throw New Exception();
		$datos = $sth->fetch();

		$folio = $datos['id'];
		$total = $datos['total'];
		$fechaCreacion = Modelos_Fecha::formatearFechaHora($datos['fecha']);
		
		require_once(APP . 'plugins/tcpdf/tcpdf.php');

		$pdf = new XIPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Xpress Industrial');
		$pdf->SetTitle('Factura Import/Export - Xpress Industrial');
		$pdf->SetSubject('Factura Import/Export - Xpress Industrial');
		$pdf->SetKeywords('Xpress Industrial, Factura Import/Export');
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		$pdf->SetFont('helvetica', '', 10);
		$pdf->AddPage();

		$htmlPartidas = '';
		$x=1;

		$sth = $this->_db->prepare("SELECT CONCAT(oc.alfanumerico, '-', iep.id_orden_compra) AS orden_compra, id_parte, id_parte_integracion, caja, costo, cantidad_recibida_import_export AS cantidad
			FROM import_export_partes iep
			JOIN ordenes_compra oc
			ON oc.id = iep.id_orden_compra
			WHERE id_factura = ?
			ORDER BY caja ASC");
		$sth->bindParam(1, $id);
		if(!$sth->execute()) throw New Exception();

		$i = 19;
		$x = 1;

		while ($datos = $sth->fetch()) {
			$idOrdenCompra = $datos['orden_compra'];
			$idParte = $datos['id_parte'];
			$idParteIntegracion = $datos['id_parte_integracion'];
			$caja = $datos['caja'];
			$costo = $datos['costo'];
			$cantidad = $datos['cantidad'];

			if ($idParteIntegracion == 0) {
				$sth2 = $this->_db->prepare("SELECT p.id, codigo, ie_descripcion, ie_descripcion_ingles, ie_um, fraccion_arancelaria, peso, pais_origen
					FROM partes p
					WHERE p.id = ?
					LIMIT 1");
				$sth2->bindParam(1, $idParte);
				if(!$sth2->execute()) throw New Exception();
				
				while ($datos2 = $sth2->fetch()) {
					if ($cantidad != 0) {
						$htmlPartidas .= '<tr>';
						$htmlPartidas .= '<td style="text-align: center;">' . $x . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $caja . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $cantidad . '<br />' . $datos2['ie_um'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $idOrdenCompra . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['codigo'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['ie_descripcion'] . '<br />' . $datos2['ie_descripcion_ingles'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['fraccion_arancelaria'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['peso'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['pais_origen'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $costo . '</td>';
						
						$cantidadTotal = number_format($costo*$cantidad, 4, '.', '');
						$htmlPartidas .= '<td style="text-align: center;">' . $cantidadTotal . '</td>';
						$htmlPartidas .= '</tr>';
						$x++;
					}
				}
			} else {
				$sth2 = $this->_db->prepare("SELECT p.id, id_parte, ie_descripcion, ie_descripcion_ingles, ie_um, fraccion_arancelaria, peso, pais_origen
					FROM baselines p
					WHERE p.id = ?
					LIMIT 1");
				$sth2->bindParam(1, $idParte);
				if(!$sth2->execute()) throw New Exception();
				
				while ($datos2 = $sth2->fetch()) {
					if ($cantidad != 0) {
						$htmlPartidas .= '<tr>';
						$htmlPartidas .= '<td style="text-align: center;">' . $x . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $caja . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $cantidad . '<br />' . $datos2['ie_um'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $idOrdenCompra . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['id_parte'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['ie_descripcion'] . '<br />' . $datos2['ie_descripcion_ingles'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['fraccion_arancelaria'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['peso'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $datos2['pais_origen'] . '</td>';
						$htmlPartidas .= '<td style="text-align: center;">' . $costo . '</td>';
						
						$cantidadTotal = number_format($costo*$cantidad, 4, '.', '');
						$htmlPartidas .= '<td style="text-align: center;">' . $cantidadTotal . '</td>';
						$htmlPartidas .= '</tr>';
						$x++;
					}
				}
			}
		}
		
		$stasis = STASIS;

		$html = <<<EOF
		<style type="text/css">
		.titulo {
		font-size: 10px;
		font-weight: bold;
		}
		.sinBorde {
		border-collapse: collapse;
		border: none;
		}
		.sinBorde tr td {
		font-family: Arial;
		font-size: 8px;
		border: none;
		}
		#partidas {
			border-collapse: collapse;
			font-size: 6px;
		}
		#partidas tr td {
			font-family: Arial;
			font-size: 6px;
		}
		</style>
		</head><body>
		<table class="sinBorde" style="text-align: left; height: 178px;" border="0" cellpadding="0" cellspacing="3">
		<tbody>
		<tr>
		<td style="height: 31px; width: 170px;"><img src="$stasis/img/logo_xpress_group.png" width="170" alt=""></td>
		<td style="height: 31px; text-align: center; width: 250px;">
		<span class="titulo">XPRESS INDUSTRIAL GROUP</span><br>
		9785 MARCONI DR. STE. M<br>
		SAN DIEGO, CA 92154<br>
		PHONE: (619) 270 8577 (619) 270 8577</td>
		<td style="height: 31px; text-align: right; width: 95px;"><span style="font-weight: bold; font-size: 10px;">INVOICE/FACTURA</span><br /><span style="font-weight: bold; font-size: 14px;">#$folio</span><br>
		<span style="font-weight: bold;">Date:</span> $fechaCreacion</td>
		</tr>
		<tr>
		<td style="height: 57px; width: 180px;"><br /><span style="font-weight: bold;">Bill To:</span><br>
		XPRESS INDUSTRIAL S DE RL DE CV<br />
		RFC XINO090313GF5<br />
		JOSE MA MORELOS 57<br />
		EJIDO CHILPANCINGO <br />
		TIJUANA B.C.
		</td>
		<td style="height: 57px; width: 207px; text-align: center;"><br /><span style="font-weight: bold;">Ship To:</span><br>
		XPRESS INDUSTRIAL S DE RL DE CV<br />
		RFC XINO090313GF5<br />
		JOSE MA MORELOS 57<br />
		EJIDO CHILPANCINGO <br />
		TIJUANA B.C.
		</td>
		<td style="height: 57px; width: 130px; text-align: right;">
		</td>
		</tr>
		</tbody>
		</table>
		<br><br />

		<table id="partidas" style="font-size: 6px; text-align: left; width: 100%; height: 59px;" border="1" cellpadding="2" cellspacing="0">
		<tbody>
		<tr>
		<td style="width:15px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">#</td>
		<td style="width:35px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">Caja</td>
		<td style="width:50px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">Qty/UOM</td>
		<td style="width:40px; text-align: center; font-weight: bold; background-color: rgb(228, 228, 228);">PO Number</td>
		<td style="width:60px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">Item #</td>
		<td style="width:157px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">Descripción/Description</td>
		<td style="width:40px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">Fracción</td>
		<td style="width:25px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">Peso</td>
		<td style="width:50px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">País de Orígen</td>
		<td style="width:30px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">U. Price</td>
		<td style="width:30px; text-align: center; background-color: rgb(228, 228, 228); font-weight: bold;">Ext. Dlls.</td>
		</tr>
		$htmlPartidas
		</tbody>
		</table><br />

		<br><table class="sinBorde" style="text-align: left; width: 367px; height: 59px;" border="1" cellpadding="2" cellspacing="0">
				<tbody>
					<tr>
						<td style="width: 432px;" rowspan="3"><strong>Notes:</strong> $observaciones</td>
						<td style="width: 100px; text-align: right;"><span style="font-weight: bold;">Total:</span> $ $total</td>
					</tr>
				</tbody>
			</table>
		</body></html>
EOF;

		$pdf->writeHTML($html, true, false, true, false, '');
		$pdf->lastPage();

		if ($descargar == 1) {
			$pdf->Output('Factura_ImportExport.pdf', 'D');
		} elseif ($visualizar == 1) {
			$pdf->Output('Factura_ImportExport.pdf', 'I');
		} else {
			$nombrePdf = uniqid() . '.pdf';
			$archivo = $pdf->Output(ROOT_DIR . "/data/tmp/$nombrePdf", 'F');
			return $nombrePdf;
		}

		exit();
	}

	public function recibir($id) {
		try {
			$datosArray = array();
			$partesArray = array();

			$sth = $this->_db->prepare("SELECT nombre, apellidos FROM usuarios WHERE id = ? LIMIT 1");
			$sth->bindParam(1, $_SESSION['login_id']);
			if(!$sth->execute()) throw New Exception();
			$datos = $sth->fetch();
			$agente = $datos['nombre'] . ' ' . $datos['apellidos'];
			$datosArray['agente'] = $agente;
			$datosArray['id'] = $id;

			// Se jalan las ordenes de compra de esta factura de importación
			$sth = $this->_db->prepare("SELECT DISTINCT o.id_orden_compra, o.id_parte_integracion
				FROM import_export_partes o
				WHERE o.id_factura = ? ORDER BY id DESC");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();

			// Por cada orden de compra, se saca si es de integración o de matriz
			// 208 (Welch) / 228 (Xpress)
			$x = 1;
			while ($datosX = $sth->fetch()) {
				$idOrdenCompra = $datosX['id_orden_compra'];
				$integracion = $datosX['id_parte_integracion'];

				// Si es de matriz
				if ($integracion == 0) {
					$sth2 = $this->_db->prepare("SELECT p.id, iep.cantidad_pendiente AS cantidad_ie, ocp.cantidad AS cantidad_oc, pm.nombre AS um, CONCAT(oc.alfanumerico, '-', iep.id_orden_compra) AS orden_compra, iep.id_orden_compra AS orden_compra_hidden, p.codigo, p.descripcion
						FROM import_export_partes iep
						JOIN ordenes_compra_partes ocp
						ON ocp.id_orden_compra = iep.id_orden_compra AND ocp.id_parte = iep.id_parte
						JOIN ordenes_compra oc
						ON oc.id = iep.id_orden_compra
						JOIN partes p
						ON p.id = iep.id_parte
						JOIN partes_medidas pm
						ON pm.id = p.id_unidad_compra
						WHERE iep.id_orden_compra = ? AND iep.id_factura = ?");
					$sth2->bindParam(1, $idOrdenCompra);
					$sth2->bindParam(2, $id);
					if(!$sth2->execute()) throw New Exception();

					while ($datos = $sth2->fetch()) {
						// Si la cantidad recibida es 0
						if ($datos['cantidad_ie'] == 0) continue;
						$partesArray[$x]['idParte'] = $datos['id'];
						$partesArray[$x]['ordenCompra'] = $datos['orden_compra'];
						$partesArray[$x]['codigo'] = $datos['codigo'];
						$partesArray[$x]['descripcion'] = $datos['descripcion'];
						$partesArray[$x]['um'] = $datos['um'];
						$partesArray[$x]['cantidad_oc'] = $datos['cantidad_oc'];
						$partesArray[$x]['ordenCompraHidden'] = $datos['orden_compra_hidden'];
						$partesArray[$x]['cantidad_ie'] = $datos['cantidad_ie'];
						$partesArray[$x]['integracion'] = $integracion;
						$x++;
					}
				// Si es de intregracion
				} else {
					$sth2 = $this->_db->prepare("SELECT p.id, iep.cantidad_pendiente AS cantidad_ie, ocp.cantidad AS cantidad_oc, p.uom_compra AS um, CONCAT(oc.alfanumerico, '-', iep.id_orden_compra) AS orden_compra, iep.id_orden_compra AS orden_compra_hidden, p.id_parte AS codigo, p.descripcion
						FROM import_export_partes iep
						JOIN ordenes_compra_partes ocp
						ON ocp.id_orden_compra = iep.id_orden_compra AND ocp.id_parte = iep.id_parte
						JOIN ordenes_compra oc
						ON oc.id = iep.id_orden_compra
						JOIN baselines p
						ON p.id = iep.id_parte
						WHERE iep.id_orden_compra = ? AND iep.id_factura = ?");
					$sth2->bindParam(1, $idOrdenCompra);
					$sth2->bindParam(2, $id);
					if(!$sth2->execute()) throw New Exception();

					while ($datos = $sth2->fetch()) {
						// Si la cantidad recibida es 0
						if ($datos['cantidad_ie'] == 0) continue;
						$partesArray[$x]['idParte'] = $datos['id'];
						$partesArray[$x]['ordenCompra'] = $datos['orden_compra'];
						$partesArray[$x]['codigo'] = $datos['codigo'];
						$partesArray[$x]['descripcion'] = $datos['descripcion'];
						$partesArray[$x]['um'] = $datos['um'];
						$partesArray[$x]['cantidad_oc'] = $datos['cantidad_oc'];
						$partesArray[$x]['ordenCompraHidden'] = $datos['orden_compra_hidden'];
						$partesArray[$x]['cantidad_ie'] = $datos['cantidad_ie'];
						$partesArray[$x]['integracion'] = $integracion;
						$x++;
					}
				}
			}

			$datosArray['partes'] = $partesArray;
			$datosArray['conteoPartes'] = $x-1;
			
			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function recibirMaterial($post) {
		try {
			$idEjercicio = date('y');
			$folioFactura = $post['folio'];
			$ordenesCompraPendientes = array();
			$ordenesCompra = array();
			$facturaPendiente = 0;

			// Por cada linea
			for($x=1; $x<=$post['filas']; $x++) {
				$idOrdenCompra = $post["ordenCompra$x"];
				$idParte = $post["idParte$x"];
				$cantidad = $post["cantidad$x"];

				// ID de la orden de compra
				$ordenesCompra[] = $_POST["ordenCompra$x"];

				// Si alguna de las lineas no llegaron completas, activar la bandera de facturaPendiente
				
				if ($_POST["cantidad$x"] != $_POST["cantidad-ie$x"]) {
					$facturaPendiente = 1;
				}

				// Se disminuyen las partes pendientes
				$sth = $this->_db->prepare("UPDATE import_export_partes SET cantidad_pendiente = cantidad_pendiente - ? WHERE id_orden_compra = ? AND id_parte = ? AND id_factura = ?");
				$sth->bindParam(1, $_POST["cantidad$x"]);
				$sth->bindParam(2, $_POST["ordenCompra$x"]);
				$sth->bindParam(3, $_POST["idParte$x"]);
				$sth->bindParam(4, $folioFactura);
				if(!$sth->execute()) throw New Exception();

				// Se verifica el destino de las partes y se crean los traspasos correspondientes
				switch($post["destino$x"]) {
					// En caso que se mande a facturar, jalar el precio de la orden de compra correspondiente
					case 'f':
					$sth = $this->_db->prepare("SELECT precio FROM ordenes_compra_partes WHERE id_orden_compra = ? AND id_parte = ?");
					$sth->bindParam(1, $post["ordenCompra$x"]);
					$sth->bindParam(2, $post["idParte$x"]);
					if(!$sth->execute()) throw New Exception();
					$dato = $sth->fetch();
					$precio = $dato['precio'];

					$sth = $this->_db->prepare("INSERT INTO facturas_partes (id_parte, cantidad, precio, id_import_export, id_integracion, id_orden_compra, import_export) VALUES (?, ?, ?, ?, ?, ?, 1)");
					$sth->bindParam(1, $post["idParte$x"]);
					$sth->bindParam(2, $post["cantidad$x"]);
					$sth->bindParam(3, $precio);
					$sth->bindParam(4, $folioFactura);
					$sth->bindParam(5, $post["integracion$x"]);
					$sth->bindParam(6, $post["ordenCompra$x"]);
					if(!$sth->execute()) throw New Exception();
					break;

					case '1':
					if ($traspasoXpress == 0) {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos (id_genera, id_almacen_origen, id_almacen_destino, id_integracion) VALUES (?, 0, ?, 0)");
							$sth->bindParam(1, $_SESSION['login_id']);
							$sth->bindParam(2, $post["destino$x"]);
							if(!$sth->execute()) throw New Exception();
							$traspasoXpress = $this->_db->lastInsertId();

							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoXpress);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					} else {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoXpress);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					}
					break;

					case '14':
					if ($traspasoSmk == 0) {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos (id_genera, id_almacen_origen, id_almacen_destino, id_integracion) VALUES (?, 0, ?, 4)");
							$sth->bindParam(1, $_SESSION['login_id']);
							$sth->bindParam(2, $post["destino$x"]);
							if(!$sth->execute()) throw New Exception();
							$traspasoSmk = $this->_db->lastInsertId();

							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoSmk);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					} else {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoSmk);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					}
					break;

					case '13':
					if ($traspasoTeleflex == 0) {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos (id_genera, id_almacen_origen, id_almacen_destino, id_integracion) VALUES (?, 0, ?, 3)");
							$sth->bindParam(1, $_SESSION['login_id']);
							$sth->bindParam(2, $post["destino$x"]);
							if(!$sth->execute()) throw New Exception();
							$traspasoTeleflex = $this->_db->lastInsertId();

							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoTeleflex);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					} else {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoTeleflex);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					}
					break;

					case '16':
					if ($traspasoThermofisher == 0) {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos (id_genera, id_almacen_origen, id_almacen_destino, id_integracion) VALUES (?, 0, ?, 5)");
							$sth->bindParam(1, $_SESSION['login_id']);
							$sth->bindParam(2, $post["destino$x"]);
							if(!$sth->execute()) throw New Exception();
							$traspasoThermofisher = $this->_db->lastInsertId();

							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoThermofisher);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					} else {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoThermofisher);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					}
					break;

					case '15':
					if ($traspasoWelchAllyn == 0) {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos (id_genera, id_almacen_origen, id_almacen_destino, id_integracion) VALUES (?, 0, ?, 2)");
							$sth->bindParam(1, $_SESSION['login_id']);
							$sth->bindParam(2, $post["destino$x"]);
							if(!$sth->execute()) throw New Exception();
							$traspasoWelchAllyn = $this->_db->lastInsertId();

							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoWelchAllyn);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					} else {
						if ($cantidad != 0) {
							$sth = $this->_db->prepare("INSERT INTO traspasos_partes (id_traspaso, id_parte, cantidad, id_integracion, cantidad_pendiente, id_orden_compra) VALUES (?, ?, ?, ?, ?, ?)");
							$sth->bindParam(1, $traspasoWelchAllyn);
							$sth->bindParam(2, $idParte);
							$sth->bindParam(3, $cantidad);
							$sth->bindParam(4, $post["integracion$x"]);
							$sth->bindParam(5, $cantidad);
							$sth->bindParam(6, $post["ordenCompra$x"]);
							if(!$sth->execute()) throw New Exception();
						}
					}
					break;
				}
			}

			// Especificar en la tabla que la factura fue recibida
			$sth = $this->_db->prepare("UPDATE import_export SET recibido = 1, fecha_recibido = NOW() WHERE id = ?");
			$sth->bindParam(1, $post['folio']);
			if(!$sth->execute()) throw New Exception();

			// Si la factura llego incompleta, especificar que fue recibida, pero incompleta
			if ($facturaPendiente == 1) {
				$sth = $this->_db->prepare("UPDATE import_export SET pendiente = 1 WHERE id = ?");
				$sth->bindParam(1, $post['folio']);
				if(!$sth->execute()) throw New Exception();
			// Si llego compelta, especificar que fue recibida y que no hay pendientes
			} else {
				$sth = $this->_db->prepare("UPDATE import_export SET pendiente = 0 WHERE id = ?");
				$sth->bindParam(1, $post['folio']);
				if(!$sth->execute()) throw New Exception();
			}

			header('Location:' . STASIS. '/reportes/import_export/1');
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function txt($id) {
		// Abriendo y creando archivo
		$fp = fopen(ROOT_DIR . "/data/privada/txt/$id.txt",'wb');

		// Se jalan datos principales
		$sth = $this->_db->prepare("SELECT CONCAT(oc.alfanumerico, '-', iep.id_orden_compra) AS orden_compra, id_parte, id_parte_integracion, caja, costo, cantidad_recibida_import_export AS cantidad
			FROM import_export_partes iep
			JOIN ordenes_compra oc
			ON oc.id = iep.id_orden_compra
			WHERE id_factura = ?
			ORDER BY caja ASC");	
		$sth->bindParam(1, $id);
		if(!$sth->execute()) throw New Exception();

		$x = 1;
		$total = 0;
		$pesoTotal = 0;
		$partidas = '';
		$totalPartidas = 0;

		while ($datos = $sth->fetch()) {
			$idParte = $datos['id_parte'];
			$idParteIntegracion = $datos['id_parte_integracion'];
			$caja = $datos['caja'];
			$valorMercancia = $datos['costo'];
			$cantidad = $datos['cantidad'];

			if ($idParteIntegracion == 0) {
				$sth2 = $this->_db->prepare("SELECT p.id, codigo, ie_descripcion, ie_descripcion_ingles, ie_um, ie_um_txt, fraccion_arancelaria, peso, pais_origen
					FROM partes p
					WHERE p.id = ?
					LIMIT 1");
				$sth2->bindParam(1, $idParte);
				if(!$sth2->execute()) throw New Exception();
				
				while ($datos2 = $sth2->fetch()) {
					if ($cantidad != 0) {
						$totalPartidas++;
						$pesoVariable = preg_replace("/[^0-9,.]/", "", $datos2['peso']);
						$pesoTotal += $pesoVariable;

						$fraccionParte = str_replace('.', '', Modelos_Caracteres::importacion(strip_tags($datos2['fraccion_arancelaria'])));
						$descripcionParte = Modelos_Caracteres::importacion(strip_tags($datos2['ie_descripcion']));
						$noParte = $datos2['codigo'];
						$umTxt = $datos2['ie_um_txt'];
						$totalMercancia = number_format($valorMercancia*$cantidad, 3, '.', '');
						$paisOrigen = substr(Modelos_Caracteres::importacion(strip_tags($datos2['pais_origen'])), 0, 3);
						$peso = number_format(floatval($pesoVariable), 2, '.', '');

						$partidas .= "551|$fraccionParte|$descripcionParte|$noParte|$totalMercancia|$cantidad|$umTxt|$totalMercancia|0|0|6|$marca|$modelo|$paisOrigen|USA|||||0||$peso|||USD|
558||
559|$marca|$modelo|||
";
					}
				}
			} else {
				$sth2 = $this->_db->prepare("SELECT p.id, id_parte, ie_descripcion, ie_descripcion_ingles, ie_um, ie_um_txt, fraccion_arancelaria, peso, pais_origen
					FROM baselines p
					WHERE p.id = ?
					LIMIT 1");
				$sth2->bindParam(1, $idParte);
				if(!$sth2->execute()) throw New Exception();
				
				while ($datos2 = $sth2->fetch()) {
					if ($cantidad != 0) {
						$totalPartidas++;
						$pesoVariable = preg_replace("/[^0-9,.]/", "", $datos2['peso']);
						$pesoTotal += $pesoVariable;

						$fraccionParte = str_replace('.', '', Modelos_Caracteres::importacion(strip_tags($datos2['fraccion_arancelaria'])));
						$descripcionParte = Modelos_Caracteres::importacion(strip_tags($datos2['ie_descripcion']));
						$noParte = $datos2['codigo'];
						$umTxt = $datos2['ie_um_txt'];
						$totalMercancia = number_format($valorMercancia*$cantidad, 3, '.', '');
						$paisOrigen = substr(Modelos_Caracteres::importacion(strip_tags($datos2['pais_origen'])), 0, 3);
						$peso = number_format(floatval($pesoVariable), 2, '.', '');

						$partidas .= "551|$fraccionParte|$descripcionParte|$noParte|$totalMercancia|$cantidad|$umTxt|$totalMercancia|0|0|6|$marca|$modelo|$paisOrigen|USA|||||0||$peso|||USD|
558||
559|$marca|$modelo|||
";
					}
				}
			}
		}

		// Total de la factura
		$sth = $this->_db->prepare("SELECT total, fecha FROM import_export WHERE id = ?");
		$sth->bindParam(1, $id);
		if(!$sth->execute()) throw New Exception();
		$datos = $sth->fetch();
		$valorDlls = $datos['total'];

		// Peso totalizado
		$pesoTotal = number_format($pesoTotal, 2, '.', '');

		// Fecha
		$fechaActual = date('Ymd');

		$contenido = "501|1|C1||XINGF5|0|0|0|0|0|$pesoTotal|1|$totalPartidas|||||
505|$id|$fechaActual|DAP|USD|$valorDlls|$valorDlls|XPRESS|
" . $partidas . "999|";

		// $contenido = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $contenido);

		$contenido = iconv("UTF-8", "WINDOWS-1252", $contenido);
		fwrite($fp,$contenido);
		fclose($fp);
		Modelos_Descarga::descargarArchivo(ROOT_DIR . "/data/privada/txt/$id.txt", "$id.txt");
	}

	public function excel($id) {
		require_once(APP . 'inc/phpexcel/PHPExcel/IOFactory.php');
		require_once(APP . 'inc/phpexcel/phpexcel.php');

		$xlsx = PHPExcel_IOFactory::createReader('Excel2007');
		$xlsx = $xlsx->load(ROOT_DIR . '/data/privada/props/import_export.xlsx');
		$xlsx->setActiveSheetIndex(0);

		$sth = $this->_db->prepare("SELECT fecha, total, status FROM import_export WHERE id = ?");
		$sth->bindParam(1, $id);
		if(!$sth->execute()) throw New Exception();
		$datos = $sth->fetch();
		$fecha = $datos['fecha'];
		$totalFactura = $datos['total'];
		$statusFactura = $datos['status'];

		$xlsx->getActiveSheet()->setCellValue('F5', $id)           
								->setCellValue('G5', Modelos_Fecha::formatearFechaUsa($fecha));

		$sth = $this->_db->prepare("SELECT CONCAT(oc.alfanumerico, '-', iep.id_orden_compra) AS orden_compra, id_parte, id_parte_integracion, caja, costo, cantidad_recibida_import_export AS cantidad
			FROM import_export_partes iep
			JOIN ordenes_compra oc
			ON oc.id = iep.id_orden_compra
			WHERE id_factura = ?
			ORDER BY caja ASC");	
		$sth->bindParam(1, $id);
		if(!$sth->execute()) throw New Exception();

		$i = 19;
		$x = 1;
		$total = 0;
		$pesoTotal = 0;
		$totalPartidas = 0;

		while ($datos = $sth->fetch()) {
			$idOrdenCompra = $datos['orden_compra'];
			$idParte = $datos['id_parte'];
			$idParteIntegracion = $datos['id_parte_integracion'];
			$caja = $datos['caja'];
			$costo = $datos['costo'];
			$cantidad = $datos['cantidad'];

			if ($idParteIntegracion == 0) {
				$sth2 = $this->_db->prepare("SELECT p.id, codigo, ie_descripcion, ie_descripcion_ingles, ie_um, fraccion_arancelaria, peso, pais_origen
					FROM partes p
					WHERE p.id = ?
					LIMIT 1");
				$sth2->bindParam(1, $idParte);
				if(!$sth2->execute()) throw New Exception();
				
				while ($datos2 = $sth2->fetch()) {
					if ($cantidad != 0) {
						if ($statusFactura == 0) {
							// Si la cadena tiene un codigo de color
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $caja, $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('A' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('A' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['ie_descripcion'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('E' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('E' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['fraccion_arancelaria'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('F' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('F' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['peso'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('G' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('G' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['pais_origen'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('H' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('H' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
						}

						$cantidadTotal = number_format($costo*$cantidad, 4, '.', '');
						$pesoVariable = preg_replace("/[^0-9,.]/", "", $datos2['peso']);
						$pesoTotal += $pesoVariable;
						$xlsx->getActiveSheet()
				                              ->setCellValueExplicit('A' . $i, Modelos_Caracteres::importacion(strip_tags($caja)), PHPExcel_Cell_DataType::TYPE_STRING)
				                              ->setCellValue('B' . $i, $cantidad)
				                              ->setCellValue('C' . $i, $idOrdenCompra)
				                              ->setCellValue('D' . $i, $datos2['codigo'])
				                              ->setCellValue('E' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['ie_descripcion'])))
				                              ->setCellValue('F' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['fraccion_arancelaria'])))
				                              ->setCellValue('G' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['peso'])))
				                              ->setCellValue('H' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['pais_origen'])))
				                              ->setCellValue('I' . $i, $costo)
				                              ->setCellValue('J' . $i, $cantidadTotal);
                        $xlsx->getActiveSheet()->getStyle('E' . $i)->getAlignment()->setWrapText(true);
                        $xlsx->getActiveSheet()->getRowDimension($i)->setRowHeight(-1);
			          	$i++;

			          	preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['ie_um'], $flagColor);
			 			if(count($flagColor[0]) >= 1) {
						    $xlsx->getActiveSheet()->getStyle('B' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
							$xlsx->getActiveSheet()->getStyle('B' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
						}

				        $xlsx->getActiveSheet()
				                              ->setCellValue('B' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['ie_um'])))
				                              ->setCellValue('E' . $i, $datos2['ie_descripcion_ingles']);
				        $xlsx->getActiveSheet()->getStyle('E' . $i)->getAlignment()->setWrapText(true);
				        $xlsx->getActiveSheet()->getRowDimension($i)->setRowHeight(-1);
			          	$i++;
						$x++;
						$totalPartidas++;
					}
				}
			} else {
				$sth2 = $this->_db->prepare("SELECT p.id, id_parte, ie_descripcion, ie_descripcion_ingles, ie_um, fraccion_arancelaria, peso, pais_origen
					FROM baselines p
					WHERE p.id = ?
					LIMIT 1");
				$sth2->bindParam(1, $idParte);
				if(!$sth2->execute()) throw New Exception();
				
				while ($datos2 = $sth2->fetch()) {
					if ($cantidad != 0) {
						if ($statusFactura == 0) {
							// Si la cadena tiene un codigo de color
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $caja, $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('A' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('A' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['ie_descripcion'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('E' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('E' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['fraccion_arancelaria'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('F' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('F' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['peso'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('G' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('G' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
							preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['pais_origen'], $flagColor);
				 			if(count($flagColor[0]) >= 1) {
							    $xlsx->getActiveSheet()->getStyle('H' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
								$xlsx->getActiveSheet()->getStyle('H' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
							}
						}

						$cantidadTotal = number_format($costo*$cantidad, 4, '.', '');
						$pesoVariable = preg_replace("/[^0-9,.]/", "", $datos2['peso']);
						$pesoTotal += $pesoVariable;
						$xlsx->getActiveSheet()
				                              ->setCellValueExplicit('A' . $i, Modelos_Caracteres::importacion(strip_tags($caja)), PHPExcel_Cell_DataType::TYPE_STRING)
				                              ->setCellValue('B' . $i, $cantidad)
				                              ->setCellValue('C' . $i, $idOrdenCompra)
				                              ->setCellValue('D' . $i, $datos2['id_parte'])
				                              ->setCellValue('E' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['ie_descripcion'])))
				                              ->setCellValue('F' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['fraccion_arancelaria'])))
				                              ->setCellValue('G' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['peso'])))
				                              ->setCellValue('H' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['pais_origen'])))
				                              ->setCellValue('I' . $i, $costo)
				                              ->setCellValue('J' . $i, $cantidadTotal);
                        $xlsx->getActiveSheet()->getStyle('E' . $i)->getAlignment()->setWrapText(true);
                        $xlsx->getActiveSheet()->getRowDimension($i)->setRowHeight(-1);
			          	$i++;

			          	preg_match_all('/#(?:[0-9a-fA-F]{6})/', $datos2['ie_um'], $flagColor);
			 			if(count($flagColor[0]) >= 1) {
						    $xlsx->getActiveSheet()->getStyle('B' . $i)->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
							$xlsx->getActiveSheet()->getStyle('B' . $i)->getFill()->getStartColor()->setARGB('A6A6A6');
						}

				        $xlsx->getActiveSheet()
				                              ->setCellValue('B' . $i, Modelos_Caracteres::importacion(strip_tags($datos2['ie_um'])))
				                              ->setCellValue('E' . $i, $datos2['ie_descripcion_ingles']);
				        $xlsx->getActiveSheet()->getStyle('E' . $i)->getAlignment()->setWrapText(true);
				        $xlsx->getActiveSheet()->getRowDimension($i)->setRowHeight(-1);
			          	$i++;
						$x++;
						$totalPartidas++;
					}
				}
			}
		}

		$pesoTotal = number_format($pesoTotal, 2, '.', '');

		$i++;
		$xlsx->getActiveSheet()
		     ->setCellValue('B' . $i, 'TOTAL BULTOS')
		     ->setCellValue('C' . $i, $totalPartidas)
		     ->setCellValue('F' . $i, 'PESO TOTAL')
		     ->setCellValue('G' . $i, $pesoTotal . ' k')
		     ->setCellValue('I' . $i, 'TOTAL')
		     ->setCellValue('J' . $i, $totalFactura);
		$xlsx->getActiveSheet()->getStyle("B$i:C$i")->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
		$xlsx->getActiveSheet()->getStyle("B$i:C$i")->getFill()->getStartColor()->setARGB('A6A6A6');

		$xlsx->getActiveSheet()->getStyle("B$i:C$i")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
		$xlsx->getActiveSheet()->getStyle("B$i:C$i")->getFill()->getStartColor()->setARGB('444444');
		$xlsx->getActiveSheet()->getStyle("F$i:G$i")->getFill()->getStartColor()->setARGB('444444');
		$xlsx->getActiveSheet()->getStyle("F$i:G$i")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);
		$xlsx->getActiveSheet()->getStyle("I$i:J$i")->getFill()->getStartColor()->setARGB('444444');
		$xlsx->getActiveSheet()->getStyle("I$i:J$i")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);

		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="factura_importacion_' . $id . '.xlsx"');
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($xlsx, 'Excel2007');
		$objWriter->save('php://output');
		exit;
	}

	public function listadoCarga() {
		require_once(APP . 'inc/phpexcel/phpexcel.php');

		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setCreator("JC Pack")
									 ->setTitle("Reporte")
									 ->setSubject("Reporte");

		$objPHPExcel->getDefaultStyle()
		    ->getAlignment()
		    ->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_LEFT);

		$x = 'A';

		foreach($_POST['facturas'] as $factura) {
			$i = 2;
			$objPHPExcel->getActiveSheet()->setCellValue($x . '1', 'Factura ' . Modelos_Caracteres::importacion(strip_tags($factura)));

			$sth = $this->_db->prepare("SELECT DISTINCT iep.caja FROM import_export_partes iep WHERE iep.id_factura = ? AND iep.caja != '' AND iep.cantidad_recibida_import_export != 0 ORDER BY caja ASC");
			$sth->bindParam(1, $factura);
			if(!$sth->execute()) throw New Exception();
			while ($datos = $sth->fetch()) {
				$caja = Modelos_Caracteres::importacion(strip_tags($datos['caja']));

				$objPHPExcel->getActiveSheet()->setCellValue($x . $i, $caja);
      			$i++;
			}
			$x++;
		}

		for ($col = 'A'; $col != $x; $col++) {
			$objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
		}

		$objPHPExcel->getActiveSheet()->getStyle('A1:' . $x . '1')->getFill()->setFillType(PHPExcel_Style_Fill::FILL_SOLID);
		$objPHPExcel->getActiveSheet()->getStyle('A1:' . $x . '1')->getFill()->getStartColor()->setARGB('333333');
		$objPHPExcel->getActiveSheet()->getStyle('A1:' . $x . '1')->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_WHITE);

		$objPHPExcel->getActiveSheet()->setAutoFilter($objPHPExcel->getActiveSheet()->calculateWorksheetDimension());

		$objPHPExcel->getActiveSheet()->setTitle('Reporte');
		$objPHPExcel->setActiveSheetIndex(0);
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="listado_carga.xlsx"');
		header('Cache-Control: max-age=0');
		$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		$objWriter->save('php://output');
		exit;
	}

	public function desplegarCostos($id) {
		try {
			$datosArray = array();

			// Nombre de Agente
			$sth = $this->_db->prepare("SELECT nombre, apellidos FROM usuarios WHERE id = ? LIMIT 1");
			$sth->bindParam(1, $_SESSION['login_id']);
			if(!$sth->execute()) throw New Exception();
			$datos = $sth->fetch();
			$agente = $datos['nombre'] . ' ' . $datos['apellidos'];

			$datosArray['folio'] = $id;
			$datosArray['agente'] = $agente;

			$sth = $this->_db->prepare("SELECT pedimento, costo_tipo_cambio, costo_aduana, costo_shipper, costo_impuestos, costo_flete, costo_total_serana, costo_total_impuestos, costo_total_transporte, costo_total_totales, fecha_recibido FROM import_export WHERE id = ?");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();
			$datos = $sth->fetch();

			$datosArray['pedimento'] = $datos['pedimento'];
			$datosArray['costo_tipo_cambio'] = $datos['costo_tipo_cambio'];
			$datosArray['costo_aduana'] = $datos['costo_aduana'];
			$datosArray['costo_shipper'] = $datos['costo_shipper'];
			$datosArray['costo_impuestos'] = $datos['costo_impuestos'];
			$datosArray['costo_flete'] = $datos['costo_flete'];
			$datosArray['costo_total_serana'] = $datos['costo_total_serana'];
			$datosArray['costo_total_impuestos'] = $datos['costo_total_impuestos'];
			$datosArray['costo_total_transporte'] = $datos['costo_total_transporte'];
			$datosArray['costo_total_totales'] = $datos['costo_total_totales'];
			$datosArray['fecha_recibido'] = Modelos_Fecha::formatearFecha($datos['fecha_recibido']);

			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function actualizarCostos($post) {
		try {
			$id = $post['factura'];

			$sth = $this->_db->prepare("UPDATE import_export SET pedimento = ?, costo_tipo_cambio = ?, costo_aduana = ?, costo_shipper = ?, costo_impuestos = ?, costo_flete = ?, costo_total_serana = ?, costo_total_impuestos = ?, costo_total_transporte = ?, costo_total_totales = ? WHERE id = ?");
			$sth->bindParam(1, $post["pedimento"]);
			$sth->bindParam(2, $post["tipo_cambio"]);
			$sth->bindParam(3, $post["aduana"]);
			$sth->bindParam(4, $post["shipper"]);
			$sth->bindParam(5, $post["impuestos"]);
			$sth->bindParam(6, $post["flete"]);
			$sth->bindParam(7, $post["totales_serana"]);
			$sth->bindParam(8, $post["totales_impuestos"]);
			$sth->bindParam(9, $post["totales_transporte"]);
			$sth->bindParam(10, $post["totales_total"]);
			$sth->bindParam(11, $id);
			if(!$sth->execute()) throw New Exception();

			header('Location:' . STASIS. "/movimientos/import_export/costos/$id/1");
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function desplegarPedimento($id) {
		try {
			$datosArray = array();

			// Nombre de Agente
			$sth = $this->_db->prepare("SELECT nombre, apellidos FROM usuarios WHERE id = ? LIMIT 1");
			$sth->bindParam(1, $_SESSION['login_id']);
			if(!$sth->execute()) throw New Exception();
			$datos = $sth->fetch();
			$agente = $datos['nombre'] . ' ' . $datos['apellidos'];

			$datosArray['folio'] = $id;
			$datosArray['agente'] = $agente;

			$sth = $this->_db->prepare("SELECT pedimento FROM import_export WHERE id = ?");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();
			$datos = $sth->fetch();

			$datosArray['pedimento'] = $datos['pedimento'];

			return $datosArray;
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function actualizarPedimento($post) {
		try {
			$id = $post['factura'];

			$sth = $this->_db->prepare("UPDATE import_export SET pedimento = ? WHERE id = ?");
			$sth->bindParam(1, $post["pedimento"]);
			$sth->bindParam(2, $id);
			if(!$sth->execute()) throw New Exception();

			header('Location:' . STASIS. "/movimientos/import_export/pedimento/$id/1");
		} catch (Exception $e) {
			echo Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function cerrar($id) {
		try {
			$sth = $this->_db->prepare("UPDATE import_export SET status = 1 WHERE id = ?");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();
	  		header('Location: ' . STASIS . '/reportes/import_export_abiertas/1');
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function eliminar($id) {
		try {
			$sth = $this->_db->prepare("DELETE FROM import_export WHERE id = ?");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();
	  		header('Location: ' . STASIS . '/reportes/import_export_abiertas/');
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function xfAgregar($id) {
		try {
			$sth = $this->_db->prepare("UPDATE import_export SET xf = 1 WHERE id = ?");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();
	  		header('Location: ' . STASIS . '/reportes/import_export_abiertas/');
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}

	public function xfEliminar($id) {
		try {
			$sth = $this->_db->prepare("UPDATE import_export SET xf = 0 WHERE id = ?");
			$sth->bindParam(1, $id);
			if(!$sth->execute()) throw New Exception();
	  		header('Location: ' . STASIS . '/reportes/import_export_abiertas/');
		} catch (Exception $e) {
			$this->mensajes[] = Modelos_Sistema::status(0, $e->getMessage());
		}
	}
}