<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if (isset($_GET['do']) && $_GET['do'] === 'save') {
    include_once 'includes/settings.php';
} else {
    include_once 'includes/init.php';
}

include_once 'billing/form.php';

// check if Marc, Eric, Lou or Fran are logged in (don't allow studio)
if (!isset($login)) {
    die('You must <a href="/calendar/">log in</a> to the calendar first.');
} else {
    if ($login != 'Marc' && $login != 'nico' && $login != 'andres' && $login != 'Lou' && $login != 'duffharris')
        die('You are NOT authorized!');
}

if (isset($_GET['do']) && $_GET['do'] == "save") {
    echo 'here';
    exit;
    save_invoice($_GET['do']);
} else if (isset($_GET['do']) && $_GET['do'] == "print") {
    print_invoice();
} else if (isset($_GET['do']) && $_GET['do'] == "edit") {
    retrive_invoice($_GET['do']);
} else if (isset($_GET['do']) && $_GET['do'] == "update") {
//	echo '<b>I am doing maintanence. Please come back in an hour. Thanks. Marc</b><br /><br />';
//	echo '<pre>';	print_r($_POST);	echo '</pre>';
    save_invoice($_GET['do']);
} else if (isset($_GET['do']) && $_GET['do'] == "delete") {
    delete_invoice();
} else if (!isset($_GET['do']) && !isset($_GET['id'])) {
    show_invoices();
}

if ((isset($_GET['id']) && !isset($_GET['do'])) || (isset($_GET['id']) && isset($_GET['do']) && $_GET['do'] == 'print')) {
    // get ID and date from URL
    $id = $_GET['id'];
    if (isset($_GET['date']))
        $date = $_GET['date'];

    // get all the id, dates and various names from the DB
    $mysqli = mysqli_connect($db_host, $db_login, $db_password, $db_database);
    $results = dbi_execute("SELECT id, date, artist, contact, company, totalpaid FROM `BILLING`") or die(mysqli_error());
    while ($row = mysqli_fetch_array($results)) {
        $ids[] = $row['id'];
    }
    // if the ID exists retrive the invoice, otherwise, if it doesn't exist in the DB let's add it
    if (isset($ids) && in_array($id, $ids)) {
        retrive_invoice('show');
    } else {
        invoice('add');
    }
}

?>
<html>
<head>
    <title>EastSide Sound Billing System<? echo( isset($_GET['id']) ? ' [invoice #'.$_GET['id'].( isset($_GET['addl_ids']) && !empty($_GET['addl_ids']) ? ' (multiple: '.$_GET['addl_ids'].')' : '' ).']' : '' ) ?></title>
    <meta HTTP-EQUIV="Pragma" CONTENT="no-cache">
    <meta HTTP-EQUIV="Expires" CONTENT="-1">

    <?php
    if ( !isset($_GET['do']) || ( isset($_GET['do']) && $_GET['do'] != "print" ) ) {
        include_once 'billing/styles.php';
        include_once 'billing/js.php';
        echo '
  <style type="text/css">
  <!--
	p.billingtable {
		font-size: 11px;
 	}
	tr.on td {
		background-color: #FAB1DF;
	}
	tr.monthly_total {
		background-color: #CCCCCC;
	}
	tr.monthly_owed {
		background-color: #FFCCFF;
	}
	tr.yearly_total {
		background-color: #000000;
	}
	tr.yearly_owed {
		background-color: #FF0000;
		color: #000000;
	}  -->
  </style>
';
    } else {
        // printing stylesheet
        echo '
  <script type="text/javascript">
	<!--
	function PrintInvoice(iframe) {
		iframe.focus();
		iframe.print();
	}
	-->
  </script>
  <noscript>Sorry but you need JavaScript enabled for this to work!</noscript>

  <style type="text/css">
  <!--
  body {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 12px;
	background-color: #FFFFFF;
  }
  -->
  </style>
';
    }
    ?>
