<?php
include ('includes/htmlMimeMail.php');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title = _('Authorise Internal Material Requisition (Internal Stock Requests)');
$ViewTopic = 'Inventory';
$BookMark = 'AuthoriseRequest';
include('includes/newheader.php');

$userid = $_SESSION['UserID'];

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

$SQLuser = "SELECT email,realname FROM www_users WHERE userid='" . $userid . "'";
$resultuser = DB_query($SQLuser);
$myrowuser = DB_fetch_array($resultuser);
$emailm = $myrowuser['email'];
$realname = $myrowuser['realname'];

/* =====================================================================
 * POST PROCESSING — COMPLETELY UNCHANGED FROM ORIGINAL
 * Same variable names, same SQL, same email logic, same PHPMailer
 * ===================================================================== */
if (isset($_POST['UpdateAll'])) {

	foreach ($_POST as $POSTVariableName => $POSTValue) {

		if (mb_substr($POSTVariableName,0,6)=='status') {

			$RequestNo=mb_substr($POSTVariableName,6);

			$SQL = "SELECT departmentid,initiator
				FROM stockrequest
				WHERE dispatchid='" . $RequestNo. "'";
			$result = DB_query($SQL);
			$myrowuser = DB_fetch_array($result) ;
			$department = $myrowuser['departmentid'];
			$initiator = $myrowuser['initiator'];

			$EmailSQL="SELECT email
					FROM www_users
					WHERE realname = '" . $initiator."'";
			$EmailResult = DB_query($EmailSQL);
			$myEmail=DB_fetch_array($EmailResult);
			$initiatoremail = $myEmail['email'];

			$sql="UPDATE stockrequest
					SET authorised='1',
					authorized_by = '" . $realname . "',
					datetime = '" . $modifieddatetime . "'
					WHERE dispatchid='" . $RequestNo . "'";
			$result=DB_query($sql);

			$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 internal stock request - '.$RequestNo.' has been authorized by manager: '.$realname.' at '.$fijitime );
			$ConfirmationText1 = _('This internal stock request - '.$RequestNo.' has been authorized by manager: '.$realname.' at '.$fijitime.'. Please go and fulfill this request created by:'.$initiator );

			$EmailSubject = _('Stock Request authorised');
			$emailcc = 'sachinebusiness@gmail.com';

			$mail = new PHPMailer(true);
			$mail->getSentMIMEMEssage();
			$mail->Host = 'smtp-relay.sendinblue.com';
			$mail->SMTPAuth = true;
			$mail->Username = 'sachinebusiness@gmail.com';
			$mail->Password = 'R5kyxwrJnWSLH4fh';
			$mail->SMTPSecure = 'tls';
			$mail->Port = 587;
			$mail->ClearAddresses();
			$mail->setFrom('erp@ebusinescloudservers.com', 'E-Business ERP');
			$mail->addAddress($myEmail1['email'], 'recipient ');
			$mail->AddCC($emailcc);
			$mail->isHTML(true);
			$mail->Subject = $EmailSubject;
			$mail->Body    = $ConfirmationText;
			$mail->send();
		}

		if (strpos($POSTVariableName, 'cancel')) {

			$CancelItems = explode('cancel', $POSTVariableName);

			$sql = "UPDATE stockrequestitems
						SET completed=1
						WHERE dispatchid='" . $CancelItems[0] . "'
						AND dispatchitemsid='" . $CancelItems[1] . "'";
			$result = DB_query($sql);
			$result = DB_query("SELECT stockid FROM stockrequestitems WHERE completed=0 AND dispatchid='" . $CancelItems[0] . "'");

			if (DB_num_rows($result) ==0){
				$result = DB_query("UPDATE stockrequest
									SET authorised='1',
									authorized_by = '" . $realname . "',
									datetime = '" . $modifieddatetime . "'
									WHERE dispatchid='" . $CancelItems[0] . "'");
			}

			$SQL = "SELECT departmentid,initiator
				FROM stockrequest
				WHERE dispatchid='" . $CancelItems[0]. "'";
			$result = DB_query($SQL);
			$myrowuser = DB_fetch_array($result) ;
			$department = $myrowuser['departmentid'];
			$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 ='sharukh@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'];

			$ConfirmationText1 = $CancelItems[0]._(' This internal stock request has been cancelled created by:'.$initiator);
			$ConfirmationText2 = $CancelItems[0]._(' This internal stock request has been cancelled by youcreated by:'.$initiator);
			$EmailSubject = _('Stock Request Cancelled');

			mail($ravinesh,$EmailSubject,$ConfirmationText1);
			mail($sharukh,$EmailSubject,$ConfirmationText1);
			mail($rav,$EmailSubject,$ConfirmationText1);
			mail($sachin,$EmailSubject,$ConfirmationText1);
			mail($initiatoremail,$EmailSubject,$ConfirmationText1);
			mail($authorisersemail,$EmailSubject,$ConfirmationText2);

			if ($department = 6 || $department = 9) {
				mail($shiv,$EmailSubject,$ConfirmationText1);
			}

			if ($department = 7 || $department = 10 || $department = 2 ) {
				mail($vani,$EmailSubject,$ConfirmationText1);
			}
		}
	}
}

