<?php
/* $Id: PO_AuthoriseMyOrders.php — Modernized UI with Ant Design styling */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('Purchase Order Authorisation');
include('includes/newheader.php');

$userid = $_SESSION['UserID'];

$EmailSQL1="SELECT realname FROM www_users WHERE userid = '" . $userid ."'";
$EmailResult1 = DB_query($EmailSQL1);
$myEmail1=DB_fetch_array($EmailResult1);
$realname = $myEmail1['realname'];

$timenow = time();
$modifieddatetime = date("Y-m-d h:i:sa", $timenow);
$fijitime = date("d-m-Y h:i:sa", $timenow);

$EmailSQL="SELECT email FROM www_users WHERE userid='".$_SESSION['UserID']."'";
$EmailResult=DB_query($EmailSQL);
$EmailRow=DB_fetch_array($EmailResult);

/* =====================================================================
 * POST PROCESSING — COMPLETELY UNCHANGED FROM ORIGINAL
 * Same variable names, same SQL, same email recipients, same logic
 * ===================================================================== */
if (isset($_POST['UpdateAll'])) {
	foreach ($_POST as $key => $value) {
		if (mb_substr($key,0,6)=='Status') {

				$OrderNo=mb_substr($key,6);
			$Status=$_POST['Status'.$OrderNo];

if ($Status == "Authorised") {

				$userid = $_SESSION['UserID'];


$EmailSQL1="SELECT realname

					FROM www_users

					WHERE userid = '" . $userid ."'";

		$EmailResult1 = DB_query($EmailSQL1);

			$myEmail1=DB_fetch_array($EmailResult1);



			$realname = $myEmail1['realname'];

			$Comment=date($_SESSION['DefaultDateFormat']).' - '._('Fully Authorised by').' <a href="mailto:' . $EmailRow['email'].'">' . $_SESSION['UserID'] . '</a><br />' . html_entity_decode($_POST['comment'],ENT_QUOTES,'UTF-8');
			$sql="UPDATE purchorders
					SET status='".$Status."',
						stat_comment='".$Comment."',
						allowprint=1,
						authorised_by ='".$realname."'
					WHERE orderno='". $OrderNo."'";
			$result=DB_query($sql);




				$SQL = "SELECT department,initiator



			FROM purchorders

			WHERE orderno ='" . $OrderNo. "'

			";



			$result = DB_query($SQL);



			$myrowuser = DB_fetch_array($result) ;

			$department = $myrowuser['department'];

			$initiator = $myrowuser['initiator'];

				$EmailSQL="SELECT email

					FROM www_users

					WHERE realname = '" . $initiator."'

						";

		$EmailResult = DB_query($EmailSQL);

			$myEmail=DB_fetch_array($EmailResult);



			$initiatoremail = $myEmail['email'];





					$ravinesh ='rdeo@wormaldfj.com';

	$sharukh ='msharukh@wormaldfj.com';

	$sachin = 'technical@wormaldfj.com';

	$shiv='shiv.c@wormaldfj.com';

	$joseph='payablewest@wormaldfj.com';
	$vani = 'vrokobaro@wormaldfj.com';

$riga = 'rtaito@wormaldfj.com';
			$ilimo= 'ilimo@wormaldfj.com';



			$EmailSQL1="SELECT email

					FROM www_users, department

					WHERE department.authoriser = www_users.userid

						AND department.departmentid = '" . $department ."'";

		$EmailResult1 = DB_query($EmailSQL1);

			$myEmail1=DB_fetch_array($EmailResult1);



			$authorisersemail = $myEmail1['email'];



			$supname =$myrow['suppname'];

			$ConfirmationText = _('This purchase order  - '.$OrderNo.'-'.$supname.' has been authorized by CFO/CEO: '.$realname.' at '.$fijitime );
	        $ConfirmationText1 = _('This purchase order  - '.$OrderNo.'-'.$supname.' has been authorized by CFO/CEO: '.$realname.' at '.$fijitime );


			$EmailSubject = $OrderNo._('Purchase order Fully Authorised');



		


	
	       // mail($ravinesh,$EmailSubject,$ConfirmationText);
			 mail($sharukh,$EmailSubject,$ConfirmationText);

			 //mail($sachin,$EmailSubject,$ConfirmationText);

			 mail($initiatoremail,$EmailSubject,$ConfirmationText1);

	     	mail($authorisersemail,$EmailSubject,$ConfirmationText);

	 //mail($riga,$EmailSubject,$ConfirmationText);



	

	}

elseif ($Status == "DepartmentalAuthorised") {

					$userid = $_SESSION['UserID'];


$EmailSQL1="SELECT realname

					FROM www_users

					WHERE userid = '" . $userid ."'";

		$EmailResult1 = DB_query($EmailSQL1);

			$myEmail1=DB_fetch_array($EmailResult1);



			$realname = $myEmail1['realname'];


			$Comment=date($_SESSION['DefaultDateFormat']).' - '._('Departmental Authorised by').' <a href="mailto:' . $EmailRow['email'].'">' . $_SESSION['UserID'] . '</a><br />' . html_entity_decode($_POST['comment'],ENT_QUOTES,'UTF-8');
			$sql="UPDATE purchorders
					SET status='".$Status."',
						stat_comment='".$Comment."',
						depart_authorised_by ='".$realname."'
					WHERE orderno='". $OrderNo."'";
			$result=DB_query($sql);

				$SQL = "SELECT department,initiator



			FROM purchorders

			WHERE orderno ='" . $OrderNo. "'

			";



			$result = DB_query($SQL);



			$myrowuser = DB_fetch_array($result) ;

			$department = $myrowuser['department'];

			$initiator = $myrowuser['initiator'];

				$EmailSQL="SELECT email

					FROM www_users

					WHERE realname = '" . $initiator."'

						";

		$EmailResult = DB_query($EmailSQL);

			$myEmail=DB_fetch_array($EmailResult);



			$initiatoremail = $myEmail['email'];





					$ravinesh ='rdeo@wormaldfj.com';

	$sharukh ='msharukh@wormaldfj.com';
    $rav ='ravneet.c@wormaldfj.com';
	$sachin = 'sachin@ebusinesserp.com';

	$shiv='shiv.c@wormaldfj.com';

	$joseph='payablewest@wormaldfj.com';
	$vani = 'vrokobaro@wormaldfj.com';

$riga = 'rtaito@wormaldfj.com';
			$ilimo= 'ilimo@wormaldfj.com';



			$EmailSQL1="SELECT email

					FROM www_users, department

					WHERE department.authoriser = www_users.userid

						AND department.departmentid = '" . $department ."'";

		$EmailResult1 = DB_query($EmailSQL1);

			$myEmail1=DB_fetch_array($EmailResult1);



			$authorisersemail = $myEmail1['email'];



			$supname =$myrow['suppname'];

			$ConfirmationText = _('This purchase order  - '.$OrderNo.'-'.$supname.' has been authorized by departmental manager: '.$realname.' at '.$fijitime.' Final Approval is now waiting from CFO/GM to complete this PO.' );
	        $ConfirmationText1 = _('This purchase order  - '.$OrderNo.'-'.$supname.' has been authorized by departmental manager: '.$realname.' at '.$fijitime.' Final Approval is now waiting from CFO/GM to complete this PO.' );


			$EmailSubject = $OrderNo._('Purchase order Departmental Authorised');



		

		
		     //   mail($ravinesh,$EmailSubject,$ConfirmationText);
				 mail($sharukh,$EmailSubject,$ConfirmationText);
				 mail($rav,$EmailSubject,$ConfirmationText);
				// mail($sachin,$EmailSubject,$ConfirmationText);

				 mail($initiatoremail,$EmailSubject,$ConfirmationText1);

	     	mail($authorisersemail,$EmailSubject,$ConfirmationText);

	// mail($riga,$EmailSubject,$ConfirmationText);



			

	}
		elseif ($Status == "Rejected" ||$Status == "Cancelled" ){


				$Comment=date($_SESSION['DefaultDateFormat']).' - '._('Rejected/Cancelled by').' <a href="mailto:' . $EmailRow['email'].'">' . $_SESSION['UserID'] . '</a><br />' . html_entity_decode($_POST['comment'],ENT_QUOTES,'UTF-8');
			$sql="UPDATE purchorders
					SET status='".$Status."',
						stat_comment='".$Comment."'

					WHERE orderno='". $OrderNo."'";
			$result=DB_query($sql);


				$SQL = "SELECT department,initiator



			FROM purchorders

			WHERE orderno ='" . $OrderNo. "'

			";



			$result = DB_query($SQL);



			$myrowuser = DB_fetch_array($result) ;

			$department = $myrowuser['department'];

			$initiator = $myrowuser['initiator'];

				$EmailSQL="SELECT email

					FROM www_users

					WHERE realname = '" . $initiator."'

						";

		$EmailResult = DB_query($EmailSQL);

			$myEmail=DB_fetch_array($EmailResult);



			$initiatoremail = $myEmail['email'];





					$ravinesh ='rdeo@wormaldfj.com';

	$sharukh ='msharukh@wormaldfj.com';
	$rav ='ravneet.c@wormaldfj.com';
	$sachin = 'technical@wormaldfj.com';

	$shiv='shiv.c@wormaldfj.com';

	$joseph='payablewest@wormaldfj.com';
	$vani = 'vrokobaro@wormaldfj.com';


			$ilimo= 'ilimo@wormaldfj.com';



			$EmailSQL1="SELECT email

					FROM www_users, department

					WHERE department.authoriser = www_users.userid

						AND department.departmentid = '" . $department ."'";

		$EmailResult1 = DB_query($EmailSQL1);

			$myEmail1=DB_fetch_array($EmailResult1);



			$authorisersemail = $myEmail1['email'];



			

			$ConfirmationText = _('This purchase order  - '.$OrderNo.'-'.$supname.' has been rejected/canceled by manager: '.$realname.' at '.$fijitime );
	        $ConfirmationText1 = _('This purchase order  - '.$OrderNo.'-'.$supname.' has been rejected/canceled by manager: '.$realname.' at '.$fijitime);


			$EmailSubject = $OrderNo._('-Purchase order Rejected/Cancelled');



		

	
		       // mail($ravinesh,$EmailSubject,$ConfirmationText);
				 mail($sharukh,$EmailSubject,$ConfirmationText);
                 mail($rav,$EmailSubject,$ConfirmationText);
				// mail($sachin,$EmailSubject,$ConfirmationText);

				 mail($initiatoremail,$EmailSubject,$ConfirmationText1);

	     	mail($authorisersemail,$EmailSubject,$ConfirmationText);



			

	
				
			}



		}
	}
}