</head>
<?php

if ( isset($_POST['additional_ids']) ) {
    for ( $i=0;$i<count($_POST['additional_ids']);$i++ ) {
        $all_ids .= substr($_POST['additional_ids'][$i],0,strpos($_POST['additional_ids'][$i],'#%#')).','; // extract all IDs and separate them by comma to put in the URL later
    }
    $addl_ids_url = explode('#%#',array_pop($_POST['additional_ids']));
    Header("Location:".$_SERVER['PHP_SELF']."?id=".$addl_ids_url[0]."&date=".$addl_ids_url[1]."&client=".urlencode($addl_ids_url[2])."&room=".$addl_ids_url[3]."&addl_ids=".rtrim($all_ids,','));
}
echo '<body'.( isset($_GET['print']) && $_GET['print'] == 'now' ? ' onload="PrintInvoice(this);"' : ( isset($_GET['do']) && $_GET['do'] == 'edit' ? ' onload="get_timers();"' : '' ) ).'>';

// show invoices
function show_invoices () {
    global $db_host, $db_login, $db_password, $db_database,$login,$_POST;
    $cr = '
';
    $cols = '8';
    $mysqli = mysqli_connect ( $db_host, $db_login, $db_password, $db_database );
    $query = 'SELECT id, date, engineer, artist, contact, company, project, subtot_notax, deposit, totalowed, totalpaid FROM `BILLING`';
    function ascdesc() {
        if ( isset($_GET['by']) )
            if ( isset($_GET['in']) && $_GET['in'] == 'ASC' )
                return 'ASC';
            else
                return 'DESC';
        else
            return 'ASC';
    }
    function inverse_ascedesc() {
        if ( ascdesc() == 'ASC' )
            return 'DESC';
        else
            return 'ASC';
    }

    // to avoid Undefined variable errors;
    if (isset($_GET['by'])) {
        if ( $_GET['by'] == 'date' )
            $query .= ' ORDER BY date '.ascdesc();
        else if ( $_GET['by'] == 'artist' )
            $query .= ' ORDER BY artist '.ascdesc();
        else if ( $_GET['by'] == 'contact' )
            $query .= ' ORDER BY contact '.ascdesc();
        else if ( $_GET['by'] == 'company' )
            $query .= ' ORDER BY company '.ascdesc();
        else if ( $_GET['by'] == 'total' )
            $query .= ' ORDER BY totalpaid '.ascdesc();
        else if ( $_GET['by'] == 'project' )
            $query .= ' ORDER BY project '.ascdesc();
        else if ( $_GET['by'] == 'engineer' )
            $query .= ' ORDER BY engineer '.ascdesc();
        else if ( $_GET['by'] == 'invoice' )
            $query .= ' ORDER BY id '.ascdesc();
    } else {
        $query .= ' ORDER BY date DESC';
    }

    $results = dbi_execute ($query) or die(mysqli_error());
    echo '<div class="title"><br /><a href="/calendar/">Back to Calendar</a><br /><span class="date"><br />EastSide Sound Billing System</span><span class="user"><br />'.$login.'</span><br /><br />(you may click on the column names to re-order)<br /><br /></div>';
    if ( $login == 'Marc' || $login == 'Lou' ) echo '<div class="title"><br /><a href="'.$_SERVER['PHP_SELF'].'?by=date&in=DESC&monthly_total=1">Show Monthly Totals</a> | <a href="'.$_SERVER['PHP_SELF'].'?by=date&in=DESC&yearly_tot=1">Show Yearly Totals</a><br /><br /></div>';
    echo '<table align="center" class="main" style="clear:both;" cellpadding="0" cellspacing="0" border="0" bordercolor="#000000">';
    echo '
		<th><p style="text-align:center">&nbsp;&nbsp;<a href="'.$_SERVER['PHP_SELF'].'?by=date&in='.inverse_ascedesc().'">Date</a>&nbsp;&nbsp;&nbsp;&nbsp;</p></th>
		<th><p style="text-align:left"><a href="'.$_SERVER['PHP_SELF'].'?by=artist&in='.inverse_ascedesc().'">Artist</a></p></th>
		<th><p style="text-align:left"><a href="'.$_SERVER['PHP_SELF'].'?by=contact&in='.inverse_ascedesc().'">Contact</a></p></th>
		<th><p style="text-align:left"><a href="'.$_SERVER['PHP_SELF'].'?by=company&in='.inverse_ascedesc().'">Company</a></p></th>
		<th><p style="text-align:left"><a href="'.$_SERVER['PHP_SELF'].'?by=project&in='.inverse_ascedesc().'">Project</a></p></th>
		<th><p style="text-align:left"><a href="'.$_SERVER['PHP_SELF'].'?by=engineer&in='.inverse_ascedesc().'">Eng</a>&nbsp;&nbsp;&nbsp;&nbsp;</p></th>
		<th><p style="text-align:right"><a href="'.$_SERVER['PHP_SELF'].'?by=total&in='.inverse_ascedesc().'">Invoice Total</a></p></th>
		<th><p style="text-align:right"></p></th>
		<th><p style="text-align:right"><a href="'.$_SERVER['PHP_SELF'].'?by=invoice&in='.inverse_ascedesc().'">Invoice No.</a></p></th>
		'.$cr;

    $i = 1;	// defining $i row counter to avoid undefined variable display_errors

    while ( $row = mysqli_fetch_array( $results ) ) {

        $i++; // needed for table rows' coloration
//if ( $login == 'Marc' || $login == 'Lou' ) {
//		if ( $_GET['by'] == 'date' ) {

        $list_date[$i] = $row['date'];						//	2007-12-21		2007-11-13		2007-11-10
        $year = substr($list_date[$i],0,4);
        $month = substr($list_date[$i],5,2);				//	12				11				11

        // get totals paid and due from invoice being fetched
        if ( !is_numeric($row['totalpaid']) ) {													// unpaid bill
            if ( $row['deposit'] != 0 && $row['deposit'] < $row['subtot_notax'] ) {				// partial deposit
                $paid = $row['deposit'];
                $owed = $row['totalowed'];
            } else {
                $paid = 0;
                $owed = $row['totalowed'];														// no deposit, no payments at all
            }
        } else if ( is_numeric($row['totalpaid']) && $row['totalpaid'] != 0 ) {					// paid bill
            $paid = $row['totalpaid'];
            $owed = 0;	// leave this here or it will break!!!
        } else if ( is_numeric($row['totalpaid']) && $row['totalpaid'] == 0 ) {					// unpaid bill
            $paid = 0;
            $owed = $row['totalowed'];
        }

        // calculate monthly totals
        if ( !isset($mm) ) { // first time around
            $mm = $month;
            $yy = $year;
            $month_Name = date("F", mktime(0, 0, 0, $mm, 10));
            $monthly_total[$mm] = $paid;
            if ( ( (float)$owed - (float)$paid ) > 0 )
                $monthly_owed[$mm] = $owed;
            else
                $monthly_owed[$mm] = 0;
        } else {
            if ( $mm == $month ) { // still in the same month
                $monthly_total[$mm] = (float)$monthly_total[$mm] + (float)$paid;
                $monthly_owed[$mm] = (float)$monthly_owed[$mm] + (float)$owed;
            }
            else if ( ( ( isset($_GET['yearly_tot']) && $_GET['yearly_tot'] == '1' ) || ( isset($_GET['monthly_total']) && $_GET['monthly_total'] == '1' ) ) && $mm != $month ) { // now different month
                echo '<tr class="monthly_total"><td colspan="'.($cols-4).'">&nbsp;</td><td class="entry">Gross Total for month of <b>'.( date("F", mktime(0, 0, 0, $mm, 10)) ).' '.( $month == 12 ? $year+1 : $year ).'</b></td><td></td><td class="entry"><p style="text-align:right">$<span style="font-weight:bold;color:black;background:lime;">'.number_format((float)$monthly_total[$mm],2,'.','').'</span>&nbsp;</p></td><td colspan="2"></td></tr>'.$cr;
                if ( $monthly_owed[$mm] > 0 )
                    echo '<tr class="monthly_owed"><td colspan="'.($cols-4).'">&nbsp;</td><td class="entry">Money Owed from month of <b>'.( date("F", mktime(0, 0, 0, $mm, 10)) ).' '.( $month == 12 ? $year+1 : $year ).'</b></td><td></td><td class="entry"><p style="text-align:right">$<span style="font-weight:bold;color:black;background:red;">'.number_format($monthly_owed[$mm],2,'.','').'</span>&nbsp;</p></td><td colspan="2"></td></tr>'.$cr;

                if ( isset($_GET['yearly_tot']) && $_GET['yearly_tot'] && isset($yy) ) {
                    $yearly_total[$yy] = (float)$yearly_total[$yy] + (float)$monthly_total[$mm];
                    $yearly_owed[$yy] = (float)$yearly_owed[$yy] + (float)$monthly_owed[$mm];
                }
                $mm = $month;
                $monthly_total[$mm] = $paid;
                $monthly_owed[$mm] = $owed;
            }
        }

        if ( isset($_GET['yearly_tot']) && $_GET['yearly_tot'] == '1' &&  $yy != $year ) { // now different year
            //$yearly_total = $_GET['yearly_total'];
            echo '<tr class="yearly_total"><td colspan="'.($cols-4).'">&nbsp;</td><td class="entry">Gross Total for <b>'.( $month == 12 ? $year+1 : $year ).'</b></td><td></td><td class="entry"><p style="text-align:right">$<span style="font-weight:bold;color:black;background:lime;">'.number_format((float)$yearly_total[$yy],2,'.','').'</span>&nbsp;</p></td><td colspan="2"></td></tr>'.$cr;
            if ( $yearly_owed[$yy] > 0 )
                echo '<tr class="yearly_owed"><td colspan="'.($cols-4).'">&nbsp;</td><td class="entry">Money Owed from <b>'.( $month == 12 ? $year+1 : $year ).'</b></td><td></td><td class="entry"><p style="text-align:right">$<span style="font-weight:bold;color:black;background:red;">'.number_format((float)$yearly_owed[$yy],2,'.','').'</span>&nbsp;</p></td><td colspan="2"></td></tr>'.$cr;
            $yy = $year;
        }

//		}
//}

        echo '	<tr'.( is_int($i/2) ? ' style="background-color: #AFB1DF;" class="off" onmouseover="this.className=\'on\'" onmouseout="this.className=\'off\'"' : ' class="off" onmouseover="this.className=\'on\'" onmouseout="this.className=\'off\'"' ).'>'.$cr;

        echo '		<td class="entry"><p class="billingtable"><a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'">&nbsp;&nbsp;&nbsp;'.$row['date'].'&nbsp;&nbsp;&nbsp;</a></p></td>'.$cr;
        echo '		<td class="entry"><p class="billingtable"><a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'"><b>'.stripslashes($row['artist']).'</b></a></p></td>'.$cr;
        echo '		<td class="entry"><p class="billingtable"><a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'">'.stripslashes($row['contact']).'</a></p></td>'.$cr;
        echo '		<td class="entry"><p class="billingtable"><a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'">'.stripslashes($row['company']).'</a></p></td>'.$cr;
        echo '		<td class="entry"><p class="billingtable"><a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'">'.stripslashes($row['project']).'</a></p></td>'.$cr;
        echo '		<td class="entry"><p class="billingtable"><a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'">'.substr($row['engineer'],0,1).'</a></p></td>'.$cr;
        // colors from http://www.w3.org/TR/css3-color/
        if ( !is_numeric($row['totalpaid']) ) {																									// unpaid bill
            if ( $row['deposit'] != 0 && $row['deposit'] < $row['subtot_notax'] ) {
                $total_displayed = '$<span style="color:orangered;"><b>'.(float)$row['deposit'].'</b>&nbsp;</span><br />
										out of &nbsp;<br />
										$<span style="color:green;"><b>'.number_format(((float)$row['deposit']+(float)$row['totalowed']),2,'.','').'</b></span>';	// partial deposit
            } else {
                $total_displayed = '$<span style="color:red;background:orange;"><b>'.number_format((float)$row['totalowed'],2,'.','').'</b></span>';	// no deposit, no payments at all
            }
        } else if ( is_numeric($row['totalpaid']) && $row['totalpaid'] != 0 ) {																	// paid bill
            $total_displayed = '$<span style="color:green;"><b>'.number_format($row['totalpaid'],2,'.','').'</b></span>';
        } else if ( is_numeric($row['totalpaid']) && $row['totalpaid'] == 0 ) {																	// paid bill
            $total_displayed = '$<span style="color:red;background:orange;"><b>'.number_format($row['totalowed'],2,'.','').'</b></span>';	// unpaid bill
        }


        echo '		<td class="entry"><p style="text-align:right"><a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'">'.$total_displayed.'&nbsp;</a></p></td>'.$cr;

        echo '		<td class="entry"><p class="billingtable" style="text-align:right">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;[<a href="'.$_SERVER['PHP_SELF'].'?do=delete&id='.$row['id'].'" onclick="return confirm(\'You are about to delete an invoice permanently. This action is NOT undoable. Are you sure you want to do that?\')";><font style="color:red;">x</font></a>]</p></td>'.$cr;
        echo '		<td class="entry"><p class="billingtable" style="text-align:right">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="'.$_SERVER['PHP_SELF'].'?id='.$row['id'].'">'.$row['id'].'&nbsp;</a></p></td>'.$cr;
        echo '	</tr>'.$cr;

    }

    echo '</table>';
    mysqli_close($mysqli);
}