/* =====================================================================
 * DETERMINE SQL BASED ON USER — Same two branches as original
 * douglas: joins www_users ON userid = session user
 * everyone else: joins www_users ON userid = department.authoriser
 * ===================================================================== */
$userid = $_SESSION['UserID'];

if ($userid == 'douglas') {
	$sql="SELECT stockrequest.dispatchid,
			locations.locationname,
			stockrequest.despatchdate,
			stockrequest.jobno,
			stockrequest.account,
			stockrequest.client,
			stockrequest.patrollocation,
			stockrequest.producttype,
			stockrequest.initiator,
			stockrequest.narrative,
			department.departmentname,
			www_users.realname,
			www_users.email
		FROM stockrequest INNER JOIN department
			ON stockrequest.departmentid=department.departmentid
		INNER JOIN locations
			ON stockrequest.loccode=locations.loccode
		INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" . $_SESSION['UserID'] . "'
		INNER JOIN www_users
			ON www_users.userid='" . $_SESSION['UserID'] . "'
		WHERE stockrequest.authorised=0
		AND stockrequest.closed=0
		AND www_users.userid='".$_SESSION['UserID']."'";
} else {
	$sql="SELECT stockrequest.dispatchid,
			locations.locationname,
			stockrequest.despatchdate,
			stockrequest.jobno,
			stockrequest.account,
			stockrequest.client,
			stockrequest.patrollocation,
			stockrequest.producttype,
			stockrequest.initiator,
			stockrequest.narrative,
			department.departmentname,
			www_users.realname,
			www_users.email
		FROM stockrequest INNER JOIN department
			ON stockrequest.departmentid=department.departmentid
		INNER JOIN locations
			ON stockrequest.loccode=locations.loccode
		INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" . $_SESSION['UserID'] . "'
		INNER JOIN www_users
			ON www_users.userid=department.authoriser
		WHERE stockrequest.authorised=0
		AND stockrequest.closed=0
		AND www_users.userid='".$_SESSION['UserID']."'";
}

$result = DB_query($sql);

/* =====================================================================
 * COLLECT DATA INTO ARRAYS — For clean rendering
 * ===================================================================== */
