<?php

require_once("../includes/config.php");
////// filters value/////
$location = base64_decode($_REQUEST['location']);
$stk_type = base64_decode($_REQUEST['stock_type']);
$prodcat = base64_decode($_REQUEST['prod_cat']);
$prodsubcat = base64_decode($_REQUEST['product_sub_category']);
$brand = base64_decode($_REQUEST['brandname']);

## selected Location
if (!empty($location)) {
    $location_str = " location_code='" . $location . "'";
} else {
    $location_str = " location_code='" . $location . "'";
}
if (!empty($stk_type)) {
    $stocktype = "stock_type='" . $stk_type . "'";
    $itemtype = "itemtypeid='" . $stk_type . "'";
} else {
    $stocktype = " 1";
    $itemtype = "1";
}
## selected product category
if (!empty($prodcat)) {
    $productCategory = "productid='" . $prodcat . "'";
} else {
    $productCategory = "1";
}
## selected product sub category
if (!empty($prodsubcat)) {
    $subCategory = "psubcatid='" . $prodsubcat . "'";
} else {
    $subCategory = "1";
}
## selected brand
if (!empty($brand)) {
    $brand_name = "brandid='" . $brand . "'";
} else {
    $brand_name = "1";
}
///// make partcode string on the basis of selection
$part_str = "";
if (!empty($productCategory) || !empty($prodsubcat) || !empty($brand)) {
    $res_part = mysqli_query($link1, "select partcode from partcode_master where " . $productCategory . " and " . $subCategory . " and " . $brand_name . " and " . $itemtype . "");
    while ($row = mysqli_fetch_array($res_part)) {
        if ($part_str == "") {
            $part_str .= "'" . $row['partcode'] . "'";
        } else {
            $part_str .= ",'" . $row['partcode'] . "'";
        }
    }
    if (!empty($part_str)) {
        
    } else {
        $part_str = "''";
    }
    $partstr = " and partcode in (" . $part_str . ")";
} else {
    $partstr = "";
}
//////End filters value/////
/** Include PHPExcel */
require_once("../ExcelExportAPI/Classes/PHPExcel.php");

// Create new PHPExcel object
$objPHPExcel = new PHPExcel();

// Set document properties
$objPHPExcel->getProperties()->setCreator("Candour Software")
        ->setLastModifiedBy("Candour Software")
        ->setTitle("Office 2007 XLSX Inventory Stock Data")
        ->setSubject("Office 2007 XLSX Inventory Stock Data")
        ->setDescription("Inventory Stock Data for Office 2007 XLSX.")
        ->setKeywords("office 2007 openxml php")
        ->setCategory("Inventory Stock Data");
// Add some data
$objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', 'Sr. No.')
        ->setCellValue('B1', 'Location Name')
        ->setCellValue('C1', 'Location Code')
        ->setCellValue('D1', 'Brand')
        ->setCellValue('E1', 'Product Category')
        ->setCellValue('F1', 'Product Sub Category')
        ->setCellValue('G1', 'Part Name')
        ->setCellValue('H1', 'Part Code')
        ->setCellValue('I1', 'Product Type')
		->setCellValue('J1', 'Vendor Part Name')
        ->setCellValue('K1', 'OK Qty')
		->setCellValue('L1', 'Average Consumptions Qty for 1 month (90 Days)')
		->setCellValue('M1', 'MSL Qty (15 Days)')
        ->setCellValue('N1', 'IQC Rejection')
		->setCellValue('O1', 'Vender Rejection')
		->setCellValue('P1', 'Process Rejection')
        ->setCellValue('Q1', 'Missing Qty')
        ->setCellValue('R1', 'Purchase Unit');
///// Add Color in header
cellColor('A1:K1', '90EE90');
cellColor('L1:M1', 'eb9571');
cellColor('N1:R1', '90EE90');

$i = 2;
$count = 1;
$sql_loc = mysqli_query($link1, "Select * from inventory_status where " . $location_str . " and " . $stocktype . " " . $partstr . "");