// print invoice
function print_invoice($id='') {
    echo '<img src="billing/ESS_official_logo.jpg" width="720px" height="150" border="0" alt="East Side Sound logo" /><br /><br />';
}

// retrive invoice for showing or editing
function retrive_invoice($action) {
    global $db_host, $db_login, $db_password, $db_database, $data;
    $mysqli = mysqli_connect ( $db_host, $db_login, $db_password, $db_database );
    $results = dbi_execute ("SELECT * FROM BILLING WHERE id = ".$_GET['id']) or die(mysqli_error());
    $data = mysqli_fetch_array( $results );
    if ( $action === 'show' ) {
        invoice('show',$data);
    } else if ( $action === 'edit' ) {
        invoice('edit',$data);
    }
    mysqli_close($mysqli);
}

// delete invoice
function delete_invoice() {
    global $db_host, $db_login, $db_password, $db_database, $data;
    $mysqli = mysqli_connect ( $db_host, $db_login, $db_password, $db_database );
    dbi_execute ("DELETE FROM BILLING WHERE id = ".$_GET['id']) or die(mysqli_error());
    mysqli_close($mysqli);
    show_invoices();
    die;
}

// extract additional ids from query


// add id entries with relative id
function save_addl_ids () {
    if ( isset($_GET['addl_ids']) ) {
        global $db_host, $db_login, $db_password, $db_database, $_POST;
        $mysqli = mysqli_connect ( $db_host, $db_login, $db_password, $db_database );
        // query
        $query = 'INSERT INTO BILLING SET
			id = '.mysqli_real_escape_string($mysqli,$_POST['id']).',
			rel_id = \''.mysqli_real_escape_string($mysqli,$_POST['rel_id']).'\';';
        // mysqli_query($query) or die(mysqli_error());
        mysqli_close($mysqli);
    }
}

