<?php
// Checked for PHP5.6 / 8.x compatibility
$active = array();
$invord = array();
$ordhold = array();
$invdate = array();
$contactname = array();
$contactemail = array();
$usegoldmine = array();
$hasareciepient = array();
$mysig = array();
$lcontactid = array();
$companyname = array();
$emailinvoice = array();
$rinvoicemethod = array();
$operakey = array();
$delnote = array();
$methoddesc = array();
$methoddescnotes = array();
$useremail = array();
$notcollected = array();
$notdeliveryconfirmationon = array();

include("../../operainfo/getq.php");
$hostcompanyid = safetext2(isset($_GET['hostcompanyid']) ? $_GET['hostcompanyid'] : '');
?>

<script type="text/javascript">

function checkhold(vui,rid) {
document.getElementById("here").innerHTML="ddddddddddd";

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
xmlhttp.open("GET","HoldInvoice.php?vui="+vui+"&holdinvoice="+rid+"&user=",true);
xmlhttp.send();


xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("here").innerHTML=xmlhttp.responseText;
    }
  }

	
	
}

</script>

<script type="text/javascript">

function gethostoptions() {

document.getElementById('hostoptions').innerHTML='test';
xmlhttp=new XMLHttpRequest();
 var link ="../functions/selecthostcompany.php<?php echo $x; ?>";
 document.getElementById("hostoptions").innerHTML=link;
xmlhttp.open("GET",link,true);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("hostoptions").innerHTML=xmlhttp.responseText;
    }
  }
}
 
</script>

<script type="text/javascript"> 
 
function sethost(hostid) {
 var link ="index.php<?php echo $x; ?>&hostcompanyid="+hostid;
 window.location.href = link;
}


</script>



<?php

if ($hostcompanyid < 1 ) {
?>
 <script type="text/javascript"> 
 function sethost(hostid) {
	 window.location='index.php<?php echo $x; ?>&hostcompanyid='+hostid;
 }
 </script>
<?php
	

$msg = "<center><h3>Please Select Host Company to review invoices to be sent</h3>";
$msg .= "<table width=50%>";
$s = "SELECT
global_companys.id as id,
global_companys.fullname as fullname
FROM global_companys, pw_companys
WHERE pw_companys.company_id = global_companys.id
AND pw_companys.vui = ?
AND active = '0'
ORDER BY name";
$stmt = pdoquery($s, array($vui));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
	$hostid = $row['id'];
	$msg .= "<TR bgcolor=\"#92adc8\" onMouseOver=\"this.bgColor='#d4deea';\" onMouseOut=\"this.bgColor='#92adc8';\">";
	$msg .= "<td><a onclick=\"sethost('$hostid')\">$global_company_logo48[$hostid]</a></td><td><h1><button onclick=\"sethost('$hostid')\">".ucwords($row['fullname'])."</button></h1></td></tR>";
}
$msg .= "</table>";
echo $msg;
	
} else {

$operadocpath = '';
$s = "SELECT operadocs FROM global_companys WHERE id = ?";
$stmt = pdoquery($s, array($hostcompanyid));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
	$operadocpath = $row['operadocs'];
}

$hasreadr = '';
$s = "SELECT ISO_quality_manual_files.docid as docid, ISO_quality_manual_user_read.last_read as lr
FROM ISO_quality_manual_files, ISO_quality_manual_user_read
WHERE ISO_quality_manual_files.description LIKE ?
AND ISO_quality_manual_files.archived = ''
AND ISO_quality_manual_user_read.docid = ISO_quality_manual_files.docid
AND ISO_quality_manual_user_read.userid = ?";
$stmt = pdoquery($s, array('%VM3COP20.061%', $vui));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
	$hasreadr = 1;
}

print "<center><h1>";
if ($hostcompanyid != '') {
	print "".$global_company_logo48[$hostcompanyid]." ".$global_company_name[$hostcompanyid]." ";
}
print "Invoices to be Emailed List</h1>";

print "
See VM3COP20.061 Sending Invoices Via E-Mail<br>
Please go through the list below and email invoice that are present. Please be aware that some may need to be sent manually, this is because sometimes the invoices are not being received so we send them manually through Googlemail it makes sure they are received. The invoices you have in paper form that are not on the list, contact and get the email address. Then send the invoice manually or post. Some people do not have an email address for this these need to be posted.<br><br>
<h3>Ensure the Top line of Intrastats is NOT showing an update is in progress</h3><br>
";

