<section class="content">
<div class="btn-group pull-right">
  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
    <i class="fa fa-download"></i> Descargar <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" role="menu">
    <li><a href="report/onesell-word.php?id=<?php echo $_GET["id"];?>">Word 2007 (.docx)</a></li>
<li><a onclick="thePDF()" id="makepdf" class=""><i class="fa fa-download"></i> Descargar PDF</a>
<li><a href="ticket.php?id=<?php echo $_GET["id"];?>" id="makepdf" class="" target="_blank"><i class="fa fa-ticket"></i> Ticket</a>
  </ul>
</div>
<h1>Resumen de Venta #<?php echo $_GET["id"]; ?></h1>

<?php if(isset($_GET["id"]) && $_GET["id"]!=""):?>
<?php
$sell = SellData::getById($_GET["id"]);
$operations = OperationData::getAllProductsBySellId($_GET["id"]);
$total = 0;
?>
<?php if($sell->is_draft):?>



<!-- Button trigger modal -->
<button type="button" class="btn btn-default" data-toggle="modal" data-target="#myModal">
  Agregar Productos
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Agregar Productos</h4>
      </div>
      <div class="modal-body">


<ul class="nav nav-tabs" id=myTabs role=tablist> 
<li role=presentation class=active><a href=#home id=home-tab role=tab data-toggle=tab aria-controls=home aria-expanded=true>Favoritos</a></li>
<li role=presentation><a href=#profile role=tab id=profile-tab data-toggle=tab aria-controls=profile>Personalizado</a></li>
 </ul> <div class=tab-content id=myTabContent> <div class="tab-pane fade in active" role=tabpanel id=home aria-labelledby=home-tab> 
  <?php
$products_fav = ProductData::getFavorites();
$filas = 0;
if(count($products_fav)>0){

$nproducts = count($products_fav);
$filas = $nproducts/10;
$extra = $nproducts%10;
if($filas>1&& $extra>0){ $filas++; }


  ?>
<div class="">
<div class="">
<form method="post" action="./?action=addoperation&opt=many">
<input type="hidden" name="sell_id" value="<?php echo $_GET["id"];?>">
<table class="table table-bordered table-hover">
  <thead>
  </thead>
  <?php
  $cnt=0;
$products_in_cero=0;
   for($f=0;$f<$filas;$f++):?>
  <tr class="<?php if( ($product->use_inventary && $q<=5) ){ echo "danger"; }?>">
   <?php
   for($i=0;$i<10;$i++):
    if($cnt<count($products_fav)):
      $product = $products_fav[$cnt];
$q= OperationData::getQByStock($product->id,StockData::getPrincipal()->id);
  ?>
  <?php 
  if( ($product->use_inventory && $q>0) || !$product->use_inventory ):?>
    <td style="width:50px;">
<h4>    <?php echo $product->name; ?></h4>
      <?php if($product->image!=""):?>
        <img src="storage/products/<?php echo $product->image;?>" style="width:64px;">
      <?php endif;?>
    <input type="hidden" name="product_id" value="<?php echo $product->id; ?>">
    <input type="number" style="width:80px;" value="0" min="0" class="form-control" required name="q-<?php echo $product->id; ?>" placeholder="Cantidad de producto ...">

<div><b>$<?php echo $product->price_out; ?></b></div>
    </td>
<?php else:$products_in_cero++;
?>
<?php  endif; ?>
<?php else:?>
  <td></td>
<?php  endif; ?>
  <?php $cnt++;endfor;?>
  </tr>
  <?php endfor;?>
</table>
<br>
<input type="submit" value="Agregar a la venta" class="btn btn-primary">
</form>
</div>
</div>
<?php } ?>
 </div> 
 <div class="tab-pane fade" role=tabpanel id=profile aria-labelledby=profile-tab>
          <form class="form-horizontal" method="post" action="index.php?action=addoperation&opt=one" role="form">
  <div class="form-group">
    <label for="inputEmail1" class="col-lg-2 control-label">Producto</label>
    <div class="col-lg-10">
<select name="product_id" class="form-control" required>
    <option value="">-- SELECCIONA UN PRODUCTO -- </option>
  <?php foreach(ProductData::getAllActive() as $product):?>
    <option value="<?php echo $product->id; ?>" ><?php echo $product->name; ?></option>
  <?php endforeach ; ?>