$requests = array();
$totalItems = 0;

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

	// Lookup project details
	$SQL77 = "SELECT project_name, wip_expense FROM projectdetails WHERE projectid='" . $myrow['jobno'] . "'";
	$result77 = DB_query($SQL77);
	$myrow77 = DB_fetch_array($result77);

	// Lookup billing name
	$SQL771 = "SELECT billing_name FROM debtoraccount WHERE account_number='" . $myrow['account'] . "'";
	$result771 = DB_query($SQL771);
	$myrow771 = DB_fetch_array($result771);

	// Lookup patrol location name
	$SQL7711 = "SELECT patrollocation FROM guardforceclient WHERE clientid='" . $myrow['patrollocation'] . "'";
	$result7711 = DB_query($SQL7711);
	$myrow7711 = DB_fetch_array($result7711);

	// Lookup category name
	$SQLP = "SELECT accountname FROM chartmaster WHERE accountcode ='" . $myrow['producttype'] . "'";
	$resultP = DB_query($SQLP);
	$myrowP = DB_fetch_array($resultP);

	// Get line items
	$LinesSQL="SELECT stockrequestitems.dispatchitemsid,
					stockrequestitems.stockid,
					stockrequestitems.decimalplaces,
					stockrequestitems.uom,
					stockmaster.description,
					stockrequestitems.quantity
			FROM stockrequestitems
			INNER JOIN stockmaster
			ON stockmaster.stockid=stockrequestitems.stockid
		WHERE dispatchid='".$myrow['dispatchid'] . "'
		AND completed=0";
	$LineResult = DB_query($LinesSQL);

	$lineItems = array();
	while ($LineRow = DB_fetch_array($LineResult)) {
		$lineItems[] = array(
			'dispatchitemsid' => $LineRow['dispatchitemsid'],
			'stockid' => $LineRow['stockid'],
			'description' => $LineRow['description'],
			'quantity' => locale_number_format($LineRow['quantity'], $LineRow['decimalplaces']),
			'uom' => $LineRow['uom']
		);
		$totalItems++;
	}

	$requests[] = array(
		'dispatchid' => $myrow['dispatchid'],
		'departmentname' => $myrow['departmentname'],
		'locationname' => $myrow['locationname'],
		'despatchdate' => ConvertSQLDate($myrow['despatchdate']),
		'accountname' => isset($myrowP['accountname']) ? $myrowP['accountname'] : '',
		'account' => $myrow['account'],
		'billing_name' => isset($myrow771['billing_name']) ? $myrow771['billing_name'] : '',
		'jobno' => $myrow['jobno'],
		'project_name' => isset($myrow77['project_name']) ? $myrow77['project_name'] : '',
		'wip_expense' => isset($myrow77['wip_expense']) ? $myrow77['wip_expense'] : '',
		'patrollocation' => isset($myrow7711['patrollocation']) ? $myrow7711['patrollocation'] : '',
		'narrative' => $myrow['narrative'],
		'initiator' => $myrow['initiator'],
		'lines' => $lineItems
	);
}

$requestCount = count($requests);
?>

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

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

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

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

