<?php
# Here we are creating a new invoice.
# The name of the company will be fed to us, so all we have to do is transaction

# our config file
include('config.inc');

# the function that processes POST variables
include('getpostvars.inc');


# here we send our POST variables off to be processed
$company_id			= getpostvars('company_id', 11);
$day				= getpostvars('day', 2);
$month				= getpostvars('month', 2);
$year				= getpostvars('year', 4);
$today				= getpostvars('today', 5);
# $transaction_id isn't needed unless I'm doing an update session... right?
#$transaction_id	= getpostvars('transaction_id', 11);
#$transaction_date	= getpostvars('transaction_date', 10);
$type_name			= getpostvars('type_name', 20);
$problem			= getpostvars('problem', 4096);
$solution			= getpostvars('solution', 4096);
$technician_id		= getpostvars('technician_id', 12);
$labor_hours		= getpostvars('labor_hours', 16);
$labor_rate			= getpostvars('labor_rate', 16);
$tax_rate			= getpostvars('tax_rate', 16);
$password			= getpostvars('password', 16);			# shuffle this off to a session variable?
$verified			= getpostvars('verified', 5);
$material_lines		= getpostvars('material_lines', 3);	# this over-writes the initial value set above
$more_material		= getpostvars('more_material', 5);		# set this to add 5 to $lines_of_material


# let's set a couple of other variables
$paid				= 0;
# this needs to go away, or at least be only a default tax rate... see to-do item on the wiki
$tax_rate 			= 8.75;

#
# let's set up our database connection
include ('database.inc');

# this is our SQL escaping function
include ('escapesqldata.inc');

#
# the wrapper I wrote to help with database calls
include ('keyvalue.inc');



###############################################################################################
#                                       print header                                          #
###############################################################################################
$title	= 'Create Invoice';
include('header.inc');


###############################################################################################
#                           date and transaction type table                                   #
###############################################################################################

# fix the next line, echo it correctly.
?>
<form action="<?= $PHP_SELF ?>" method="POST" enctype="text">
<?php
# grab today's date if requested
if ($today == "true")
  {
    # need to end up on YYYY-MM-DD format
	# calculate $transaction_date later
    $month	= date("m");
    $day	= date("j");
    $year	= date("Y");
  };
?>

<big><b>Date and Invoice Information</b></big><br>
<table cols=2>
  <tr>
    <td><b>Date:</b>&nbsp;
      <input type="text" name="month" value="<?= $month ?>" size=2> /
      <input type="text" name="day" value="<?= $day ?>" size=2> /
      <input type="text" name="year" value="<?= $year ?>" size=4>
    </td>
    <td><b>Transaction type:</b>

      <?php
      # radio selection carried over from previous screen
      switch($type_name)
      {
        case 'Invoice':
          $invoicechecked = 'checked';
          break;
        case 'Estimate':
          $estimatechecked = 'checked';
          break;
        case 'Proposal':
          $proposalchecked = 'checked';
          break;
      };
      ?>

      &nbsp;<input type=radio name="type_name" <?= $invoicechecked ?> value="Invoice"> Invoice
      &nbsp;<input type=radio name="type_name" <?= $estimatechecked ?> value="Estimate"> Estimate
      &nbsp;<input type=radio name="type_name" <?= $proposalchecked ?> value="Proposal"> Proposal
    </td>
  </tr>
  <tr>
    <td><input type=checkbox name="today" value="true"> The work is being completed today. </td>
    <td> </td>
  <tr>
    <td><b>Invoice Number:</b>
	<?php echo $transaction_id;
	# I took out the form field here... when i write an update screen,
	# I'll have to carry $transaction_id again
	?>  </td>
    <td>  </td>
</table>


<?php
###############################################################################################
#                          retrieve company info from database                                #
###############################################################################################

echo "<big><b>Company Information</b></big><br>";

# next we grab the data for the company from the database
include ('showcompany.inc');

# here we embed $company_id into the form
echo "<input type=hidden name=\"company_id\" value=\"$company_id\">\n";