while ($row_loc = mysqli_fetch_array($sql_loc)) {
    $sql = mysqli_query($link1, "Select brandid,productid,psubcatid,itemtypeid,vendor_part_name from partcode_master where partcode='" . $row_loc["partcode"] . "'");
    $row_part = mysqli_fetch_assoc($sql);
	
	//// find average qty //////////
	$k = 0.00;
	$l = 0.00; //and partcode = '".$row_loc['partcode']."'
	$lll = 0.00;
	$mmm = 0.00;
	$tt = mysqli_fetch_array(mysqli_query($link1, "SELECT SUM(qty) AS tot FROM stock_ledger WHERE from_party = '".$row_loc['location_code']."' and partcode = '".$row_loc['partcode']."'  and stock_transfer LIKE 'OUT' and (reference_no NOT LIKE 'GP/%' AND reference_no NOT LIKE 'RGP/%') and reference_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY) "));
	if($tt['tot']!=0 && $tt['tot']!=""){
		$lll = ($tt['tot']/90);
		$mmm = ($lll*30);
		$k = getQtyFormate($mmm, 2);
		$l = getQtyFormate(($k/2), 2);
	}else{
		$k = "";
		$l = "";
	}
	
    
    $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A' . $i, $count)
            ->setCellValue('B' . $i, getAnyDetails($row_loc["location_code"], "locationname", "location_code", "location_master", $link1))
            ->setCellValue('C' . $i, $row_loc["location_code"])
            ->setCellValue('D' . $i, getAnyDetails($row_part["brandid"], "brand", "brandid", "brand_master", $link1))
            ->setCellValue('E' . $i, getAnyDetails($row_part["productid"], "product_name", "productid", "product_master", $link1))
            ->setCellValue('F' . $i, getAnyDetails($row_part["psubcatid"], "prod_sub_cat", "psubcatid", "product_sub_category", $link1))
            ->setCellValue('G' . $i, getAnyDetails($row_loc["partcode"], "part_name", "partcode", "partcode_master", $link1))
            ->setCellValue('H' . $i, $row_loc["partcode"])
            ->setCellValue('I' . $i, getAnyDetails($row_loc['stock_type'], "parttype", "typeid", "part_type_master", $link1))
            ->setCellValue('J' . $i, $row_part['vendor_part_name'])
			->setCellValue('K' . $i, getQtyFormate($row_loc['ok_qty'], 6))
			->setCellValue('L' . $i, $k)
			->setCellValue('M' . $i, $l)
            ->setCellValue('N' . $i, getQtyFormate($row_loc['damage_qty'], 6))
			->setCellValue('O' . $i, getQtyFormate($row_loc['faulty_qty'], 6))
			->setCellValue('P' . $i, getQtyFormate($row_loc['p_rejected_qty'], 6))
            ->setCellValue('Q' . $i, getQtyFormate($row_loc['missing_qty'], 6))
            ->setCellValue('R' . $i, $row_loc['purchase_unit']);

    $count++;
    $i++;
}
///// apply border on export sheet
$styleArray = array(
    'borders' => array(
        'allborders' => array(
            'style' => PHPExcel_Style_Border::BORDER_MEDIUM
        )
    )
);

$objPHPExcel->getActiveSheet()->getStyle('A1:R' . ($i - 1))->applyFromArray($styleArray);
unset($styleArray);

// Rename worksheet
$objPHPExcel->getActiveSheet()->setTitle('Inventory Stock');

////////////////////////////////////second sheet start bin//////////////////////////////////////////////////////
// Create a new worksheet, after the default sheet
$objPHPExcel->createSheet();

// Add some data to the second sheet, resembling some different data types

$objPHPExcel->setActiveSheetIndex(1)
        ->setCellValue('A1', 'Sr. No.')
        ->setCellValue('B1', 'Partcode')
        ->setCellValue('C1', 'Bin No.')
        ->setCellValue('D1', 'Qty')
        ->setCellValue('E1', 'Stock Type')
		->setCellValue('F1', 'Update By');

///// Add Color in header
cellColor('A1:F1', '90EE90');

$i = 2;
$count = 1;
$sql_loc = mysqli_query($link1, "Select partcode,location_code from inventory_status where " . $location_str . " and " . $stocktype . " " . $partstr . "");

while ($row_loc = mysqli_fetch_array($sql_loc)) {
    $sql = mysqli_query($link1, "Select * from bin_allocation where partcode='" . $row_loc["partcode"] . "' and location_code='" . $row_loc["location_code"] . "'");
    $row_bin = mysqli_fetch_assoc($sql);
    if($row_bin["bin_id"] !=""){
    if($row_bin["stock_type"]=='ok-qty'){ $stock ="Ok";}else if($row_bin["stock_type"]=='damage-qty'){ $stock ="Damage";}else{$stock ="";}
    $objPHPExcel->setActiveSheetIndex(1)
            ->setCellValue('A' . $i, $count)
            ->setCellValue('B' . $i, $row_loc["partcode"])
            ->setCellValue('C' . $i, getAnyDetails($row_bin["bin_id"], "bin_no", "bin_id", "bin_master", $link1))
            ->setCellValue('D' . $i, $row_bin["qty"])
            ->setCellValue('E' . $i, $stock)
			->setCellValue('F' . $i, $row_bin["update_by"]);
           
    $count++;
    $i++;
}}

// Rename 2nd sheet
$objPHPExcel->getActiveSheet()->setTitle('Bin Data');


// Set active sheet index to the first sheet, so Excel opens this as the first sheet
$objPHPExcel->setActiveSheetIndex(0);

////////////////////////////////////second sheet end bin//////////////////////////////////////////////////////



// Redirect output to a client?s web browser (Excel2007)
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="inventory_status_excel.xlsx"');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');

// If you're serving to IE over SSL, then the following may be needed
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');



////////////////////////send excel data/////////////////////////


exit;
?>
