<?php

	/* (C) DairyWindow 2012-2017 */

	require "inc/connect.php";

	$success = false;

	if(isset($_POST['create']) && isset($_POST['specid']) && $_POST['specid']!='' && $_POST['specid']!=null){

		//see if spec already exists first
		$sql="
			select specID
			from dw_spec
			where specText=? and specSite=?
		";
		if(!$qry = mysqli_prepared_query($link, $sql, "si", array($_POST['newspec' ], $_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
		if(mysqli_prepared_num_rows($qry)<1){

			$oldspecid     = clean($_POST['specid'  ]);
			$specText      = clean($_POST['newspec' ]);
			$specGSP       = clean($_POST['newgsp'  ]);
			$specShortDesc = clean($_POST['newshort']);
			$specLongDesc  = clean($_POST['newlong' ]);

			//create new spec
			$sql="
				Select *
				From dw_spec
				Where specID = ?
			";
			if(!$qry = mysqli_prepared_query($link, $sql, "i", array($oldspecid), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
			if(mysqli_prepared_num_rows($qry)==1){
				//$row = mysqli_fetch_assoc($qry);
				$row = $qry[0];

				//specText
				//specGSP
				$specCode         = clean($row['specCode'        ]);
				//specShortDesc
				//specLongDesc
				$specExpiry       = clean($row['specExpiry'      ]);
				$specStyle        = clean($row['specStyle'       ]);
				$specVersion      = clean($row['specVersion'     ]);
				$specOrder        = clean($row['specOrder'       ]);
				$specUnitTypeText = clean($row['specUnitTypeText']);
				$specSend         = clean($row['specSend'        ]);
				$specShowLoc      = clean($row['specShowLoc'     ]);
				$specEmailAddy    = clean($row['specEmailAddy'   ]);
				$specActive       = 1;
				$specModUser      = $_SESSION['userID'];

				$specModReason    = "";
				$specChangeCode   = "";
				if($row['specRegime']!=null && $row['specRegime']!="") $specRegime = clean($row['specRegime']);
				else $specRegime  = 0;
				$specSite         = clean($row['specSite'        ]);
				if($row['specKGperPallet']!=null && $row['specKGperPallet']!="") $specKGperPallet = clean($row['specKGperPallet']);
				else $specKGperPallet = 0;
				$specCSV          = clean($row['specCSV'         ]);
				$specBagSize      = clean($row['specBagSize'     ]);

				$sql="
					Insert Into dw_spec                             ( specText,  specGSP,  specCode,  specShortDesc,  specLongDesc,  specExpiry,  specStyle,  specVersion,  specOrder,  specUnitTypeText,  specSend,  specShowLoc,  specEmailAddy,  specActive,  specModUser,  specModDate,  specModReason,  specChangeCode,  specRegime,  specSite,  specKGperPallet,  specCSV,  specBagSize)
					Values                                          (     ?   ,      ?  ,      ?   ,      ?        ,      ?       ,      ?     ,      ?    ,      ?      ,      ?    ,      ?           ,      ?   ,      ?      ,      ?        ,      ?     ,      ?      ,    now()    ,      ?        ,      ?         ,      ?     ,      ?   ,      ?          ,      ?  ,      ?      )
				";
				if(!savesql($link, $sql, "ssssssisisiisii sssisss", array($specText, $specGSP, $specCode, $specShortDesc, $specLongDesc, $specExpiry, $specStyle, $specVersion, $specOrder, $specUnitTypeText, $specSend, $specShowLoc, $specEmailAddy, $specActive, $specModUser,               $specModReason, $specChangeCode, $specRegime, $specSite, $specKGperPallet, $specCSV, $specBagSize), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);

				//get the id of the newly created spec
				$sql="
					Select specID
					From dw_spec
					Where specID > ?
					Order by specID desc
					Limit 1
				";
				if(!$qry = mysqli_prepared_query($link, $sql, "i", array(0), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
				$newspecid = $qry[0]['specID'];

				if(isset($_POST['newlimit']) && ($_POST['newlimit']==1 || $_POST['newlimit']=='1')){
					//copy over test limits
					$sql="
						Select *
						From dw_limit
						Where limitSpec = ?
					";
					if(!$qry = mysqli_prepared_query($link, $sql, "i", array($oldspecid), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					foreach($qry as $row){
						$limitTest     = clean($row['limitTest'    ]);
						$limitLocation = clean($row['limitLocation']);
						$limitLow      = clean($row['limitLow'     ]);
						$limitHigh     = clean($row['limitHigh'    ]);
						$limitDateFrom = clean($row['limitDateFrom']);
						$limitDateTo   = clean($row['limitDateTo'  ]);

						$sql='# insert new limits
							Insert into dw_limit          ( limitSpec,  limitTest,  limitLocation,  limitLow,  limitHigh,  limitDateFrom,  limitDateTo, limitModUser, limitModDate)
							values                        (      ?   ,       ?   ,       ?       ,       ?  ,       ?   ,       ?       ,       ?     ,      ?      ,     now()   )';
						$params =                       '      i           i           i               d          d           s               s            i                     ';
						if(!savesql($link, $sql, $params, array($newspecid, $limitTest, $limitLocation, $limitLow, $limitHigh, $limitDateFrom, $limitDateTo, $_SESSION['userID']       ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
				}

				if(isset($_POST['newsub']) && ($_POST['newsub']==1 || $_POST['newsub']=='1')){
					//copy over sub form details
					$sql="
						Select *
						From dw_sub
						Where subSpec = ?
					";
					if(!$qry = mysqli_prepared_query($link, $sql, "i", array($oldspecid), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					foreach($qry as $row){
						$subTest = $row['subTest'];
						$subFreq = $row['subFreq'];
						$subForm = $row['subForm'];
						$subCOA = $row['subCOA' ];

						$sql="
							Insert into dw_sub             (  subSpec ,  subTest,  subFreq,  subForm,  subCOA,      subModUser    , subModDate)
							values                         (     ?    ,     ?   ,     ?   ,     ?   ,     ?  ,         ?          ,    now()  )
						";
						if(!savesql($link, $sql, "iiiiii", array($newspecid, $subTest, $subFreq, $subForm, $subCOA, $_SESSION['userID']            ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
				}

				if(isset($_POST['newcoa']) && ($_POST['newcoa']==1 || $_POST['newcoa']=='1')){
					//copy over coa form details
					$sql="
						Select *
						From dw_coa
						Where coaSpec = ?
					";
					if(!$qry = mysqli_prepared_query($link, $sql, "i", array($oldspecid), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					foreach($qry as $row){
						$coaTest = $row['coaTest'];

						$sql="
							Insert into dw_coa          (  coaSpec ,  coaTest,      coaModUser    , coaModDate)
							values                      (     ?    ,     ?   ,         ?          ,    now()  )
						";
						if(!savesql($link, $sql, "iii", array($newspecid, $coaTest, $_SESSION['userID']            ), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					}
				}
				$success = true;
			}else{
				//got zero rows or more than 1, or error (-1)
				$message['type']="error";
				$message['text']="Could not find the product with ID ".$oldspecid;
			}
		}else{
			$message['type']="error";
			$message['text']="Sorry but product ".$_POST['newspec' ]." already exists";
		}
	}

	$title = "Clone product";
	require "inc/head.php";
	$menu = "clone_product";
	require "inc/menu.php";

	if($debug) showdebug();

?>

<div id="topDIV" class="page-header">
	<h1 class="text-center"><?php echo $title; ?></h1>
</div>

<div class="container">
	<?php if($success){ ?><p class="bg-success">The product was successfully cloned</p><?php } ?>
	<form method="post" class="form-horizontal">
		<div class="form-group">
			<label for="exampleInputEmail1" class="control-label col-sm-2">Product to clone</label>
			<div class='col-sm-10'>
				<?php
					//get all specs
					$sql="
						Select
							dw_settings.comp_name,
							dw_spec.specID,
							dw_spec.specText,
							dw_spec.specShortDesc,
							dw_style.styleText
						From
							dw_spec Left Join
							dw_settings
							On dw_settings.settingsID = dw_spec.specSite Left Join
							dw_style
							On dw_spec.specStyle = dw_style.styleID
						Where
							specActive = 1
							And specSite = ?
						Order By
							dw_spec.specSite,
							dw_spec.specStyle,
							dw_spec.specOrder,
							dw_spec.specText
					";
					if(!$qry = mysqli_prepared_query($link, $sql, "i", array($_SESSION['userSite']), __FILE__, __LINE__)) reporterror(get_error(), $sql, $_SERVER['REQUEST_URI'], __FILE__, __LINE__);
					echo "<select name='specid' id='specid' class='form-control' onchange='getspec();'><option value='0'></option>";
					$group = array();
					foreach($qry as $row){
						$group[$row['styleText']][] = $row;
					}
					foreach ($group as $key => $values) {
						echo "<optgroup label='".$key."'>\n";
						foreach ($values as $value) {
							echo "<option value='".$value['specID']."'>".$value['specText'];
							if($value['specText']!= $value['specShortDesc']) echo " (".$value['specShortDesc'].")";
							echo "</option>";
						}
						echo "</optgroup>";
					}
					echo "</select>";
				?>
			</div>
		</div>
		<div class="form-group">
			<label for="newlimit" class="control-label col-sm-2">Copy test limits</label>
			<div class='col-sm-10'>
				<input type="checkbox" data-toggle="toggle" id="newlimit" name="newlimit" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" checked >
			</div>
		</div>
		<div class="form-group">
			<label for="newsub" class="control-label col-sm-2">Copy sub form details</label>
			<div class='col-sm-10'>
				<input type="checkbox" data-toggle="toggle" id="newsub" name="newsub" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" checked >
			</div>
		</div>
		<div class="form-group">
			<label for="newcoa" class="control-label col-sm-2">Copy tests on COA</label>
			<div class='col-sm-10'>
				<input type="checkbox" data-toggle="toggle" id="newcoa" name="newcoa" data-onstyle="success" data-offstyle="default" data-on="Yes" data-off="No" value="1" checked >
			</div>
		</div>
		<div id="newdata"></div>
		<?php if($_SESSION['userLevel']==1){ ?>
		<div class="form-group">
			<div class="col-sm-offset-2 col-sm-10">
				<button type="submit" class="btn btn-default btn-primary" name='create'>Create</button>
			</div>
		</div>
		<?php } ?>
	</form>
</div>
<script>
	function getspec() {
		var specid = document.getElementById('specid').value;
		var xmlhttp = new XMLHttpRequest();
		xmlhttp.onreadystatechange = function() {
			if (xmlhttp.readyState==4 && xmlhttp.status==200) {
				document.getElementById("newdata").innerHTML = xmlhttp.responseText;
			}
		};
		xmlhttp.open("GET", "ajax/get_spec.php?specid=" + specid + "&clone=true", true);
		xmlhttp.send();
	}

	dropdown("#product");
	dropdown("#newlocation");

</script>
<?php
	require "inc/footer.php";
?>