</select>
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword1" class="col-lg-2 control-label">Cantidad</label>
    <div class="col-lg-10">
      <input type="number" class="form-control" name="q" id="inputPassword1" required placeholder="Cantidad">
    </div>
  </div>

  <div class="form-group">
    <div class="col-lg-offset-2 col-lg-10">
    <input type="hidden" name="sell_id" value="<?php echo $_GET["id"];?>">
      <button type="submit" class="btn btn-primary">Agregar Producto</button>
    </div>
  </div>
</form>
</div> 
 </div>








      </div>

    </div>
  </div>
</div>

<a href="./?view=opensell&id=<?php echo $sell->id; ?>" class="btn btn-info">Procesar</a>
<br><br><p class="alert alert-warning">Venta pendiente</p>
<?php endif; ?>
<?php
if(isset($_COOKIE["selled"])){
	foreach ($operations as $operation) {
//		print_r($operation);
    $productx = ProductData::getById($operation->product_id);
    if($productx->use_inventory){
		$qx = OperationData::getQByStock($operation->product_id,StockData::getPrincipal()->id);
		// print "qx=$qx";
			$p = $operation->getProduct();
		if($qx==0){
			echo "<p class='alert alert-danger'>El producto <b style='text-transform:uppercase;'> $p->name</b> no tiene existencias en inventario.</p>";			
		}else if($qx<=$p->inventary_min/2){
			echo "<p class='alert alert-danger'>El producto <b style='text-transform:uppercase;'> $p->name</b> tiene muy pocas existencias en inventario.</p>";
		}else if($qx<=$p->inventary_min){
			echo "<p class='alert alert-warning'>El producto <b style='text-transform:uppercase;'> $p->name</b> tiene pocas existencias en inventario.</p>";
		}
  }
	}
	setcookie("selled","",time()-18600);
}

?>
<div class="box box-primary">
<table class="table table-bordered">
<tr>
  <td style="width:200px;"><b>Tipo de Venta</b></td>
  <td>
<?php if($sell->k==1){ echo "Restaurante"; }
else if($sell->k==2){ echo "Para LLevar"; }
else if($sell->k==3){ echo "A domicilio"; }
?>
</tr>
<?php if($sell->person_id!=""):
$client = $sell->getPerson();
?>
<tr>
	<td style="width:150px;">Cliente</td>
	<td><?php echo $client->name." ".$client->lastname;?></td>
</tr>

<?php endif; ?>
<?php if($sell->waiter_id!=""):
$client = $sell->getWaiter();
?>
<tr>
  <td style="width:150px;">Mesero</td>
  <td><?php echo $client->name." ".$client->lastname;?></td>
</tr>

<?php endif; ?>
<?php if($sell->user_id!=""):
$user = $sell->getUser();
?>
<!--
<tr>
	<td>Atendido por</td>
	<td><?php echo $user->name." ".$user->lastname;?></td>
</tr>
-->
<?php endif; ?>
</table>
</div>
<br>
<div class="box box-primary">
<table class="table table-bordered table-hover">
	<thead>
		<th>Codigo</th>
		<th>Cantidad</th>
		<th>Nombre del Producto</th>
		<th>Precio Unitario</th>
		<th>Total</th>

	</thead>
<?php
	foreach($operations as $operation){
		$product  = $operation->getProduct();
?>
<tr>
	<td><?php echo $product->barcode ;?></td>
	<td><?php echo $operation->q ;?></td>
	<td><?php echo $product->name ;?></td>
	<td>$ <?php echo number_format($operation->price_out,2,".",",") ;?></td>
	<td><b>$ <?php echo number_format($operation->q*$operation->price_out,2,".",",");$total+=$operation->q*$operation->price_out;?></b></td>
</tr>
<?php
	}
	?>
</table>
</div>
<br><br>
<div class="row">
<div class="col-md-4">
<div class="box box-primary">
<table class="table table-bordered">
  <tr>
    <td><h4>Propina:</h4></td>
    <td><h4>$ <?php echo number_format($sell->tip,2,'.',','); ?></h4></td>
  </tr>
	<tr>
		<td><h4>Descuento:</h4></td>
		<td><h4>$ <?php echo number_format($sell->discount,2,'.',','); ?></h4></td>
	</tr>
	<tr>
		<td><h4>Subtotal:</h4></td>
		<td><h4>$ <?php echo number_format($total,2,'.',','); ?></h4></td>
	</tr>
	<tr>
		<td><h4>Total:</h4></td>
		<td><h4>$ <?php echo number_format(($total + $sell->tip) -	$sell->discount,2,'.',','); ?></h4></td>
	</tr>
</table>
</div>


</div>
</div>