/* =====================================================================
 * DETERMINE SQL BASED ON USER — Same WHERE conditions as original
 * ===================================================================== */

$isAdmin = ($userid == 'ravinesh' || $userid == 'riga' || $userid == 'admin' || $userid == 'sharukh' || $userid == 'ravneet' || $userid == 'rajnal');
$showGLName = false; // only admin block has the oldglcode table JOIN

if ($isAdmin) {
	$showGLName = true;
	$sql="SELECT purchorders.*,
			department.departmentname,
			suppliers.suppname,
			suppliers.currcode,
			www_users.realname,
			www_users.email,
			currencies.decimalplaces AS currdecimalplaces
		FROM purchorders INNER JOIN suppliers
			ON suppliers.supplierid=purchorders.supplierno
			INNER JOIN department
			ON purchorders.department = department.departmentid
		INNER JOIN currencies
			ON suppliers.currcode=currencies.currabrev
		INNER JOIN www_users
			ON www_users.userid=department.authoriser
	WHERE status='Pending'   
	OR status = 'DepartmentalAuthorised'
	Order by purchorders.orderno DESC";

} elseif ($userid == 'jpenjueli' || $userid == '11113') {
	$sql="SELECT purchorders.*,
			department.departmentname,
			suppliers.suppname,
			suppliers.currcode,
			www_users.realname,
			www_users.email,
			currencies.decimalplaces AS currdecimalplaces
		FROM purchorders INNER JOIN suppliers
			ON suppliers.supplierid=purchorders.supplierno
			INNER JOIN department
			ON purchorders.department = department.departmentid
		INNER JOIN currencies
			ON suppliers.currcode=currencies.currabrev
		INNER JOIN www_users
			ON www_users.userid=department.authoriser
	WHERE purchorders.department = 1
	AND status='Pending'   
	OR status = 'DepartmentalAuthorised'";

} elseif ($userid == 'losa') {
	$sql="SELECT purchorders.*,
			department.departmentname,
			suppliers.suppname,
			suppliers.currcode,
			www_users.realname,
			www_users.email,
			currencies.decimalplaces AS currdecimalplaces
		FROM purchorders INNER JOIN suppliers
			ON suppliers.supplierid=purchorders.supplierno
			INNER JOIN department
			ON purchorders.department = department.departmentid
		INNER JOIN currencies
			ON suppliers.currcode=currencies.currabrev
		INNER JOIN www_users
			ON www_users.userid=department.authoriser
	WHERE status='Pending'   
	OR status = 'DepartmentalAuthorised'
	AND purchorders.department = 6";

} elseif ($userid == 'crispus') {
	$sql="SELECT purchorders.*,
			department.departmentname,
			suppliers.suppname,
			suppliers.currcode,
			www_users.realname,
			www_users.email,
			currencies.decimalplaces AS currdecimalplaces
		FROM purchorders INNER JOIN suppliers
			ON suppliers.supplierid=purchorders.supplierno
			INNER JOIN department
			ON purchorders.department = department.departmentid
		INNER JOIN currencies
			ON suppliers.currcode=currencies.currabrev
		INNER JOIN www_users
			ON www_users.userid=department.authoriser
	WHERE (status='Pending'   
	OR status = 'DepartmentalAuthorised')
	AND (purchorders.department = 9
   	OR purchorders.department = 11)";

} elseif ($userid == 'malka') {
	$sql="SELECT purchorders.*,
			department.departmentname,
			suppliers.suppname,
			suppliers.currcode,
			www_users.realname,
			www_users.email,
			currencies.decimalplaces AS currdecimalplaces
		FROM purchorders INNER JOIN suppliers
			ON suppliers.supplierid=purchorders.supplierno
			INNER JOIN department
			ON purchorders.department = department.departmentid
		INNER JOIN currencies
			ON suppliers.currcode=currencies.currabrev
		INNER JOIN www_users
			ON www_users.userid=department.authoriser
	WHERE (status='Pending'   
	OR status = 'DepartmentalAuthorised')
	AND (purchorders.department = '22'
	OR purchorders.department = '23')";

} elseif ($userid == 'douglas' || $userid == 'george') {
	$sql="SELECT purchorders.*,
			department.departmentname,
			suppliers.suppname,
			suppliers.currcode,
			www_users.realname,
			www_users.email,
			currencies.decimalplaces AS currdecimalplaces
		FROM purchorders INNER JOIN suppliers
			ON suppliers.supplierid=purchorders.supplierno
			INNER JOIN department
			ON purchorders.department = department.departmentid
		INNER JOIN currencies
			ON suppliers.currcode=currencies.currabrev
		INNER JOIN www_users
			ON www_users.userid=department.authoriser
	WHERE status='Pending'   
	OR status = 'DepartmentalAuthorised'
	AND purchorders.department = 7";

} elseif ($userid == 'mike') {
	$sql="SELECT purchorders.*,
			department.departmentname,
			suppliers.suppname,
			suppliers.currcode,
			currencies.decimalplaces AS currdecimalplaces
		FROM purchorders INNER JOIN suppliers
			ON suppliers.supplierid=purchorders.supplierno
			INNER JOIN department
			ON purchorders.department = department.departmentid
		INNER JOIN currencies
			ON suppliers.currcode=currencies.currabrev
	WHERE (purchorders.department = '2' 
	OR purchorders.department = '10')
	AND (status='Pending'   
	OR status = 'DepartmentalAuthorised')";

} else {
	$sql = '';
}

