<?php
include('../headertop.php');
include('../db.php');
//include('../datepicker.php');

$disp = '';
$pagetitle = 'Add Project Estimations';

date_default_timezone_set('Asia/Kolkata');

if(!isset($_POST['estimatesubmit']))
{
echo '<meta http-equiv="refresh" content="0;URL=estimates.php">';
exit;
}



$project = 1;
$estimate = $_POST['estimate'];

/*
$qp = "select project_name from project where id='$project'";
$resp = mysqli_query($dbcon,$qp) or die(mysqli_error($dbcon));
$rwp = mysqli_fetch_array($resp);
*/

foreach($estimate as $k=>$v)
{
if(is_numeric($v) and $v>0)
	{
	$qwt = "select work_type from work_type where id='$k'";
	$reswt = mysqli_query($dbcon,$qwt) or die(mysqli_error($dbcon));
	$rwwt = mysqli_fetch_array($reswt);
	
	$qfindest = "select * from estimates where project_id='$project' and work_type_id='$k'";
	$rfindest = mysqli_query($dbcon,$qfindest) or die(mysqli_error($dbcon));
	
	if(mysqli_num_rows($rfindest)<1)	
	$qins[] = "insert into estimates(project_id,project_name,work_type_id,work_type_name,estimate) values('$project','XYZ Project','$k','".$rwwt['work_type']."','$v')";
	else
	$qins[] = "update estimates set estimate='$v' where project_id='$project' and work_type_id='$k'";
	}
}

mysqli_autocommit($dbcon, false);

foreach($qins as $query)
{
$results[] = mysqli_query($dbcon,$query) or die(mysqli_error());
}

foreach($results as $result)
{
	if(!$result)
	{
	mysqli_rollback($dbcon);
	echo '<meta http-equiv="refresh" content="0;URL=estimates.php?sm=Could not save estimates information. Try again!">';
	exit;
	}
}

mysqli_commit($dbcon);

$sm = "Estimates information saved ";
echo '<meta http-equiv="refresh" content="0;URL=estimates.php?sm='.$sm.'">';