<script type="text/javascript">
        function thePDF() {

var columns = [
//    {title: "Reten", dataKey: "reten"},
    {title: "Codigo", dataKey: "code"}, 
    {title: "Cantidad", dataKey: "q"}, 
    {title: "Nombre del Producto", dataKey: "product"}, 
    {title: "Precio unitario", dataKey: "pu"}, 
    {title: "Total", dataKey: "total"}, 
//    ...
];


var columns2 = [
//    {title: "Reten", dataKey: "reten"},
    {title: "", dataKey: "clave"}, 
    {title: "", dataKey: "valor"}, 
//    ...
];

var rows = [
  <?php foreach($operations as $operation):
  $product  = $operation->getProduct();
  ?>

    {
      "code": "<?php echo $product->barcode; ?>",
      "q": "<?php echo $operation->q; ?>",
      "product": "<?php echo $product->name; ?>",
      "pu": "$ <?php echo number_format($operation->price_out,2,".",","); ?>",
      "total": "$ <?php echo number_format($operation->q*$operation->price_out,2,".",","); ?>",
      },
 <?php endforeach; ?>
];

var rows2 = [
<?php if($sell->person_id!=""):
$person = $sell->getPerson();
?>

    {
      "clave": "Cliente",
      "valor": "<?php echo $person->name." ".$person->lastname; ?>",
      },
      <?php endif; ?>
<?php if($sell->waiter_id!=""):
$person = $sell->getWaiter();
?>

    {
      "clave": "Mesero",
      "valor": "<?php echo $person->name." ".$person->lastname; ?>",
      },
      <?php endif; ?>
];

var rows3 = [

    {
      "clave": "Descuento",
      "valor": "$ <?php echo number_format($sell->discount,2,'.',',');; ?>",
      },
    {
      "clave": "Subtotal",
      "valor": "$ <?php echo number_format($sell->total,2,'.',',');; ?>",
      },
    {
      "clave": "Total",
      "valor": "$ <?php echo number_format($sell->total-$sell->discount,2,'.',',');; ?>",
      },
];



// Only pt supported (not mm or in)
var doc = new jsPDF('p', 'pt');
//var doc = new jsPDF('p', 'mm', [600, 200]);

        doc.setFontSize(26);
        doc.text("NOTA DE VENTA #<?php echo $sell->id; ?>", 20, 35);
        doc.setFontSize(14);
        doc.text("Fecha: <?php echo $sell->created_at; ?>", 20, 45);
//        doc.text("Operador:", 40, 150);
//        doc.text("Header", 40, 30);
  //      doc.text("Header", 40, 30);
<?php if($sell->person_id!="" ||$sell->waiter_id!=""):?>
doc.autoTable(columns2, rows2, {
    theme: 'grid',
    overflow:'linebreak',
    styles: {
        fillColor: [100, 100, 100]
    },
    columnStyles: {
        id: {fillColor: 255}
    },
    margin: {left:20,right:20,top: 50},
    afterPageContent: function(data) {
//        doc.text("Header", 40, 30);
    }
});
<?php endif; ?>


doc.autoTable(columns, rows, {
    theme: 'grid',
    overflow:'linebreak',
    styles: {
        fillColor: [100, 100, 100]
    },
    columnStyles: {
        id: {fillColor: 255}
    },
    margin: {left:20,right:20,top: doc.autoTableEndPosY()+15},
    afterPageContent: function(data) {
//        doc.text("Header", 40, 30);
    }
});

doc.autoTable(columns2, rows3, {
    theme: 'grid',
    overflow:'linebreak',
    styles: {
        fillColor: [100, 100, 100]
    },
    columnStyles: {
        id: {fillColor: 255}
    },
    margin: {left:20,right:20,top: doc.autoTableEndPosY()+15},
    afterPageContent: function(data) {
//        doc.text("Header", 40, 30);
    }
});

//doc.setFontsize
//img = new Image();
//img.src = "liberacion2.jpg";
//doc.addImage(img, 'JPEG', 40, 10, 610, 100, 'monkey'); // Cache the image using the alias 'monkey'
doc.setFontSize(20);
doc.setFontSize(12);
doc.text("Generado por el Sistema Thunder MAX v5", 20, doc.autoTableEndPosY()+25);
doc.save('sell-<?php echo date("d-m-Y h:i:s",time()); ?>.pdf');
//doc.output("datauri");

        }
    </script>

<script>
  $(document).ready(function(){
//    $("#makepdf").trigger("click");
  });
</script>




<?php else:?>
	501 Internal Error
<?php endif; ?>
</section>