if ($hasreadr == '') {
	print "<h3>Please Read VM3COP20.061 in the Document index<br> Then refresh this page</h3>";
} else {

	$s = "SELECT * FROM pw_companys WHERE vui = ?";
	$stmt = pdoquery($s, array($vui));
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$coid = $row['company_id'];
		$useremail[$coid] = $row['useremail'];
	}

	$coupleweeksago = date("U") - (604800 * 2);

	$invsearch = " (1=2 ";
	$s = "SELECT subject FROM viamedquote_followups WHERE followupgroup = 'emailinvoice' AND generatedon > ?";
	$stmt = pdoquery($s, array($coupleweeksago));
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$invuse = $row['subject'];
		$active[$invuse] = 1;
		$invsearch .= " OR INVOICE_NU = '$invuse'";
	}
	$invsearch .= " ) ";

	$s = "SELECT INVOICE_NU, SALES_ORDE FROM ORDERSR WHERE $invsearch";
	$stmt = pdoquery($s, array());
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$invuse = $row['INVOICE_NU'];
		$invord[$invuse] = $row['SALES_ORDE'];
	}

	$s = "SELECT ordernumber FROM ordernumbertrack WHERE holdinvoice = '-1'";
	$stmt = pdoquery($s, array());
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$useord = $row['ordernumber'];
		$ordhold[$useord] = -1;
	}

	$s = "SELECT Reference, universaltime FROM VST_invoices WHERE universaltime > ? AND Type = 'Invoice' AND Value > '0' AND Paid_Indic = ''";
	$stmt = pdoquery($s, array($coupleweeksago));
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$invuse = $row['Reference'];
		$invdate[$invuse] = date("d M Y", $row['universaltime']);
	}

	$s = "SELECT Reference, universaltime FROM invoices WHERE universaltime > ? AND Type = 'Invoice' AND Value > '0' AND Paid_Indic = ''";
	$stmt = pdoquery($s, array($coupleweeksago));
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$invuse = $row['Reference'];
		$invdate[$invuse] = date("d M Y", $row['universaltime']);
	}

	$s = "SELECT id, COMPANY_ID, CONTACT, INETADDR, emailinvoicegoldmine FROM viamedquotecontact WHERE emailinvoice = 'on' AND hideme = ''";
	$stmt = pdoquery($s, array());
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$companyid = $row['COMPANY_ID'];
		$contactid = $row['id'];
		$lcontactid[$companyid] = $row['id'];
		$contactname[$companyid] = $row['CONTACT']." ".(isset($contactname[$contactid]) ? $contactname[$contactid] : '');
		$contactemail[$companyid] = isset($contactemail[$companyid]) ? $contactemail[$companyid]." ".$row['INETADDR'] : $row['INETADDR'];
		$usegoldmine[$companyid] = $row['emailinvoicegoldmine'];
	}

	$s = "SELECT COMPANY_ID FROM viamedquotecontact WHERE emailinvoice <> '' AND INETADDR <> '' AND hideme = '' GROUP BY INETADDR";
	$stmt = pdoquery($s, array());
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$companyid = $row['COMPANY_ID'];
		$hasareciepient[$companyid] = 1;
	}

	$s = "SELECT hostcompanyid, signiture FROM pw_emailsignitures WHERE hostcompanyid = ? AND employeeid = ?";
	$stmt = pdoquery($s, array($hostcompanyid, $vui));
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$hhost = $row['hostcompanyid'];
		$mysig[$hhost] = $row['signiture'];
	}

	$s = "SELECT ID, COMPANY, emailinvoices, Invoice_Method, KEY5, delnotification FROM viamedquoteaddress WHERE hideme = ''";
	$stmt = pdoquery($s, array());
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$companyid = $row['ID'];
		$companyname[$companyid] = $row['COMPANY'];
		$emailinvoice[$companyid] = $row['emailinvoices'];
		$operakey[$companyid] = $row['KEY5'];
		$rinvoicemethod[$companyid] = $row['Invoice_Method'];
		$op = $row['KEY5'];
		$companyidfromopera[$op] = $row['ID'];
		$delnote[$companyid] = $row['delnotification'];
	}

	$s = "SELECT id, method FROM viamedquoteaddress_invoicemethod";
	$stmt = pdoquery($s, array());
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$methodid = $row['id'];
		$methoddesc[$methodid] = $row['method'];
	}

	print "<table><tr><td>KEY</td></tr>";
	print "<tr><td bgcolor=".$pastelred.">No Invoice PDF in the System</td></tr>";
	print "<tr><td bgcolor=".$pastelgreen.">PDF in the System Ready to send</td></tr>";
	print "<tr><td bgcolor=".$pastelyellow.">Send Email from Goldmine with Invoices attached</td></tr>";
	print "<tr><td bgcolor='#92adc8'>Invoice to be Posted</td></tr>";
	print "<tr><td bgcolor=".$pastelbrown.">Uses a Special system for Invoices See account notes</td></tr>";
	print "</table><br>";

	print "<div id='here'></div><table width=90% class=n3 border=1><tr><td>*</td><td>Host</td><td>INV Date</td>