###############################################################################################
#                              description of work performed                                  #
###############################################################################################
?>

<p><big><b>Problem Reported</big></b>
<br><textarea name="problem" value="<?= $problem; ?>" cols="80" rows="5"><?= $problem; ?></textarea>

<p><big><b>Description of work performed</big></b>
<br><textarea name="solution" value="<?= $solution; ?>" cols="80" rows="5"><?= $solution; ?></textarea>

<?php
#<p><b>Technician's username:</b> <input type="text" name="technician_id" value="<?= $technician_id; ? >" size=12>

echo "<p><b>Technician's username:</b>\n";
dropdown_select_id ($technician_id, 'technician', $link);
?>



<?php
###############################################################################################
#                                      materials used                                         #
###############################################################################################
#
# here we twiddle the number of lines showing in the materials form
# we need to start out with at least 5 lines in the form
if ($material_lines == '') {
$material_lines		= 5;
}
#
# we check to see if more lines of material are needed, and increment if necessary
if ($more_material == 'true') {
$material_lines		= $material_lines + 5;
}

echo "<input type=hidden name=\"material_lines\" value=\"$material_lines\">\n";

?>

<p><big><b>Materials Used</big></b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
Need to add more lines of material? <input type=checkbox name="more_material" value="true">
<table border=1 width="100%">
  <tr>
    <th>
      Quantity
    </td>
    <th>
      Description
    </td>
    <th>
      Unit Price
    </td>
    <th>
      Extended
    </td>
  </tr>

  <?php

  # loop places materials into an array
  for ($line=1; $line <= $material_lines; $line++) {
    # for clarity's sake, we'll $_POST the materials variables here instead of at the top
    $materials[$line]["quantity"] = $_POST["materials"][$line]["quantity"];
	$materials[$line]["item_description"] = $_POST["materials"][$line]["item_description"];
	$materials[$line]["unitprice"] = $_POST["materials"][$line]["unitprice"];
	
    echo "<tr>\n";
    echo "<td align=\"center\"><input type=\"text\" name=\"materials[$line][quantity]\"
        size=4 value=\"" . $materials[$line]["quantity"] . "\">  </td>\n";
    echo "<td align=\"left\"><input type=\"text\" name=\"materials[$line][item_description]\"
        size=60 value=\"" . $materials[$line]["item_description"] . "\">  </td>\n";
    echo "<td align=\"right\"><input type=\"text\" name=\"materials[$line][unitprice]\"
        size=9 value=\"" . $materials[$line]["unitprice"] . "\">  </td>\n";
	$extended	= $materials[$line]["quantity"] * $materials[$line]["unitprice"];
	$materialtotal	= $materialtotal + $extended;
    echo "<td align=\"right\">\$" . number_format($extended,2) . "  </td>\n";
    echo "</tr>\n";
  }

  # labor rate
  $labortotal	= $labor_hours * $labor_rate;

  # ugh, clean this up,it stinks
  echo "
  <tr>
      <td align=\"center\"><input type=\"text\" name=\"labor_hours\"
        size=4 value=\"" . $labor_hours . "\"></td>
		<td align=\"left\">hours labor</td>
      <td align=\"right\"><input type=\"text\" name=\"labor_rate\"
        size=9 value=\"" . $labor_rate . "\"></td>
      <td align=\"right\">$labortotal</td>
  </tr>\n";

  # here we have to add up all the numbers and print out our totals
  include ('totals.inc');
  ?>

</table>



<?php
###############################################################################################
#                                      form submittal                                         #
###############################################################################################
?>
<p><input type=checkbox name="verified" value="true"> All data has been verified.
<p><input type=submit value="Submit"></p>
</form>


<?php
###############################################################################################
#                                     database insert                                         #
###############################################################################################

# Now we can do our insert

# This needs to have referential integrity, and I can't do that kind of stuff yet

# here's my algorithm:
# do the transaction insert
# get the transaction_id
# do the materials inserts, in a loop, checking each line along the way for validity