/* =====================================================================
 * COLLECT DATA INTO PHP ARRAYS — For clean rendering
 * ===================================================================== */
$orders = array();
$totalPending = 0;
$totalDeptAuth = 0;
$grandTotalValue = 0;

if (!empty($sql)) {
	$result = DB_query($sql);

	while ($myrow = DB_fetch_array($result)) {

		$AuthSQL="SELECT authlevel FROM purchorderauth
					WHERE userid='".$_SESSION['UserID']."'
					AND currabrev='".$myrow['currcode']."'";
		$AuthResult=DB_query($AuthSQL);
		$myauthrow=DB_fetch_array($AuthResult);
		$AuthLevel = isset($myauthrow['authlevel']) ? $myauthrow['authlevel'] : 0;

		$OrderValueSQL="SELECT sum(unitprice*quantityord) as ordervalue
			           	FROM purchorderdetails
				        WHERE orderno='".$myrow['orderno'] . "'";
		$OrderValueResult=DB_query($OrderValueSQL);
		$MyOrderValueRow=DB_fetch_array($OrderValueResult);
		$OrderValue = isset($MyOrderValueRow['ordervalue']) ? $MyOrderValueRow['ordervalue'] : 0;

		/* --- Determine dropdown type (matching original logic exactly) --- */
		$canAuthorise = false;
		$canDeptAuth = false;
		$readOnly = false;

		if ($isAdmin) {
			/* Original admin block: if ($AuthLevel>=$OrderValue) { render } — no else = skip */
			if ($AuthLevel >= $OrderValue) {
				$canAuthorise = true;
			} else {
				continue; // CRITICAL: admin skips orders above their auth level
			}
		} else {
			/* Non-admin: full auth if within level, dept auth or read-only if over */
			if ($OrderValue <= $AuthLevel) {
				$canAuthorise = true;
			} else {
				if ($myrow['status'] == 'DepartmentalAuthorised') {
					$readOnly = true;
				} else {
					$canDeptAuth = true;
				}
			}
		}

		/* --- Get line items --- */
		if ($showGLName) {
			$LineSQL="SELECT purchorderdetails.*,
						department.departmentname,
						stockmaster.description,
						stockmaster.decimalplaces,
						oldglcode.name
					FROM purchorderdetails
					LEFT JOIN stockmaster
					ON stockmaster.stockid=purchorderdetails.itemcode
					LEFT JOIN department
					ON purchorderdetails.department = department.departmentid
					LEFT JOIN oldglcode
					ON purchorderdetails.oldglcode = oldglcode.oldglcode
				WHERE orderno='".$myrow['orderno'] . "'";
		} else {
			$LineSQL="SELECT purchorderdetails.*,
						stockmaster.description,
						stockmaster.decimalplaces
					FROM purchorderdetails
					LEFT JOIN stockmaster
					ON stockmaster.stockid=purchorderdetails.itemcode
				WHERE orderno='".$myrow['orderno'] . "'";
		}
		$LineResult=DB_query($LineSQL);

		$lineItems = array();
		$totaltoauthorize = 0;
		while ($LineRow=DB_fetch_array($LineResult)) {
			$dp = ($LineRow['decimalplaces'] != NULL) ? $LineRow['decimalplaces'] : 2;
			$lineTotal = $LineRow['unitprice'] * $LineRow['quantityord'];
			$totaltoauthorize += $lineTotal;
			$lineItems[] = array(
				'itemdescription' => $LineRow['itemdescription'],
				'oldglcode' => isset($LineRow['oldglcode']) ? $LineRow['oldglcode'] : '',
				'glname' => isset($LineRow['name']) ? $LineRow['name'] : '',
				'quantityord' => locale_number_format($LineRow['quantityord'], $dp),
				'currcode' => $myrow['currcode'],
				'unitprice' => locale_number_format($LineRow['unitprice'], 3),
				'linetotal' => locale_number_format($lineTotal, 3),
				'jobref' => isset($LineRow['jobref']) ? $LineRow['jobref'] : ''
			);
		}

		if ($myrow['status'] == 'Pending') $totalPending++;
		if ($myrow['status'] == 'DepartmentalAuthorised') $totalDeptAuth++;
		$grandTotalValue += $totaltoauthorize;

		$orders[] = array(
			'orderno' => $myrow['orderno'],
			'suppname' => $myrow['suppname'],
			'orddate' => ConvertSQLDate($myrow['orddate']),
			'initiator' => $myrow['initiator'],
			'deliverydate' => ConvertSQLDate($myrow['deliverydate']),
			'departmentname' => $myrow['departmentname'],
			'status' => $myrow['status'],
			'currcode' => $myrow['currcode'],
			'stat_comment' => isset($myrow['stat_comment']) ? $myrow['stat_comment'] : '',
			'totalformatted' => locale_number_format($totaltoauthorize, 2),
			'canAuthorise' => $canAuthorise,
			'canDeptAuth' => $canDeptAuth,
			'readOnly' => $readOnly,
			'lines' => $lineItems
		);
	}
}