<td>INV</td><td>ORD</td><td>Contact</td><td>Company</td>";
	print "<td>Shipper collected</td>";
	print "<td>Delivery Notification Sent</td>";
	print "<td>Email</td><td>Send</td><td>Remove</td><td>Not Sent</td><td>xml</td></tr>";

	// --- Delivery status lookups ---
	$s = "SELECT ordernumber FROM viamedquote_orders_deliverys WHERE giventoshipperon = '0' OR deliveryconfirmationon = '0'";
	$stmt = pdoquery($s, array());
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$orderid = $row['ordernumber'];
		$notcollected[$orderid] = 1;
		$notdeliveryconfirmationon[$orderid] = 1;
	}

	// --- Main invoice query ---
	$hostsearch = '';
	$hostsearch_params = array();
	if ($hostcompanyid != '') {
		$hostsearch = " AND viamedquote_orders.hostcompany = ? ";
		$hostsearch_params[] = $hostcompanyid;
	}

	$s = "SELECT
viamedquote_orders.id as orderid,
viamedquote_orders.company_id as company_id,
viamedquote_orders.contact_id as contact_id,
viamedquote_orders.hostcompany as hostcompanyid,
viamedquote_orders_invoices.invoicecommitedon as invoicecommitedon,
viamedquote_orders.holdinvoices as holdinvoices,
viamedquote_orders_invoices.invoiceref as invoiceref,
viamedquote_orders.customer_ref,
viamedquote_orders.customer_ref_extra
FROM viamedquote_orders_invoices, viamedquote_orders
WHERE viamedquote_orders.id = viamedquote_orders_invoices.orderid
AND viamedquote_orders_invoices.invoicesenttocustomeron = '0'
AND viamedquote_orders_invoices.invoicetotal > '0'
AND viamedquote_orders_invoices.invoicecommitedon > ''
AND viamedquote_orders_invoices.invoicecommitedon > '0'
$hostsearch
ORDER BY viamedquote_orders_invoices.invoicecommitedon";

	$stmt = pdoquery($s, $hostsearch_params);
	while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
		$orderid       = $row['orderid'];
		$contactid     = $row['contact_id'];
		$companyid     = $row['company_id'];
		$rowhostid     = $row['hostcompanyid'];
		$fromemailis   = isset($useremail[$rowhostid]) ? $useremail[$rowhostid] : '';
		$prndate       = date("d M Y", $row['invoicecommitedon']);
		$filename      = $operadocpath.$row['invoiceref'].".pdf";
		$holdinvoices  = $row['holdinvoices'];
		$displayname   = $row['invoiceref'].".pdf";
		$invoiceref    = $row['invoiceref'];
		$customer_ref  = $row['customer_ref'];
		$customer_ref_extra = $row['customer_ref_extra'];

		$isdelnote     = isset($delnote[$companyid]) ? $delnote[$companyid] : 0;
		$iscollected   = isset($notcollected[$orderid]) ? $notcollected[$orderid] : 0;

		if ($isdelnote == 0 && $iscollected != 1) {

			if (file_exists($filename)) {
				$usecolor = $pastelgreen;

				if (isset($emailinvoice[$companyid]) && $emailinvoice[$companyid] == 'No') {
					print "<tr bgcolor=".$pastelblue."><td>";
				} elseif (isset($emailinvoice[$companyid]) && $emailinvoice[$companyid] == 'Own') {
					print "<tr bgcolor=".$pastelbrown."><td>";
				} else {
					print "<tr bgcolor=".$usecolor."><td>";
				}
				print "";
			} else {
				$usecolor = $pastelred;
				print "<tr bgcolor=".$usecolor."><td>No File";
			}

			print "</td>";
			print "<td>".$global_company_logo24[$rowhostid]."</td>";
			print "<td></td><td>".$prndate."</td><td>";
			print "<a href=\"/intranet/databases/download_documents/viewoperadoc.php".$x."&operadoc=".$invoiceref."\" target=\"_Viewinvoice\">";
			print operadoclinks($x, $invoiceref, '').$invoiceref."</a></td>";

			print "<td>".$orderid."</td>";

			print "<td><a href=\"../crm/quotationrequest4.php".$x."&id=".$contactid."&cid=".$companyid."\">";
			$extrames = '';
			if (!isset($contactemail[$companyid]) || $contactemail[$companyid] == '') {
				print "No Email for Invoices contact set ";
			}
			print (isset($contactname[$companyid]) ? $contactname[$companyid] : '')."<br>".(isset($contactemail[$companyid]) ? $contactemail[$companyid] : '')." </a>";
			print "</td>";

			print "<td>".linkcrm($x, $companyid, '');
			print (isset($companyname[$companyid]) ? $companyname[$companyid] : getcompanyname($companyid))."</td>";

			print "<td>";
			if ($iscollected != 1) {
				print "<img src=\"/intranet/images/big-tick.png\" width=16 height=16>";
			} else {
				print "<img src=\"/intranet/images/small_cross.png\" width=16 height=16>";
			}
			print "</td>";

			print "<td>";
			$isdelconf = isset($notdeliveryconfirmationon[$orderid]) ? $notdeliveryconfirmationon[$orderid] : 0;
			if ($isdelconf != 1) {
				print "<img src=\"/intranet/images/big-tick.png\" width=16 height=16>";
			} else {
				print "<img src=\"/intranet/images/small_cross.png\" width=16 height=16>";
			}
			print "</td>";

			$coemail = isset($contactemail[$companyid]) ? $contactemail[$companyid] : '';
			if ($coemail != '' && $extrames == '') {
				print "<td>";
				if (isset($emailinvoice[$companyid]) && $emailinvoice[$companyid] == 'No') {
					print "Post Invoice";
				} else {
					$rto = '';
					if ($rowhostid == 1) { $rto = "accounts@viamed.co.uk"; }
					if ($rowhostid == 2) { $rto = "accounts@vandagraph.co.uk"; }
					if ($rowhostid == 3) { $rto = "accounts@vandagraphst.com"; }

					$subject = $global_company_name[$rowhostid]." Invoice ".$invoiceref." Reference ".$customer_ref.$customer_ref_extra;

					$sentto = $coemail;
					$gmailbody  = "Please find attached ".urlencode($global_company_name[$rowhostid])." Invoice(s) ".$displayname." %0D%0A %0D%0A";
					$gmailbody .= "Should you have any queries please do not hesitate to contact us at%0D%0A".urlencode($rto)."%0D%0A%0D%0A";
					$gmailbody .= "Kind Regards%0D%0A%0D%0A".urlencode(ucwords($localname))."%0D%0A".urlencode(isset($global_company_name[$rowhostid]) ? $global_company_name[$rowhostid] : '')."%0D%0A".urlencode($fromemailis);
					$mailtolink = "mailto:".urlencode($sentto)."?from=".urlencode($fromemailis)."&subject=".urlencode($subject)."&body=%0D%0A".$gmailbody;
					?>
<a href="<?php echo $mailtolink; ?>" title='Send Email' target="email">
    Email<br>Send Via Gmail
</a><br>
					<?php
					echo "<br><a href=\"../openai/chatapi.php".$x."&hostcompanyid=".$rowhostid."&sendto=".urlencode($coemail)."&contactid=".$contactid."&companyid=".$companyid."&subject=".urlencode($subject)."&message=".urlencode($gmailbody)."\" target='AIText'>TidyEmail</a>";
					$gmailbody = '';
				}
				print "</td>";

				print "<td>";
				if ($hostcompanyid == 0 || $hostcompanyid == '') {
					print "Error ? Host is Zero";
				}
				if (!(isset($hasareciepient[$companyid]) && $hasareciepient[$companyid] == 1) && $coemail == '') {
					print "No Contact set to recieve Email Invoices";
				}
				print "</td>";
			} else {
				print "<td></td><td></td>";
			}

			if ($holdinvoices != 1) {
				print "<td><a href=\"sendhminvoice.php".$x."&hostcompanyid=".$rowhostid."&invoiceref=".$invoiceref."\">Invoice Sent</a></td>";
				print "<td><a href=\"sendhminvoice.php".$x."&hostcompanyid=".$rowhostid."&invoiceref=".$invoiceref."&not=1\">Invoice NOT Sent</a></td>";
			} else {
				print "<td colspan=2>INVOICES SET TO HOLD</td>";
			}

			print "<td><a href=\"invoice_xml.php".$x."&invoice=".$invoiceref."\">Export XML</a></td>";
			print "</tr>";
		}
	}

	print "</table>";
}

}
?>
