<?php
include($_SERVER['DOCUMENT_ROOT'] .'/script/HeaderInc.php');
$ArrPost = explode('&', $_POST['PrintDocx']);
foreach($ArrPost as $value){
  $ArrT = explode('=', $value);  
  if(false === strpos($ArrT[0], 'colspan')){
    $ArrValues[$ArrT[0]][]=$ArrT[1];    
  }
  else{
    $ArrValues['colspan'][str_replace('colspan[','',str_replace(']','',$ArrT[0]))]=$ArrT[1];
  }
}
$PHPWord  = new PHPWord();
$section  = $PHPWord->createSection();
$styleTable = array('borderSize'=>6, 'cellMargin'=>80);

$styleCell = array('valign'=>'center');

$fontStyleTH = array('bold'=>true, 'align'=>'left', 'spaceAfter'=>0);
$fontStyle = array('bold'=>false, 'align'=>'left');
$paragStyle = array('spaceAfter'=>0);

$PHPWord->addTableStyle('gridprint', $styleTable);
$table = $section->addTable('gridprint');
$table->addRow();
foreach ($ArrValues['thead'] as $value) {
  $table->addCell($styleCell)->addText($value, $fontStyleTH, $paragStyle);
}
$i = count($ArrValues['colspan'][0]);
$table->addRow();
foreach ($ArrValues['tbody'] as $key => $value) {
  if($i == count($ArrValues['thead'])){
    $table->addRow();
    $i = count($ArrValues['colspan'][0]);
  }
  if(isset($ArrValues['colspan'][$key]) && 0 < $ArrValues['colspan'][$key]){
    $styleCellC=array('gridSpan' => $ArrValues['colspan'][$key]);
    $table->addCell(10,$styleCellC)->addText($value, $fontStyle, $paragStyle);
  }
  else{
    $table->addCell(10)->addText($value, $fontStyle, $paragStyle);
  }
  $i++;
}
$file = $ArrValues['grid'][0].'_'. date("d_m_Y_H_i_s").'.docx';
$filePath = $_SERVER['DOCUMENT_ROOT'] .'/../tmp/'.$file;
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save($filePath);
include($_SERVER['DOCUMENT_ROOT'] .'/script/FooterInc.php');
if(!$filePath) {     
  die('file not found'); 
} 
else {     
  ob_clean();
  header("Content-Disposition: attachment; filename=".$file);     
  header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");     
  header('Content-Length: '. filesize($filePath));    
  readfile($filePath); 
  unlink($filePath);
  exit;
}
?>