$orderCount = count($orders);
?>

<!-- ============================================================
     MODERN UI — Ant Design Style / Teal Brand / Poppins Font
     ============================================================ -->
<style>
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap');

:root {
	--po-primary: #2AABB3;
	--po-dark: #1E8F96;
	--po-darker: #187278;
	--po-light: #E6F7F8;
	--po-success: #52C41A;
	--po-warning: #FAAD14;
	--po-danger: #FF4D4F;
	--po-info: #1890FF;
	--po-border: #E5E7EB;
	--po-text: #1F2937;
	--po-muted: #6B7280;
	--po-bg: #F8FAFB;
	--po-white: #FFFFFF;
	--po-shadow: 0 2px 8px rgba(0,0,0,0.06);
	--po-shadow-lg: 0 4px 16px rgba(0,0,0,0.10);
	--po-radius: 8px;
}

.po-wrap {
	font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
	max-width: 1400px;
	margin: 0 auto;
	padding: 0 20px 40px;
	color: var(--po-text);
}
.po-wrap *, .po-wrap *::before, .po-wrap *::after { box-sizing: border-box; }

/* ── Banner ── */
.po-banner {
	background: linear-gradient(135deg, var(--po-primary) 0%, var(--po-darker) 100%);
	border-radius: var(--po-radius);
	padding: 26px 30px;
	margin-bottom: 22px;
	color: #fff;
	display: flex;
	justify-content: space-between;
	align-items: center;
	flex-wrap: wrap;
	gap: 14px;
}
.po-banner h1 { font-size: 21px; font-weight: 600; margin: 0; display: flex; align-items: center; gap: 10px; color: #fff; }
.po-banner h1 i { font-size: 22px; }
.po-banner .crumb { font-size: 12px; opacity: .85; margin-top: 3px; }
.po-banner .crumb a { color: rgba(255,255,255,.9); text-decoration: none; }
.po-banner .crumb a:hover { text-decoration: underline; }
.po-banner-r { display: flex; align-items: center; gap: 10px; }
.po-pill { background: rgba(255,255,255,.2); border-radius: 18px; padding: 5px 14px; font-size: 12px; font-weight: 500; color: #fff; }
.po-pill-dim { background: rgba(255,255,255,.13); }

/* ── KPI Cards ── */
.po-kpi { display: grid; grid-template-columns: repeat(4,1fr); gap: 14px; margin-bottom: 22px; }
@media(max-width:900px){ .po-kpi{grid-template-columns:repeat(2,1fr);} }
@media(max-width:500px){ .po-kpi{grid-template-columns:1fr;} }

.kpi-card {
	background: var(--po-white);
	border-radius: var(--po-radius);
	padding: 18px;
	border-left: 4px solid var(--po-primary);
	box-shadow: var(--po-shadow);
	display: flex; align-items: center; gap: 14px;
	transition: transform .2s, box-shadow .2s;
}
.kpi-card:hover { transform: translateY(-2px); box-shadow: var(--po-shadow-lg); }
.kpi-card.warn  { border-left-color: var(--po-warning); }
.kpi-card.ok    { border-left-color: var(--po-success); }
.kpi-card.inf   { border-left-color: var(--po-info); }

.kpi-ico {
	width: 46px; height: 46px; border-radius: 10px;
	display: flex; align-items: center; justify-content: center;
	font-size: 19px; flex-shrink: 0;
}
.kpi-ico.c1 { background: var(--po-light); color: var(--po-primary); }
.kpi-ico.c2 { background: #FFF7E6; color: var(--po-warning); }
.kpi-ico.c3 { background: #E6F7FF; color: var(--po-info); }
.kpi-ico.c4 { background: #F6FFED; color: var(--po-success); }
.kpi-val { font-size: 24px; font-weight: 700; line-height: 1.1; }
.kpi-lbl { font-size: 11px; color: var(--po-muted); font-weight: 600; text-transform: uppercase; letter-spacing: .5px; }

/* ── Toolbar ── */
.po-toolbar {
	background: var(--po-white);
	border-radius: var(--po-radius);
	padding: 14px 18px;
	margin-bottom: 18px;
	box-shadow: var(--po-shadow);
	display: flex; align-items: center; gap: 10px; flex-wrap: wrap;
}
.po-search { flex: 1; min-width: 180px; position: relative; }
.po-search input {
	width: 100%; padding: 8px 10px 8px 36px;
	border: 1px solid var(--po-border); border-radius: 6px;
	font-family: inherit; font-size: 13px; outline: none;
	transition: border-color .2s;
}
.po-search input:focus { border-color: var(--po-primary); }
.po-search i { position: absolute; left: 11px; top: 50%; transform: translateY(-50%); color: var(--po-muted); font-size: 13px; }

.po-fbtn {
	padding: 7px 14px; border: 1px solid var(--po-border); border-radius: 6px;
	background: var(--po-white); color: var(--po-text); font-family: inherit; font-size: 12px;
	cursor: pointer; transition: all .2s; font-weight: 500;
}
.po-fbtn:hover { border-color: var(--po-primary); color: var(--po-primary); }
.po-fbtn.on { background: var(--po-primary); color: #fff; border-color: var(--po-primary); }

.po-xbtn {
	padding: 5px 12px; border: 1px solid var(--po-border); border-radius: 6px;
	background: var(--po-white); color: var(--po-muted); font-family: inherit; font-size: 11px;
	cursor: pointer; transition: all .2s; display: flex; align-items: center; gap: 5px;
}
.po-xbtn:hover { border-color: var(--po-primary); color: var(--po-primary); }

/* ── Order Cards ── */
.po-list { display: flex; flex-direction: column; gap: 14px; }

.po-card {
	background: var(--po-white);
	border-radius: var(--po-radius);
	box-shadow: var(--po-shadow);
	overflow: hidden;
	border: 1px solid var(--po-border);
	transition: box-shadow .2s;
}
.po-card:hover { box-shadow: var(--po-shadow-lg); }

.po-hdr {
	padding: 14px 18px;
	display: flex; align-items: center; gap: 14px;
	cursor: pointer; flex-wrap: wrap; user-select: none;
	border-bottom: 1px solid transparent;
	transition: background .15s;
}
.po-hdr:hover { background: var(--po-light); }
.po-hdr.open { border-bottom-color: var(--po-border); background: var(--po-light); }

.po-num {
	font-weight: 700; font-size: 14px; color: var(--po-dark);
	min-width: 80px; display: flex; align-items: center; gap: 5px;
}
.po-num i { font-size: 10px; transition: transform .3s; color: var(--po-muted); }
.po-hdr.open .po-num i { transform: rotate(90deg); }
.po-sup { flex: 1; min-width: 130px; font-weight: 500; font-size: 13px; }

.po-meta { display: flex; gap: 16px; flex-wrap: wrap; font-size: 11px; color: var(--po-muted); }
.po-meta span { display: flex; align-items: center; gap: 3px; }
.po-meta i { font-size: 11px; }

.po-val { font-weight: 700; font-size: 14px; min-width: 90px; text-align: right; }

/* Status badges */
.po-badge {
	display: inline-flex; align-items: center; gap: 4px;
	padding: 3px 10px; border-radius: 10px;
	font-size: 10px; font-weight: 600; text-transform: uppercase; letter-spacing: .3px;
	white-space: nowrap;
}
.po-badge.pend  { background: #FFF7E6; color: #D48806; }
.po-badge.dauth { background: #E6F7FF; color: #096DD9; }
.po-badge.auth  { background: #F6FFED; color: #389E0D; }
.po-badge.rej   { background: #FFF1F0; color: #CF1322; }

/* ── Expanded Details ── */
.po-det { display: none; padding: 0; }
.po-det.show { display: block; }

.po-dgrid { display: grid; grid-template-columns: 1fr 260px; }
@media(max-width:768px){ .po-dgrid{grid-template-columns:1fr;} }

.po-lsec { padding: 14px 18px; overflow-x: auto; }
.po-lsec h4 {
	font-size: 12px; font-weight: 600; color: var(--po-muted); margin: 0 0 10px;
	text-transform: uppercase; letter-spacing: .5px;
}
.po-ltbl { width: 100%; border-collapse: collapse; font-size: 12px; min-width: 500px; }
.po-ltbl th {
	background: var(--po-bg); padding: 7px 10px; text-align: left;
	font-weight: 600; font-size: 10px; text-transform: uppercase; letter-spacing: .5px;
	color: var(--po-muted); border-bottom: 2px solid var(--po-border);
}
.po-ltbl td { padding: 7px 10px; border-bottom: 1px solid var(--po-border); }
.po-ltbl tr:last-child td { border-bottom: none; }
.po-ltbl .r { text-align: right; }
.po-ltbl .tot { font-weight: 700; background: var(--po-light); }
.po-ltbl .tot td { border-top: 2px solid var(--po-primary); }

/* Action panel */
.po-apnl {
	padding: 14px 18px; background: var(--po-bg);
	border-left: 1px solid var(--po-border);
	display: flex; flex-direction: column; gap: 10px;
}
@media(max-width:768px){ .po-apnl{border-left:none;border-top:1px solid var(--po-border);} }
.po-apnl h4 {
	font-size: 12px; font-weight: 600; color: var(--po-muted); margin: 0;
	text-transform: uppercase; letter-spacing: .5px;
}
.po-links { display: flex; flex-direction: column; gap: 6px; }
.po-lnk {
	display: flex; align-items: center; gap: 7px;
	padding: 7px 10px; border-radius: 6px; text-decoration: none;
	color: var(--po-dark); font-size: 12px; font-weight: 500;
	border: 1px solid var(--po-border); background: var(--po-white);
	transition: background .15s;
}
.po-lnk:hover { background: var(--po-light); border-color: var(--po-primary); }
.po-lnk i { font-size: 13px; }

/* Select */
.po-selw label {
	font-size: 10px; font-weight: 600; color: var(--po-muted);
	text-transform: uppercase; letter-spacing: .5px; display: block; margin-bottom: 5px;
}
.po-selw select {
	width: 100%; padding: 8px 30px 8px 10px;
	border: 1px solid var(--po-border); border-radius: 6px;
	font-family: inherit; font-size: 12px; font-weight: 500;
	color: var(--po-text); background: var(--po-white);
	cursor: pointer; outline: none; appearance: none; -webkit-appearance: none;
	background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='%236B7280' d='M6 8L1 3h10z'/%3E%3C/svg%3E");
	background-repeat: no-repeat; background-position: right 10px center;
	transition: border-color .2s;
}
.po-selw select:focus { border-color: var(--po-primary); box-shadow: 0 0 0 2px rgba(42,171,179,.15); }
.po-selw select.sel-auth   { border-color: var(--po-success); background-color: #F6FFED; }
.po-selw select.sel-reject  { border-color: var(--po-danger); background-color: #FFF1F0; }
.po-selw select.sel-dept    { border-color: var(--po-info); background-color: #E6F7FF; }

.po-ro {
	padding: 7px 12px; background: #F3F4F6; border-radius: 6px;
	color: var(--po-muted); font-size: 11px; font-weight: 500; text-align: center; line-height: 1.5;
}

/* ── Sticky Submit ── */
.po-submit {
	position: sticky; bottom: 0;
	background: var(--po-white); border-top: 1px solid var(--po-border);
	padding: 14px 18px; margin-top: 22px;
	border-radius: var(--po-radius);
	box-shadow: 0 -2px 10px rgba(0,0,0,.06);
	display: flex; align-items: center; justify-content: space-between; gap: 14px; z-index: 10;
}
.po-submit .info { font-size: 12px; color: var(--po-muted); }
.po-submit .info strong { color: var(--po-text); }
.po-btn {
	padding: 9px 28px;
	background: linear-gradient(135deg, var(--po-primary) 0%, var(--po-dark) 100%);
	color: #fff; border: none; border-radius: 6px;
	font-family: inherit; font-size: 13px; font-weight: 600;
	cursor: pointer; transition: all .2s;
	box-shadow: 0 2px 6px rgba(42,171,179,.3);
}
.po-btn:hover {
	background: linear-gradient(135deg, var(--po-dark) 0%, var(--po-darker) 100%);
	box-shadow: 0 4px 12px rgba(42,171,179,.4); transform: translateY(-1px);
}

/* Changed dot indicator */
.po-changed { position: relative; }
.po-changed::after {
	content: '\25cf'; position: absolute; top: -2px; right: -2px;
	color: var(--po-warning); font-size: 14px; line-height: 1;
}

/* ── Empty state ── */
.po-empty {
	text-align: center; padding: 50px 20px;
	background: var(--po-white); border-radius: var(--po-radius); box-shadow: var(--po-shadow);
}
.po-empty i { font-size: 44px; color: var(--po-border); margin-bottom: 14px; display: block; }
.po-empty h3 { font-size: 17px; font-weight: 600; margin: 0 0 6px; }
.po-empty p { font-size: 13px; color: var(--po-muted); margin: 0; }

/* ── Modal Popup ── */
.po-modal-overlay {
	display: none;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	width: 100vw;
	height: 100vh;
	background: rgba(0,0,0,.5);
	z-index: 99999;
	backdrop-filter: blur(2px);
}
.po-modal-overlay.show { display: block; }

@keyframes poSlideUp { from { opacity: 0; transform: translate(-50%,-50%) scale(.95); } to { opacity: 1; transform: translate(-50%,-50%) scale(1); } }

.po-modal {
	position: fixed;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	width: 50vw;
	height: 50vh;
	min-width: 400px;
	min-height: 320px;
	max-width: 950px;
	max-height: 720px;
	background: #fff;
	border-radius: 10px;
	display: flex;
	flex-direction: column;
	box-shadow: 0 16px 48px rgba(0,0,0,.25), 0 0 0 1px rgba(0,0,0,.05);
	animation: poSlideUp .25s ease;
	overflow: hidden;
	z-index: 100000;
}
@media(max-width:860px){ .po-modal { width: 90vw; height: 65vh; min-width: 300px; } }

.po-modal-hdr {
	display: flex; align-items: center; justify-content: space-between;
	padding: 14px 20px;
	background: linear-gradient(135deg, #2AABB3 0%, #187278 100%);
	color: #fff; flex-shrink: 0;
}
.po-modal-hdr h3 { margin: 0; font-size: 14px; font-weight: 600; display: flex; align-items: center; gap: 8px; color: #fff; }
.po-modal-close {
	width: 30px; height: 30px; border-radius: 50%;
	background: rgba(255,255,255,.2); border: none; color: #fff;
	font-size: 18px; cursor: pointer; display: flex; align-items: center; justify-content: center;
	transition: background .2s; line-height: 1;
}
.po-modal-close:hover { background: rgba(255,255,255,.35); }

.po-modal-body { flex: 1; overflow: hidden; position: relative; }
.po-modal-body iframe {
	width: 100%; height: 100%; border: none; display: block;
	transition: opacity .3s ease;
}
.po-modal-spinner {
	position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%);
	font-size: 13px; color: #6B7280; display: flex; align-items: center; gap: 8px;
}
.po-modal-spinner i { animation: poSpin 1s linear infinite; }
@keyframes poSpin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }

.po-modal-foot {
	padding: 8px 20px; border-top: 1px solid #E5E7EB;
	display: flex; align-items: center; justify-content: space-between;
	background: #FAFBFC; flex-shrink: 0;
}
.po-modal-foot a {
	font-size: 11px; color: #2AABB3; text-decoration: none; font-weight: 500;
	display: flex; align-items: center; gap: 4px;
}
.po-modal-foot a:hover { text-decoration: underline; }
.po-modal-foot .po-modal-foot-hint { font-size: 10px; color: #6B7280; }
</style>

<!-- ============================================================
     HTML RENDERING
     ============================================================ -->
<div class="po-wrap">

	<!-- Banner -->
	<div class="po-banner">
		<div>
			<h1><i class="fa fa-check-circle"></i> Purchase Order Authorisation</h1>
			<div class="crumb">
				<a href="index.php">Home</a> &nbsp;/&nbsp; Purchasing &nbsp;/&nbsp; Authorise Orders
			</div>
		</div>
		<div class="po-banner-r">
			<span class="po-pill"><i class="fa fa-user"></i>&nbsp; <?php echo htmlspecialchars($realname); ?></span>
			<span class="po-pill po-pill-dim"><i class="fa fa-calendar"></i>&nbsp; <?php echo $fijitime; ?></span>
		</div>
	</div>

	<!-- KPI -->
	<div class="po-kpi">
		<div class="kpi-card">
			<div class="kpi-ico c1"><i class="fa fa-file-text-o"></i></div>
			<div><div class="kpi-val"><?php echo $orderCount; ?></div><div class="kpi-lbl">Total Orders</div></div>
		</div>
		<div class="kpi-card warn">
			<div class="kpi-ico c2"><i class="fa fa-clock-o"></i></div>
			<div><div class="kpi-val"><?php echo $totalPending; ?></div><div class="kpi-lbl">Pending</div></div>
		</div>
		<div class="kpi-card inf">
			<div class="kpi-ico c3"><i class="fa fa-building-o"></i></div>
			<div><div class="kpi-val"><?php echo $totalDeptAuth; ?></div><div class="kpi-lbl">Dept. Authorised</div></div>
		</div>
		<div class="kpi-card ok">
			<div class="kpi-ico c4"><i class="fa fa-money"></i></div>
			<div><div class="kpi-val"><?php echo locale_number_format($grandTotalValue, 2); ?></div><div class="kpi-lbl">Total Value</div></div>
		</div>
	</div>

<?php if ($orderCount > 0): ?>

	<!-- Toolbar -->
	<div class="po-toolbar">
		<div class="po-search">
			<i class="fa fa-search"></i>
			<input type="text" id="poSearch" placeholder="Search PO#, supplier, initiator, department..." />
		</div>
		<button type="button" class="po-fbtn on" data-f="all">All (<?php echo $orderCount; ?>)</button>
		<button type="button" class="po-fbtn" data-f="Pending">Pending (<?php echo $totalPending; ?>)</button>
		<button type="button" class="po-fbtn" data-f="DepartmentalAuthorised">Dept Auth (<?php echo $totalDeptAuth; ?>)</button>
		<button type="button" class="po-xbtn" id="xpandBtn"><i class="fa fa-expand"></i> Expand All</button>
	</div>

	<!-- FORM — same action, same field names as original -->
	<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'],ENT_QUOTES,'UTF-8'); ?>" id="poForm">
		<input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />

		<div class="po-list" id="poList">
		<?php foreach ($orders as $idx => $order): ?>
			<?php
				$bc = 'pend';
				if ($order['status'] == 'DepartmentalAuthorised') $bc = 'dauth';
				elseif ($order['status'] == 'Authorised') $bc = 'auth';
				elseif ($order['status'] == 'Rejected' || $order['status'] == 'Cancelled') $bc = 'rej';
			?>
			<div class="po-card"
				 data-status="<?php echo htmlspecialchars($order['status']); ?>"
				 data-search="<?php echo htmlspecialchars(strtolower($order['orderno'].' '.$order['suppname'].' '.$order['initiator'].' '.$order['departmentname'])); ?>">

				<!-- Hidden comment field — same name="comment" as original -->
				<input type="hidden" name="comment" value="<?php echo htmlspecialchars(isset($order['stat_comment']) ? $order['stat_comment'] : '', ENT_QUOTES,'UTF-8'); ?>" />

				<!-- Clickable Header -->
				<div class="po-hdr" onclick="poToggle(this)">
					<div class="po-num"><i class="fa fa-caret-right"></i> PO-<?php echo $order['orderno']; ?></div>
					<div class="po-sup"><?php echo htmlspecialchars($order['suppname']); ?></div>
					<div class="po-meta">
						<span><i class="fa fa-calendar-o"></i> <?php echo $order['orddate']; ?></span>
						<span><i class="fa fa-user-o"></i> <?php echo htmlspecialchars($order['initiator']); ?></span>
						<span><i class="fa fa-building-o"></i> <?php echo htmlspecialchars($order['departmentname']); ?></span>
						<span><i class="fa fa-truck"></i> <?php echo $order['deliverydate']; ?></span>
					</div>
					<span class="po-badge <?php echo $bc; ?>">
						<?php echo ($order['status'] == 'DepartmentalAuthorised') ? 'Dept. Auth' : $order['status']; ?>
					</span>
					<div class="po-val"><?php echo $order['currcode']; ?> <?php echo $order['totalformatted']; ?></div>
				</div>

				<!-- Expandable Details -->
				<div class="po-det" id="poDet<?php echo $idx; ?>">
					<div class="po-dgrid">
						<!-- Line Items Table -->
						<div class="po-lsec">
							<h4><i class="fa fa-list"></i>&nbsp; Line Items</h4>
							<table class="po-ltbl">
								<thead><tr>
									<th>Item Description</th>
									<th>GL Code</th>
									<?php if ($showGLName): ?><th>GL Name</th><?php endif; ?>
									<th class="r">Qty</th>
									<th>Currency</th>
									<th class="r">Unit Price</th>
									<th class="r">Line Total</th>
									<th>Jobref</th>
								</tr></thead>
								<tbody>
								<?php foreach ($order['lines'] as $line): ?>
									<tr>
										<td><?php echo htmlspecialchars($line['itemdescription']); ?></td>
										<td><?php echo htmlspecialchars($line['oldglcode']); ?></td>
										<?php if ($showGLName): ?><td><?php echo htmlspecialchars($line['glname']); ?></td><?php endif; ?>
										<td class="r"><?php echo $line['quantityord']; ?></td>
										<td><?php echo $line['currcode']; ?></td>
										<td class="r"><?php echo $line['unitprice']; ?></td>
										<td class="r"><?php echo $line['linetotal']; ?></td>
										<td><?php echo htmlspecialchars($line['jobref']); ?></td>
									</tr>
								<?php endforeach; ?>
									<tr class="tot">
										<td colspan="<?php echo $showGLName ? 7 : 6; ?>" style="text-align:right;">Order Total</td>
										<td class="r"><?php echo $order['totalformatted']; ?></td>
										<td></td>
									</tr>
								</tbody>
							</table>
						</div>

						<!-- Action Panel -->
						<div class="po-apnl">
							<h4><i class="fa fa-gavel"></i>&nbsp; Decision</h4>

							<?php if ($order['readOnly']): ?>
								<div class="po-ro">
									<i class="fa fa-lock"></i>&nbsp; Awaiting CFO/GM Approval<br/>
									<small>Above your authorisation level</small>
								</div>

							<?php elseif ($order['canAuthorise']): ?>
								<div class="po-selw">
									<label>Set Status</label>
									<select name="Status<?php echo $order['orderno']; ?>" onchange="poSelChange(this)">
										<option selected="selected" value="Pending">Pending</option>
										<option value="Authorised">Authorised</option>
										<option value="Rejected">Rejected</option>
										<option value="Cancelled">Cancelled</option>
									</select>
								</div>

							<?php elseif ($order['canDeptAuth']): ?>
								<div class="po-selw">
									<label>Set Status</label>
									<select name="Status<?php echo $order['orderno']; ?>" onchange="poSelChange(this)">
										<option selected="selected" value="Pending">Pending</option>
										<option value="DepartmentalAuthorised">Departmental Authorised</option>
										<option value="Rejected">Rejected</option>
										<option value="Cancelled">Cancelled</option>
									</select>
								</div>
							<?php endif; ?>

							<div class="po-links" style="margin-top:6px;">
								<h4><i class="fa fa-link"></i>&nbsp; Quick Links</h4>
								<a class="po-lnk" href="javascript:void(0)" onclick="poOpenModal('<?php echo $RootPath; ?>/PurchaseOrdersAttachments.php?orderno=<?php echo $order['orderno']; ?>', 'Attachments — PO-<?php echo $order['orderno']; ?>', 'fa-paperclip')">
									<i class="fa fa-paperclip"></i> View Attachments
								</a>
								<a class="po-lnk" href="javascript:void(0)" onclick="poOpenModal('<?php echo $RootPath; ?>/PurchaseOrdersSplit.php?orderno=<?php echo $order['orderno']; ?>', 'GL Split — PO-<?php echo $order['orderno']; ?>', 'fa-pie-chart')">
									<i class="fa fa-pie-chart"></i> View GL Split
								</a>
							</div>
						</div>
					</div>
				</div>
			</div>
		<?php endforeach; ?>
		</div>

		<!-- Sticky Submit -->
		<div class="po-submit">
			<div class="info">
				<strong id="poChangedCount">0</strong> decision(s) changed &nbsp;|&nbsp;
				<strong><?php echo $orderCount; ?></strong> order(s) total &nbsp;|&nbsp;
				Value: <strong><?php echo locale_number_format($grandTotalValue, 2); ?></strong>
			</div>
			<button type="submit" name="UpdateAll" value="Update" class="po-btn">
				<i class="fa fa-check"></i>&nbsp; Update All Decisions
			</button>
		</div>
	</form>

<?php else: ?>
	<div class="po-empty">
		<i class="fa fa-check-circle"></i>
		<h3>All Clear!</h3>
		<p>There are no purchase orders awaiting your authorisation at this time.</p>
	</div>
<?php endif; ?>

</div><!-- end po-wrap -->

<!-- Modal Popup for Attachments / GL Split — OUTSIDE po-wrap for proper fixed centering -->
<div class="po-modal-overlay" id="poModalOverlay">
	<div class="po-modal">
		<div class="po-modal-hdr">
			<h3><i class="fa fa-paperclip" id="poModalIcon"></i> <span id="poModalTitle">Loading...</span></h3>
			<button class="po-modal-close" onclick="poCloseModal()" title="Close">&times;</button>
		</div>
		<div class="po-modal-body">
			<div class="po-modal-spinner" id="poModalSpinner"><i class="fa fa-spinner"></i> Loading content...</div>
			<iframe id="poModalFrame" src="about:blank" onload="poFrameLoaded()"></iframe>
		</div>
		<div class="po-modal-foot">
			<a href="#" id="poModalNewTab" target="_blank"><i class="fa fa-external-link"></i> Open in new tab</a>
			<span class="po-modal-foot-hint">Press ESC to close</span>
		</div>
	</div>
</div>

<script>
(function(){
	/* Toggle single card */
	window.poToggle = function(hdr) {
		var det = hdr.nextElementSibling;
		if (!det) return;
		hdr.classList.toggle('open');
		det.classList.toggle('show');
	};

	/* Expand / Collapse all */
	var xBtn = document.getElementById('xpandBtn');
	if (xBtn) {
		var xOpen = false;
		xBtn.addEventListener('click', function() {
			xOpen = !xOpen;
			var cards = document.querySelectorAll('.po-card');
			for (var i = 0; i < cards.length; i++) {
				if (cards[i].style.display === 'none') continue;
				var h = cards[i].querySelector('.po-hdr');
				var d = cards[i].querySelector('.po-det');
				if (xOpen) { h.classList.add('open'); d.classList.add('show'); }
				else { h.classList.remove('open'); d.classList.remove('show'); }
			}
			this.innerHTML = xOpen ? '<i class="fa fa-compress"></i> Collapse All' : '<i class="fa fa-expand"></i> Expand All';
		});
	}

	/* Search */
	var si = document.getElementById('poSearch');
	if (si) {
		si.addEventListener('input', function() {
			var t = this.value.toLowerCase();
			var cards = document.querySelectorAll('.po-card');
			for (var i = 0; i < cards.length; i++) {
				var s = cards[i].getAttribute('data-search') || '';
				cards[i].style.display = (t === '' || s.indexOf(t) !== -1) ? '' : 'none';
			}
		});
	}

	/* Status filter buttons */
	var fbtns = document.querySelectorAll('.po-fbtn');
	for (var i = 0; i < fbtns.length; i++) {
		fbtns[i].addEventListener('click', function() {
			for (var j = 0; j < fbtns.length; j++) fbtns[j].classList.remove('on');
			this.classList.add('on');
			var f = this.getAttribute('data-f');
			var cards = document.querySelectorAll('.po-card');
			for (var k = 0; k < cards.length; k++) {
				cards[k].style.display = (f === 'all' || cards[k].getAttribute('data-status') === f) ? '' : 'none';
			}
			if (si) si.value = '';
		});
	}

	/* Select colour change + change tracking */
	var changedCount = 0;
	var counter = document.getElementById('poChangedCount');

	window.poSelChange = function(sel) {
		var v = sel.value;
		sel.className = '';
		if (v === 'Authorised') sel.className = 'sel-auth';
		else if (v === 'DepartmentalAuthorised') sel.className = 'sel-dept';
		else if (v === 'Rejected' || v === 'Cancelled') sel.className = 'sel-reject';

		var card = sel.closest('.po-card');
		if (v !== 'Pending') {
			if (!card.classList.contains('po-changed')) {
				card.classList.add('po-changed');
				changedCount++;
			}
		} else {
			if (card.classList.contains('po-changed')) {
				card.classList.remove('po-changed');
				changedCount--;
			}
		}
		if (counter) counter.textContent = changedCount;
	};

	/* Confirm before submit */
	var form = document.getElementById('poForm');
	if (form) {
		form.addEventListener('submit', function(e) {
			if (changedCount > 0) {
				if (!confirm('You are about to update ' + changedCount + ' purchase order(s). Continue?')) {
					e.preventDefault();
				}
			}
		});
	}

	/* ── Modal Popup Functions ── */
	var modalOverlay = document.getElementById('poModalOverlay');
	var modalFrame = document.getElementById('poModalFrame');
	var modalTitle = document.getElementById('poModalTitle');
	var modalIcon = document.getElementById('poModalIcon');
	var modalSpinner = document.getElementById('poModalSpinner');
	var modalNewTab = document.getElementById('poModalNewTab');

	window.poOpenModal = function(url, title, icon) {
		if (modalTitle) modalTitle.textContent = title || 'Loading...';
		if (modalIcon) modalIcon.className = 'fa ' + (icon || 'fa-file');
		if (modalSpinner) modalSpinner.style.display = 'flex';
		if (modalFrame) { modalFrame.style.opacity = '0'; modalFrame.src = url; }
		if (modalNewTab) modalNewTab.href = url;
		if (modalOverlay) modalOverlay.classList.add('show');
		document.body.style.overflow = 'hidden';
	};

	window.poCloseModal = function() {
		if (modalOverlay) modalOverlay.classList.remove('show');
		if (modalFrame) { modalFrame.src = 'about:blank'; modalFrame.style.opacity = '0'; }
		document.body.style.overflow = '';
	};

	window.poFrameLoaded = function() {
		if (modalFrame && modalFrame.src !== 'about:blank') {
			if (modalSpinner) modalSpinner.style.display = 'none';
			modalFrame.style.opacity = '1';
		}
	};

	/* Close on overlay background click */
	if (modalOverlay) {
		modalOverlay.addEventListener('click', function(e) {
			if (e.target === modalOverlay) poCloseModal();
		});
	}

	/* Close on ESC key */
	document.addEventListener('keydown', function(e) {
		if (e.key === 'Escape' && modalOverlay && modalOverlay.classList.contains('show')) {
			poCloseModal();
		}
	});
})();
</script>

<?php
echo '</div>';

include('includes/MainMenuLinksArray.php');

if (isset($SupplierLogin) AND $SupplierLogin==1){
	echo '<table class="table_index">
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=1">' . _('View or Amend outstanding offers') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=2">' . _('Create a new offer') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SupplierTenders.php?TenderType=3">' . _('View any open tenders without an offer') . '</a></p></td></tr>
		</table>';
	include('includes/footer.inc');
	exit;
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
	echo '<table class="table_index">
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/CustomerInquiry.php?CustomerID=' . $_SESSION['CustomerID'] . '">' . _('Account Status') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectOrderItems.php?NewOrder=Yes">' . _('Place An Order') . '</a></p></td></tr>
			<tr><td class="menu_group_item"><p>&bull; <a href="' . $RootPath . '/SelectCompletedOrder.php?SelectedCustomer=' . $_SESSION['CustomerID'] . '">' . _('Order Status') . '</a></p></td></tr>
		</table>';
	include('includes/footer.inc');
	exit;
}

if (isset($_GET['Application'])){
	$_SESSION['Module'] = $_GET['Application'];
}
?>