.kpi-card {
	background: var(--sr-white);
	border-radius: var(--sr-radius);
	padding: 18px;
	border-left: 4px solid var(--sr-primary);
	box-shadow: var(--sr-shadow);
	display: flex; align-items: center; gap: 14px;
	transition: transform .2s, box-shadow .2s;
}
.kpi-card:hover { transform: translateY(-2px); box-shadow: var(--sr-shadow-lg); }
.kpi-card.warn { border-left-color: var(--sr-warning); }
.kpi-card.inf  { border-left-color: var(--sr-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(--sr-light); color: var(--sr-primary); }
.kpi-ico.c2 { background: #FFF7E6; color: var(--sr-warning); }
.kpi-ico.c3 { background: #E6F7FF; color: var(--sr-info); }
.kpi-val { font-size: 24px; font-weight: 700; line-height: 1.1; }
.kpi-lbl { font-size: 11px; color: var(--sr-muted); font-weight: 600; text-transform: uppercase; letter-spacing: .5px; }

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

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

.sr-auth-all {
	padding: 6px 14px; border: 1px solid var(--sr-success); border-radius: 6px;
	background: #F6FFED; color: #389E0D; font-family: inherit; font-size: 12px; font-weight: 500;
	cursor: pointer; transition: all .2s; display: flex; align-items: center; gap: 5px;
}
.sr-auth-all:hover { background: var(--sr-success); color: #fff; }

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

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

/* Card header */
.sr-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;
}
.sr-hdr:hover { background: var(--sr-light); }
.sr-hdr.open { border-bottom-color: var(--sr-border); background: var(--sr-light); }

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

.sr-dept { font-weight: 500; font-size: 13px; flex: 1; min-width: 110px; }

.sr-meta { display: flex; gap: 14px; flex-wrap: wrap; font-size: 11px; color: var(--sr-muted); }
.sr-meta span { display: flex; align-items: center; gap: 3px; white-space: nowrap; }
.sr-meta i { font-size: 11px; }

.sr-items-count {
	background: var(--sr-light); color: var(--sr-dark);
	padding: 2px 10px; border-radius: 10px;
	font-size: 11px; font-weight: 600; white-space: nowrap;
}

/* Auth checkbox in header */
.sr-auth-chk {
	display: flex; align-items: center; gap: 6px;
	padding: 4px 12px; border-radius: 6px;
	font-size: 11px; font-weight: 600; color: var(--sr-success);
	background: #F6FFED; border: 1px solid #B7EB8F;
	white-space: nowrap; cursor: pointer;
	transition: all .15s;
}
.sr-auth-chk:hover { background: #D9F7BE; }
.sr-auth-chk input[type="checkbox"] {
	width: 16px; height: 16px; accent-color: var(--sr-success); cursor: pointer;
}

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

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

/* Info section */
.sr-info-grid {
	padding: 14px 18px;
	display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
	gap: 10px;
	background: var(--sr-bg); border-bottom: 1px solid var(--sr-border);
}
.sr-info-item {}
.sr-info-item .lbl {
	font-size: 9px; font-weight: 600; color: var(--sr-muted);
	text-transform: uppercase; letter-spacing: .5px; margin-bottom: 2px;
}
.sr-info-item .val { font-size: 12px; font-weight: 500; }

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

.sr-cancel-chk {
	display: flex; align-items: center; gap: 5px;
	font-size: 11px; color: var(--sr-danger); font-weight: 500; cursor: pointer;
}
.sr-cancel-chk input[type="checkbox"] {
	width: 15px; height: 15px; accent-color: var(--sr-danger); cursor: pointer;
}

/* Side panel */
.sr-apnl {
	padding: 14px 18px; background: var(--sr-bg);
	border-left: 1px solid var(--sr-border);
	display: flex; flex-direction: column; gap: 10px;
}
@media(max-width:768px){ .sr-apnl{border-left:none;border-top:1px solid var(--sr-border);} }
.sr-apnl h4 {
	font-size: 12px; font-weight: 600; color: var(--sr-muted); margin: 0;
	text-transform: uppercase; letter-spacing: .5px;
}
.sr-detail-row { display: flex; flex-direction: column; gap: 2px; }
.sr-detail-row .lbl {
	font-size: 9px; font-weight: 600; color: var(--sr-muted);
	text-transform: uppercase; letter-spacing: .5px;
}
.sr-detail-row .val { font-size: 12px; font-weight: 500; word-break: break-word; }

/* ── Sticky Submit ── */
.sr-submit {
	position: sticky; bottom: 0;
	background: var(--sr-white); border-top: 1px solid var(--sr-border);
	padding: 14px 18px; margin-top: 22px;
	border-radius: var(--sr-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;
}
.sr-submit .info { font-size: 12px; color: var(--sr-muted); }
.sr-submit .info strong { color: var(--sr-text); }

.sr-btn {
	padding: 9px 28px;
	background: linear-gradient(135deg, var(--sr-primary) 0%, var(--sr-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);
}
.sr-btn:hover {
	background: linear-gradient(135deg, var(--sr-dark) 0%, var(--sr-darker) 100%);
	box-shadow: 0 4px 12px rgba(42,171,179,.4); transform: translateY(-1px);
}

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

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

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

	<!-- Banner -->
	<div class="sr-banner">
		<div>
			<h1><i class="fa fa-clipboard"></i> Internal Stock Request Authorisation</h1>
			<div class="crumb">
				<a href="index.php">Home</a> &nbsp;/&nbsp; Inventory &nbsp;/&nbsp; Authorise Requests
			</div>
		</div>
		<div class="sr-banner-r">
			<span class="sr-pill"><i class="fa fa-user"></i>&nbsp; <?php echo htmlspecialchars($realname); ?></span>
			<span class="sr-pill sr-pill-dim"><i class="fa fa-calendar"></i>&nbsp; <?php echo $fijitime; ?></span>
		</div>
	</div>

	<!-- KPI -->
	<div class="sr-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 $requestCount; ?></div><div class="kpi-lbl">Pending Requests</div></div>
		</div>
		<div class="kpi-card warn">
			<div class="kpi-ico c2"><i class="fa fa-cubes"></i></div>
			<div><div class="kpi-val"><?php echo $totalItems; ?></div><div class="kpi-lbl">Total Line Items</div></div>
		</div>
		<div class="kpi-card inf">
			<div class="kpi-ico c3"><i class="fa fa-user-o"></i></div>
			<div><div class="kpi-val"><?php
				$uniqueInitiators = array();
				foreach ($requests as $r) {
					$uniqueInitiators[$r['initiator']] = true;
				}
				echo count($uniqueInitiators);
			?></div><div class="kpi-lbl">Requestors</div></div>
		</div>
	</div>

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

	<!-- Toolbar -->
	<div class="sr-toolbar">
		<div class="sr-search">
			<i class="fa fa-search"></i>
			<input type="text" id="srSearch" placeholder="Search request#, department, initiator, narrative..." />
		</div>
		<button type="button" class="sr-xbtn" id="xpandBtn"><i class="fa fa-expand"></i> Expand All</button>
		<button type="button" class="sr-auth-all" id="authAllBtn"><i class="fa fa-check-circle"></i> Select 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="srForm">
		<input type="hidden" name="FormID" value="<?php echo $_SESSION['FormID']; ?>" />

		<div class="sr-list" id="srList">
		<?php foreach ($requests as $idx => $req): ?>
			<div class="sr-card"
				 data-search="<?php echo htmlspecialchars(strtolower($req['dispatchid'].' '.$req['departmentname'].' '.$req['initiator'].' '.$req['narrative'].' '.$req['billing_name'].' '.$req['project_name'])); ?>">

				<!-- Clickable Header -->
				<div class="sr-hdr" onclick="srToggle(this)">
					<div class="sr-num"><i class="fa fa-caret-right"></i> #<?php echo $req['dispatchid']; ?></div>
					<div class="sr-dept"><?php echo htmlspecialchars($req['departmentname']); ?></div>
					<div class="sr-meta">
						<span><i class="fa fa-calendar-o"></i> <?php echo $req['despatchdate']; ?></span>
						<span><i class="fa fa-user-o"></i> <?php echo htmlspecialchars($req['initiator']); ?></span>
						<span><i class="fa fa-map-marker"></i> <?php echo htmlspecialchars($req['locationname']); ?></span>
					</div>
					<span class="sr-items-count"><?php echo count($req['lines']); ?> item(s)</span>
					<!-- Authorise checkbox — same name="status{dispatchid}" as original -->
					<label class="sr-auth-chk" onclick="event.stopPropagation();">
						<input type="checkbox" name="status<?php echo $req['dispatchid']; ?>" onchange="srChkChange()" />
						Authorise
					</label>
				</div>

				<!-- Expandable Details -->
				<div class="sr-det" id="srDet<?php echo $idx; ?>">

					<!-- Info grid with all the metadata fields -->
					<div class="sr-info-grid">
						<div class="sr-info-item">
							<div class="lbl">Category</div>
							<div class="val"><?php echo htmlspecialchars($req['accountname']); ?></div>
						</div>
						<div class="sr-info-item">
							<div class="lbl">Account</div>
							<div class="val"><?php echo htmlspecialchars($req['account']); ?></div>
						</div>
						<div class="sr-info-item">
							<div class="lbl">Client Name</div>
							<div class="val"><?php echo htmlspecialchars($req['billing_name']); ?></div>
						</div>
						<div class="sr-info-item">
							<div class="lbl">Job No</div>
							<div class="val"><?php echo htmlspecialchars($req['jobno']); ?></div>
						</div>
						<div class="sr-info-item">
							<div class="lbl">Job Name</div>
							<div class="val"><?php echo htmlspecialchars($req['project_name']); ?></div>
						</div>
						<div class="sr-info-item">
							<div class="lbl">WIP GL</div>
							<div class="val"><?php echo htmlspecialchars($req['wip_expense']); ?></div>
						</div>
						<div class="sr-info-item">
							<div class="lbl">Patrol Location</div>
							<div class="val"><?php echo htmlspecialchars($req['patrollocation']); ?></div>
						</div>
						<div class="sr-info-item">
							<div class="lbl">Narrative</div>
							<div class="val"><?php echo htmlspecialchars($req['narrative']); ?></div>
						</div>
					</div>

					<!-- Line Items Table -->
					<div class="sr-lsec">
						<h4><i class="fa fa-cubes"></i>&nbsp; Requested Items</h4>
						<table class="sr-ltbl">
							<thead><tr>
								<th>Product Description</th>
								<th class="r">Qty Required</th>
								<th>Unit</th>
								<th>Cancel Line</th>
							</tr></thead>
							<tbody>
							<?php foreach ($req['lines'] as $line): ?>
								<tr>
									<td><?php echo htmlspecialchars($line['description']); ?></td>
									<td class="r"><?php echo $line['quantity']; ?></td>
									<td><?php echo htmlspecialchars($line['uom']); ?></td>
									<td>
										<!-- Cancel checkbox — same name="{dispatchid}cancel{lineId}" as original -->
										<label class="sr-cancel-chk">
											<input type="checkbox" name="<?php echo $req['dispatchid']; ?>cancel<?php echo $line['dispatchitemsid']; ?>" />
											Cancel
										</label>
									</td>
								</tr>
							<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				</div>
			</div>
		<?php endforeach; ?>
		</div>

		<!-- Sticky Submit -->
		<div class="sr-submit">
			<div class="info">
				<strong id="srAuthCount">0</strong> request(s) selected for authorisation &nbsp;|&nbsp;
				<strong><?php echo $requestCount; ?></strong> total pending
			</div>
			<button type="submit" name="UpdateAll" value="Update" class="sr-btn">
				<i class="fa fa-check"></i>&nbsp; Update All
			</button>
		</div>
	</form>

<?php else: ?>
	<div class="sr-empty">
		<i class="fa fa-check-circle"></i>
		<h3>All Clear!</h3>
		<p>There are no internal stock requests awaiting your authorisation.</p>
	</div>
<?php endif; ?>

</div>

<!-- ============================================================
     JAVASCRIPT — Toggle, Search, Select All, Change Tracking
     ============================================================ -->
<script>
(function(){
	/* Toggle single card */
	window.srToggle = 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('.sr-card');
			for (var i = 0; i < cards.length; i++) {
				if (cards[i].style.display === 'none') continue;
				var h = cards[i].querySelector('.sr-hdr');
				var d = cards[i].querySelector('.sr-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';
		});
	}

	/* Select All / Deselect All authorise checkboxes */
	var authAllBtn = document.getElementById('authAllBtn');
	if (authAllBtn) {
		var allChecked = false;
		authAllBtn.addEventListener('click', function() {
			allChecked = !allChecked;
			var chks = document.querySelectorAll('.sr-auth-chk input[type="checkbox"]');
			for (var i = 0; i < chks.length; i++) {
				chks[i].checked = allChecked;
			}
			this.innerHTML = allChecked
				? '<i class="fa fa-times-circle"></i> Deselect All'
				: '<i class="fa fa-check-circle"></i> Select All';
			srChkChange();
		});
	}

	/* Search */
	var si = document.getElementById('srSearch');
	if (si) {
		si.addEventListener('input', function() {
			var t = this.value.toLowerCase();
			var cards = document.querySelectorAll('.sr-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';
			}
		});
	}

	/* Track authorise checkbox count */
	var counter = document.getElementById('srAuthCount');
	window.srChkChange = function() {
		var checked = document.querySelectorAll('.sr-auth-chk input[type="checkbox"]:checked');
		if (counter) counter.textContent = checked.length;
	};

	/* Confirm before submit */
	var form = document.getElementById('srForm');
	if (form) {
		form.addEventListener('submit', function(e) {
			var authChecked = document.querySelectorAll('.sr-auth-chk input[type="checkbox"]:checked').length;
			var cancelChecked = document.querySelectorAll('.sr-cancel-chk input[type="checkbox"]:checked').length;
			var total = authChecked + cancelChecked;
			if (total > 0) {
				var msg = '';
				if (authChecked > 0) msg += authChecked + ' request(s) to authorise';
				if (cancelChecked > 0) {
					if (msg) msg += ' and ';
					msg += cancelChecked + ' line(s) to cancel';
				}
				if (!confirm('You are about to process: ' + msg + '. Continue?')) {
					e.preventDefault();
				}
			}
		});
	}
})();
</script>

<?php

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'];
}
?>