// add invoice
function save_invoice ($do) {
    global $db_host, $db_login, $db_password, $db_database, $_POST;
    $mysqli = mysqli_connect ( $db_host, $db_login, $db_password, $db_database );
    // query
    if ( $do == 'save' ) {
        echo'here'; exit;
        $query = 'INSERT INTO BILLING SET
		id = '.mysqli_real_escape_string($mysqli, $_POST['id']).',';
    } else if ( $do == 'update' ) {
        $query = 'UPDATE BILLING SET';
    }
    $query .= '
		date = \''.mysqli_real_escape_string($mysqli,$_POST['date']).'\',
		artist = \''.mysqli_real_escape_string($mysqli,$_POST['artist']).'\',
		contact = \''.mysqli_real_escape_string($mysqli,$_POST['contact']).'\',
		company = \''.mysqli_real_escape_string($mysqli,$_POST['company']).'\',
		address = \''.mysqli_real_escape_string($mysqli,$_POST['address']).'\',
		city = \''.mysqli_real_escape_string($mysqli,$_POST['city']).'\',
		zip = \''.mysqli_real_escape_string($mysqli,$_POST['zip']).'\',
		country = \''.mysqli_real_escape_string($mysqli,$_POST['country']).'\',
		phone = \''.mysqli_real_escape_string($mysqli,$_POST['phone']).'\',
		email = \''.mysqli_real_escape_string($mysqli,$_POST['email']).'\',
		project = \''.mysqli_real_escape_string($mysqli,$_POST['project']).'\',
		po = \''.mysqli_real_escape_string($mysqli,$_POST['po']).'\',
		temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['temp1'] ?? '').'\',
		temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['temp2'] ?? '').'\',
		temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['temp3'] ?? '').'\',
		engineer = \''.mysqli_real_escape_string($mysqli,$_POST['engineer']).'\',
		payment = \''.mysqli_real_escape_string($mysqli,$_POST['payment']).'\',
		whose = \''.mysqli_real_escape_string($mysqli,$_POST['whose']).'\',
		rel_id = \''.mysqli_real_escape_string($mysqli,$_POST['rel_id'] ?? '').'\',
		temp6 = \''.mysqli_real_escape_string($mysqli,$_POST['temp6'] ?? '').'\',
		temp7 = \''.mysqli_real_escape_string($mysqli,$_POST['temp7'] ?? '').'\',
		temp8 = \''.mysqli_real_escape_string($mysqli,$_POST['temp8'] ?? '').'\',
		temp9 = \''.mysqli_real_escape_string($mysqli,$_POST['temp9'] ?? '').'\',
		temp10 = \''.mysqli_real_escape_string($mysqli,$_POST['temp10'] ?? '').'\',
		l1_day = \''.mysqli_real_escape_string($mysqli,$_POST['l1_day']).'\',
		l1_start = \''.mysqli_real_escape_string($mysqli,$_POST['l1_start']).'\',
		l1_end = \''.mysqli_real_escape_string($mysqli,$_POST['l1_end']).'\',
		l1_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l1_qty']).'\',
		l1_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l1_rate']).'\',
		l1_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l1_desc']).'\',
		l1_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l1_subtot']).'\',
		l1_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l1_temp1'] ?? '').'\',
		l1_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l1_temp2'] ?? '').'\',
		l1_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l1_temp3'] ?? '').'\',
		l2_day = \''.mysqli_real_escape_string($mysqli,$_POST['l2_day']).'\',
		l2_start = \''.mysqli_real_escape_string($mysqli,$_POST['l2_start']).'\',
		l2_end = \''.mysqli_real_escape_string($mysqli,$_POST['l2_end']).'\',
		l2_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l2_qty']).'\',
		l2_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l2_rate']).'\',
		l2_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l2_desc']).'\',
		l2_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l2_subtot']).'\',
		l2_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l2_temp1'] ?? '').'\',
		l2_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l2_temp2'] ?? '').'\',
		l2_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l2_temp3'] ?? '').'\',
		l3_day = \''.mysqli_real_escape_string($mysqli,$_POST['l3_day']).'\',
		l3_start = \''.mysqli_real_escape_string($mysqli,$_POST['l3_start']).'\',
		l3_end = \''.mysqli_real_escape_string($mysqli,$_POST['l3_end']).'\',
		l3_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l3_qty']).'\',
		l3_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l3_rate']).'\',
		l3_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l3_desc']).'\',
		l3_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l3_subtot']).'\',
		l3_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l3_temp1'] ?? '').'\',
		l3_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l3_temp2'] ?? '').'\',
		l3_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l3_temp3'] ?? '').'\',
		l4_day = \''.mysqli_real_escape_string($mysqli,$_POST['l4_day']).'\',
		l4_start = \''.mysqli_real_escape_string($mysqli,$_POST['l4_start']).'\',
		l4_end = \''.mysqli_real_escape_string($mysqli,$_POST['l4_end']).'\',
		l4_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l4_qty']).'\',
		l4_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l4_rate']).'\',
		l4_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l4_desc']).'\',
		l4_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l4_subtot']).'\',
		l4_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l4_temp1'] ?? '').'\',
		l4_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l4_temp2'] ?? '').'\',
		l4_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l4_temp3'] ?? '').'\',
		l5_day = \''.mysqli_real_escape_string($mysqli,$_POST['l5_day']).'\',
		l5_start = \''.mysqli_real_escape_string($mysqli,$_POST['l5_start']).'\',
		l5_end = \''.mysqli_real_escape_string($mysqli,$_POST['l5_end']).'\',
		l5_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l5_qty']).'\',
		l5_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l5_rate']).'\',
		l5_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l5_desc']).'\',
		l5_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l5_subtot']).'\',
		l5_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l5_temp1'] ?? '').'\',
		l5_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l5_temp2'] ?? '').'\',
		l5_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l5_temp3'] ?? '').'\',
		l6_day = \''.mysqli_real_escape_string($mysqli,$_POST['l6_day']).'\',
		l6_start = \''.mysqli_real_escape_string($mysqli,$_POST['l6_start']).'\',
		l6_end = \''.mysqli_real_escape_string($mysqli,$_POST['l6_end']).'\',
		l6_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l6_qty']).'\',
		l6_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l6_rate']).'\',
		l6_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l6_desc']).'\',
		l6_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l6_subtot']).'\',
		l6_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l6_temp1'] ?? '').'\',
		l6_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l6_temp2'] ?? '').'\',
		l6_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l6_temp3'] ?? '').'\',
		l7_day = \''.mysqli_real_escape_string($mysqli,$_POST['l7_day']).'\',
		l7_start = \''.mysqli_real_escape_string($mysqli,$_POST['l7_start']).'\',
		l7_end = \''.mysqli_real_escape_string($mysqli,$_POST['l7_end']).'\',
		l7_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l7_qty']).'\',
		l7_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l7_rate']).'\',
		l7_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l7_desc']).'\',
		l7_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l7_subtot']).'\',
		l7_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l7_temp1'] ?? '').'\',
		l7_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l7_temp2'] ?? '').'\',
		l7_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l7_temp3'] ?? '').'\',
		l8_day = \''.mysqli_real_escape_string($mysqli,$_POST['l8_day']).'\',
		l8_start = \''.mysqli_real_escape_string($mysqli,$_POST['l8_start']).'\',
		l8_end = \''.mysqli_real_escape_string($mysqli,$_POST['l8_end']).'\',
		l8_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l8_qty']).'\',
		l8_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l8_rate']).'\',
		l8_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l8_desc']).'\',
		l8_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l8_subtot']).'\',
		l8_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l8_temp1'] ?? '').'\',
		l8_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l8_temp2'] ?? '').'\',
		l8_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l8_temp3'] ?? '').'\',
		l9_day = \''.mysqli_real_escape_string($mysqli,$_POST['l9_day']).'\',
		l9_start = \''.mysqli_real_escape_string($mysqli,$_POST['l9_start']).'\',
		l9_end = \''.mysqli_real_escape_string($mysqli,$_POST['l9_end']).'\',
		l9_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l9_qty']).'\',
		l9_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l9_rate']).'\',
		l9_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l9_desc']).'\',
		l9_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l9_subtot']).'\',
		l9_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l9_temp1'] ?? '').'\',
		l9_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l9_temp2'] ?? '').'\',
		l9_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l9_temp3'] ?? '').'\',
		l10_day = \''.mysqli_real_escape_string($mysqli,$_POST['l10_day']).'\',
		l10_start = \''.mysqli_real_escape_string($mysqli,$_POST['l10_start']).'\',
		l10_end = \''.mysqli_real_escape_string($mysqli,$_POST['l10_end']).'\',
		l10_qty = \''.mysqli_real_escape_string($mysqli,$_POST['l10_qty']).'\',
		l10_rate = \''.mysqli_real_escape_string($mysqli,$_POST['l10_rate']).'\',
		l10_desc = \''.mysqli_real_escape_string($mysqli,$_POST['l10_desc']).'\',
		l10_subtot = \''.mysqli_real_escape_string($mysqli,$_POST['l10_subtot']).'\',
		l10_temp1 = \''.mysqli_real_escape_string($mysqli,$_POST['l10_temp1'] ?? '').'\',
		l10_temp2 = \''.mysqli_real_escape_string($mysqli,$_POST['l10_temp2'] ?? '').'\',
		l10_temp3 = \''.mysqli_real_escape_string($mysqli,$_POST['l10_temp3'] ?? '').'\',
		notes = \''.mysqli_real_escape_string($mysqli,$_POST['notes']).'\',
		subtot_notax = \''.mysqli_real_escape_string($mysqli,$_POST['subtot_notax']).'\',
		addtax = \''.mysqli_real_escape_string($mysqli,$_POST['addtax'] ?? '').'\',
		tax = \''.mysqli_real_escape_string($mysqli,$_POST['tax']).'\',
		subtot_aftax = \''.mysqli_real_escape_string($mysqli,$_POST['subtot_aftax']).'\',
		deposit = \''.mysqli_real_escape_string($mysqli,$_POST['deposit']).'\',
		totalowed = \''.mysqli_real_escape_string($mysqli,$_POST['totalowed']).'\',
		totalpaid = \''.mysqli_real_escape_string($mysqli,$_POST['totalpaid']).'\',
		temp11 = \''.mysqli_real_escape_string($mysqli,$_POST['temp11'] ?? '').'\',
		temp12 = \''.mysqli_real_escape_string($mysqli,$_POST['temp12'] ?? '').'\',
		temp13 = \''.mysqli_real_escape_string($mysqli,$_POST['temp13'] ?? '').'\',
		temp14 = \''.mysqli_real_escape_string($mysqli,$_POST['temp14'] ?? '').'\'';
    if ( $do == 'save' ) {
        $query .= ';';
    } else if ( $do == 'update' ) {
        $query .= ' WHERE id='.mysqli_real_escape_string($mysqli,$_POST['id']);
    }
    dbi_execute ($query) or die(mysqli_error());
    mysqli_close($mysqli);
    if ( isset($_GET['do2']) && $_GET['do2'] == "print" )
        header('Location:'.$_SERVER['PHP_SELF'].'?id='.$_GET['id'].'&do=print&print=now');
    else
        show_invoices();
}
?>
</body>
</html>