if ( ($verified == 'true') ) {

  # need to construct $transaction_date
  $transaction_date	= $year . "-" . $month . "-" . $day;

  # we need to escape our SQL data before doing the query using escapesqldata()
  $transaction_date		= escapesqldata($transaction_date);
  $type_id				= escapesqldata($type_id);
  $company_id			= escapesqldata($company_id);
  $purchase_order		= escapesqldata($purchase_order);
  $project_reference	= escapesqldata($project_reference);
  $problem				= escapesqldata($problem);
  $technician_id		= escapesqldata($technician_id);
  $labor_hours			= escapesqldata($labor_hours);
  $labor_rate			= escapesqldata($labor_rate);
  $tax_rate				= escapesqldata($tax_rate);

  # Ok, this is utterly horrible.
  # There must be a way to refactor this. I've just typed these field names in thrice.
  # Step through an array?
  # What about putting this in a class, once I figure out how to do OOP?

  # let's grab $type_id from the database
  $type_id	= fetch_id($type_id, $type_name, 'type', $link);

  # transaction
  #$fields		= 'transaction_id, type_id, date, company_id';
  $fields		= 'transaction_date, type_id, company_id';
  $fields		.= ', purchase_order, project_reference, problem, solution';
  $fields		.= ', technician_id, labor_hours, labor_rate, tax_rate, paid';

  #$values		= "'NULL, $type_id, $transaction_date', '$company_id'";
  $values		= "'$transaction_date', '$type_id', '$company_id'";
  $values		.= ", '$purchase_order', '$project_reference', '$problem', '$solution'";
  $values		.= ", '$technician_id', '$labor_hours', '$labor_rate', '$tax_rate', '$paid'";

  $table		= 'transaction';
  @mysql_query ("INSERT INTO $table ($fields) VALUES ($values)", $link);
  echo "<br>INSERT INTO $table ($fields) VALUES ($values)<br>\n";

  # need to determine $transaction_id that was just assigned,
  # so we can insert it into table material
  $transaction_id	= mysql_insert_id();
  echo "<h2>transaction_id = $transaction_id</h2>\n";

  # material
  # here we need to loop this to get all values from the array

  for ($line=1; $line <= $material_lines; $line++) {

	# all of these have been posted above, so we can just use the data
	$quantity						= $materials[$line]["quantity"];
    # $item_type hasn't been integrated into the form yet...
    #$item_type						= $materials[$line]["item_type"];
    #$item_type						= '';	# do this, or just leave it undefined?
    $item_description				= $materials[$line]["item_description"];
    $unitprice						= $materials[$line]["unitprice"];

	# here we need to test each line for actual data before doing the insert
	if ( ($quantity != '') and ($item_description != '') and ($unitprice != '') ) {
      # since we apparently have some sort of data, let's do an insert on table material

	  # Here we excape the SQL before running the query
	  $quantity						= escapesqldata($quantity);
	  # $item_type					= escapesqldata($item_type); 	# we haven't placed this into the form yet
	  $item_description				= escapesqldata($item_description);
	  $unitprice					= escapesqldata($unitprice);


      $fields			= 'transaction_id, quantity, item_type, item_description, unitprice';
      $values			= "'$transaction_id', '$quantity', '$item_type', '$item_description', '$unitprice'";

      $table			= 'material';
      @mysql_query ("INSERT INTO $table ($fields) VALUES ($values)", $link);
      echo "<br>INSERT INTO $table ($fields) VALUES ($values)<br>\n";
	}

  }

  # echo results to the user
  # query for $type_name
  echo "<big><b>Thanks. The $type_id was added to the database.</b></big>\n";
  include('dberrors_insert.inc');


  echo "<form action=\"printinvoice.php\" method=\"POST\" enctype=\"text\">
    <input type=hidden name=\"transaction_id\" value=\"$transaction_id\">
    <input type=submit value=\"Print Invoice\">
    </form>\n<br><br>\n";

}

echo "<P>";
print_r($_POST);
?>
