<?php

    $db = $GLOBALS ['db'];
    $contrator = $_POST['contractor'];
    $date_from = $_POST["date_from"];
    $date_to = $_POST["date_to"];
    $searchByType = $_POST['type'];
    $category = $_POST['category'];
	$subcategory = $_POST['subcategory'];
	$user = $_POST['user'];
    $date_from = new DateTime($date_from);
    $date_to = new DateTime($date_to);
	
    $query="";

		$query="SELECT
                            pozycja.name,
                            pozycja.ecmproduct_id as 'id',
							faktura.parent_id as 'parent_id',
							produkt.code,
                            sum(
                            CASE WHEN faktura.type!='correct'
                                    THEN
                                            CASE WHEN faktura.currency_value is null or faktura.currency_value='' or faktura.currency_value=0
                                                    THEN
                                                            pozycja.total_netto
                                                    ELSE
                                                            pozycja.total_netto*faktura.currency_value
                                            END
                                    ELSE
											CASE WHEN pozycja.old_ecminvoiceoutitem_id IS null OR pozycja.old_ecminvoiceoutitem_id='' THEN
                                                    0
                                            ELSE
                                                    CASE WHEN faktura.currency_value is null or faktura.currency_value='' or faktura.currency_value=0
                                                            THEN
                                                                    pozycja.total_netto_corrected
                                                            ELSE
                                                                    pozycja.total_netto_corrected*faktura.currency_value
                                                    END
                                   			END
									END
                                ) as netto,
                                sum(
                                        CASE WHEN faktura.type!='correct' 
                                                THEN 
                                                        pozycja.quantity
                                                ELSE 
                                                        pozycja.quantity-pozycja.old_quantity 
                                        END
                                ) as ilosc,
                                sum(
                                    
                                                        pozycja.price_purchase*pozycja.quantity 
                                            
                                ) as koszt
                                    FROM
                                        ecminvoiceoutitems pozycja
                                            JOIN
                                        ecminvoiceouts faktura ON pozycja.ecminvoiceout_id = faktura.id
                                            JOIN
                                        ecmproducts produkt ON pozycja.ecmproduct_id = produkt.id
                                        	JOIN
                                        accounts acco ON acco.id = faktura.parent_id
                                    WHERE
									faktura.register_date BETWEEN 
                                        '".$date_from->format('Y-m-d')."' AND
                                           '".$date_to->format('Y-m-d')."'
                                                and faktura.type like '".$searchByType."' 
                                    ";

                                    if( $contrator == 1249 )
                                    	$query .= "and acco.parent_id='".$contrator."'";
                                    else
                                    	$query .= "and faktura.parent_id='".$contrator."'";

                                    $query .= "
										and faktura.canceled = 0
											and faktura.deleted= 0
												and pozycja.deleted= 0
                                    GROUP BY pozycja.name
                                    COLLATE utf8_polish_ci;";
        $data = array();
        $rows = $db->query ($query);
	// prepare data for Smarty
	while($r = $db->fetchByAssoc ( $rows ))
	{
							$row = array();
							$row["id"] = $r["id"]; 
							$row["name"] = $r["name"]; 
							$row["code"] = $r["code"];
							$userBool=1;
							if($user!="")
							{
								$userBool=0;
								$querySelectUsers="SELECT user.id,
													first_name as 'first',
													last_name as 'last'
											FROM 			
												accounts acc
													JOIN
												users user ON acc.assigned_user_id=user.id
											WHERE acc.id='".$r["parent_id"]."';";
								$rowsSelectUsers = $db->query ($querySelectUsers);
								while($rowSelectUser = $db->fetchByAssoc ( $rowsSelectUsers ))
								{
									
									if($rowSelectUser["id"]==$user)
									{
										$userBool=1;
									}else{
										$userBool=0;
									}
								}
							}
						
							if($userBool==1)
							{
								$queryCategory="SELECT category.name as 'kategoria'
											FROM 			
												ecmproductcategories_bean bean
													JOIN
												ecmproductcategories category ON bean.ecmproductcategory_id = category.id
											WHERE bean.bean_id='".$row["id"]."'
											and bean.position = 0 
											and bean.deleted = '0'
											and category.deleted=0
											and category.name='".$category."';";
								$rowsCategory = $db->query ($queryCategory);
								while($rowCategory = $db->fetchByAssoc ( $rowsCategory ))
								{
									$row["kategoria"] = $rowCategory["kategoria"];
								}
								if($row["kategoria"]!='')
								{
									
									$querySubCategory="SELECT category.name as 'podkategoria'
													FROM 			
														ecmproductcategories_bean bean
															JOIN
														ecmproductcategories category ON bean.ecmproductcategory_id = category.id
													WHERE bean.bean_id='".$row["id"]."'
													and bean.position = 1
													and bean.deleted = '0'
													and category.deleted=0
													and category.name='".$subcategory."';";
										$rowsSubcategory = $db->query ($querySubCategory);
										while($rowSubcategory = $db->fetchByAssoc ( $rowsSubcategory ))
										{
											$row["podkategoria"] = $rowSubcategory["podkategoria"];
										}
										if($row["podkategoria"]!='')
										{
											
											$row["ilosc"] = $r["ilosc"];
											$row["netto"] = $r["netto"];
											$row["srednia"] = $row["netto"]/$row["ilosc"];
											$row["koszt"] = $r["koszt"];
											//if($row["netto"]>$row["koszt"])
											//{
												 $row["marza"] = ($row["netto"]-$row["koszt"])/($row["netto"])*100;
											//}else{
											//	$row["marza"] = 0;
											//}
											
											$data [] = $row;
										}
								}
							}
	}
        $smart = new Sugar_Smarty ();
        $smart -> assign("data", $data);


	
	echo $smart->display ( 'modules/EcmReports/tpls/detailProducts.tpl' );
?>