<?php

/* $Id: index.php 6941 2014-10-26 23:18:08Z daintree $*/

error_reporting(E_ALL & ~E_NOTICE);

$PageSecurity=0;

include('includes/DefineStockRequestClass.php');

include('includes/session.inc');

$Title=_('Internal Stock Request');

include('includes/newheader.php');

include('includes/SQL_CommonFunctions.inc');


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';

?>

<!-- ============================================================
     ENHANCED UI: Ant Design Style + Teal Branding
     ============================================================ -->
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

<style>
/* ── Base Reset & Typography ── */
.isr-wrapper * { box-sizing: border-box; }
.isr-wrapper {
    font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
    color: #1F2937;
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px 40px;
}

/* ── Gradient Banner ── */
.isr-banner {
    background: linear-gradient(135deg, #1E8F96 0%, #2AABB3 50%, #35C4CD 100%);
    border-radius: 16px;
    padding: 32px 36px;
    margin: 20px 0 24px;
    color: #fff;
    position: relative;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(42,171,179,0.3);
}
.isr-banner::before {
    content: '';
    position: absolute;
    top: -40px;
    right: -40px;
    width: 200px;
    height: 200px;
    background: rgba(255,255,255,0.06);
    border-radius: 50%;
}
.isr-banner::after {
    content: '';
    position: absolute;
    bottom: -60px;
    right: 80px;
    width: 160px;
    height: 160px;
    background: rgba(255,255,255,0.04);
    border-radius: 50%;
}
.isr-banner h1 {
    font-size: 26px;
    font-weight: 700;
    margin: 0 0 6px;
    letter-spacing: -0.3px;
}
.isr-banner p {
    font-size: 14px;
    opacity: 0.9;
    margin: 0;
    font-weight: 300;
}
.isr-banner-actions {
    position: absolute;
    top: 28px;
    right: 36px;
    z-index: 2;
}
.isr-help-btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 10px 20px;
    background: rgba(255,255,255,0.18);
    border: 1.5px solid rgba(255,255,255,0.35);
    border-radius: 10px;
    color: #fff;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    backdrop-filter: blur(4px);
}
.isr-help-btn:hover {
    background: rgba(255,255,255,0.3);
    border-color: rgba(255,255,255,0.5);
    transform: translateY(-1px);
}
.isr-help-btn i { font-size: 15px; }

/* ── Help Modal ── */
.isr-modal-overlay {
    display: none;
    position: fixed;
    top: 0; left: 0; right: 0; bottom: 0;
    background: rgba(0,0,0,0.45);
    z-index: 10000;
    align-items: center;
    justify-content: center;
    backdrop-filter: blur(3px);
    animation: isrFadeIn 0.25s ease;
}
.isr-modal-overlay.active { display: flex; }
@keyframes isrFadeIn { from { opacity: 0; } to { opacity: 1; } }
@keyframes isrSlideUp { from { opacity: 0; transform: translateY(30px); } to { opacity: 1; transform: translateY(0); } }

.isr-modal {
    background: #fff;
    border-radius: 18px;
    width: 680px;
    max-width: 92vw;
    max-height: 85vh;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0,0,0,0.2);
    animation: isrSlideUp 0.3s ease;
    display: flex;
    flex-direction: column;
}
.isr-modal-header {
    background: linear-gradient(135deg, #1E8F96, #2AABB3);
    padding: 24px 28px;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.isr-modal-header h2 {
    margin: 0;
    font-size: 20px;
    font-weight: 700;
    display: flex;
    align-items: center;
    gap: 10px;
}
.isr-modal-close {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    border: none;
    background: rgba(255,255,255,0.2);
    color: #fff;
    font-size: 18px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: background 0.2s;
}
.isr-modal-close:hover { background: rgba(255,255,255,0.35); }

.isr-modal-body {
    padding: 28px;
    overflow-y: auto;
    flex: 1;
}

.isr-help-step {
    display: flex;
    gap: 16px;
    margin-bottom: 22px;
    padding: 18px;
    border-radius: 12px;
    background: #FAFBFC;
    border: 1px solid #F0F0F0;
    transition: border-color 0.2s, box-shadow 0.2s;
}
.isr-help-step:hover {
    border-color: #D1EEF0;
    box-shadow: 0 2px 12px rgba(42,171,179,0.08);
}
.isr-help-step:last-child { margin-bottom: 0; }

.isr-help-num {
    width: 40px;
    height: 40px;
    min-width: 40px;
    border-radius: 50%;
    background: linear-gradient(135deg, #2AABB3, #1E8F96);
    color: #fff;
    font-size: 16px;
    font-weight: 700;
    display: flex;
    align-items: center;
    justify-content: center;
}
.isr-help-content h4 {
    margin: 0 0 6px;
    font-size: 15px;
    font-weight: 600;
    color: #1F2937;
}
.isr-help-content p {
    margin: 0;
    font-size: 13px;
    color: #6B7280;
    line-height: 1.6;
}
.isr-help-tip {
    background: #E6F7F8;
    border: 1px solid #B5E8EB;
    border-radius: 10px;
    padding: 14px 18px;
    margin-top: 20px;
    display: flex;
    gap: 12px;
    align-items: flex-start;
}
.isr-help-tip i {
    color: #2AABB3;
    font-size: 18px;
    margin-top: 2px;
}
.isr-help-tip p {
    margin: 0;
    font-size: 13px;
    color: #1E8F96;
    line-height: 1.6;
}
.isr-modal-footer {
    padding: 16px 28px;
    border-top: 1px solid #F0F0F0;
    text-align: right;
}
.isr-modal-footer button {
    padding: 10px 28px;
    background: linear-gradient(135deg, #2AABB3, #1E8F96);
    color: #fff;
    border: none;
    border-radius: 8px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
}
.isr-modal-footer button:hover {
    background: linear-gradient(135deg, #1E8F96, #187278);
    transform: translateY(-1px);
}

/* ── Breadcrumb ── */
.isr-breadcrumb {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: rgba(255,255,255,0.8);
    margin-bottom: 12px;
}
.isr-breadcrumb a {
    color: rgba(255,255,255,0.8);
    text-decoration: none;
}
.isr-breadcrumb a:hover { color: #fff; }
.isr-breadcrumb .sep { opacity: 0.5; }

/* ── KPI Dashboard Cards ── */
.isr-dashboard {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 24px;
}
.isr-kpi {
    background: #fff;
    border-radius: 12px;
    padding: 20px 22px;
    border-left: 4px solid #2AABB3;
    box-shadow: 0 1px 8px rgba(0,0,0,0.06);
    transition: transform 0.2s, box-shadow 0.2s;
}
.isr-kpi:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 16px rgba(0,0,0,0.1);
}
.isr-kpi-icon {
    width: 42px;
    height: 42px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    margin-bottom: 12px;
}
.isr-kpi-icon.teal { background: #E6F7F8; color: #2AABB3; }
.isr-kpi-icon.blue { background: #E8F4FD; color: #1890FF; }
.isr-kpi-icon.green { background: #E8F8E8; color: #52C41A; }
.isr-kpi-icon.orange { background: #FFF4E6; color: #FAAD14; }
.isr-kpi .kpi-value {
    font-size: 26px;
    font-weight: 700;
    color: #1F2937;
    line-height: 1.1;
}
.isr-kpi .kpi-label {
    font-size: 12px;
    color: #6B7280;
    font-weight: 500;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-top: 4px;
}

/* ── Dashboard Toggle ── */
.isr-dash-toggle {
    display: flex;
    align-items: center;
    gap: 8px;
    cursor: pointer;
    font-size: 13px;
    color: #6B7280;
    font-weight: 500;
    margin-bottom: 16px;
    user-select: none;
    padding: 8px 14px;
    background: #F9FAFB;
    border-radius: 8px;
    width: fit-content;
    transition: color 0.2s;
}
.isr-dash-toggle:hover { color: #2AABB3; }
.isr-dash-toggle i { transition: transform 0.3s; font-size: 11px; }
.isr-dash-toggle.collapsed i { transform: rotate(-90deg); }
.isr-dashboard-wrap {
    overflow: hidden;
    transition: max-height 0.4s ease, opacity 0.3s;
    max-height: 300px;
    opacity: 1;
}
.isr-dashboard-wrap.collapsed {
    max-height: 0;
    opacity: 0;
}

/* ── Section Cards ── */
.isr-card {
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 1px 8px rgba(0,0,0,0.06);
    border: 1px solid #E5E7EB;
    margin-bottom: 20px;
    overflow: hidden;
}
.isr-card-header {
    padding: 18px 24px;
    border-bottom: 1px solid #F0F0F0;
    display: flex;
    align-items: center;
    gap: 12px;
    background: #FAFBFC;
}
.isr-card-header i {
    width: 36px;
    height: 36px;
    background: linear-gradient(135deg, #2AABB3, #1E8F96);
    color: #fff;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 15px;
}
.isr-card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #1F2937;
}
.isr-card-header .subtitle {
    font-size: 12px;
    color: #9CA3AF;
    font-weight: 400;
}
.isr-card-body {
    padding: 24px;
}

/* ── Form Overlay Styles ── */
.isr-wrapper table.selection {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    border: none !important;
    background: transparent !important;
}
.isr-wrapper table.selection tr {
    background: transparent !important;
}
.isr-wrapper table.selection th {
    display: none;
}
.isr-wrapper table.selection td {
    padding: 10px 4px;
    border: none !important;
    vertical-align: middle;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    color: #374151;
    font-weight: 500;
}
.isr-wrapper table.selection td:first-child {
    width: 220px;
    padding-right: 16px;
    white-space: nowrap;
    color: #4B5563;
}

/* Select inputs */
.isr-wrapper select,
.isr-wrapper table.selection select {
    width: 100%;
    max-width: 500px;
    height: 40px;
    padding: 0 36px 0 14px;
    border: 1.5px solid #D1D5DB;
    border-radius: 8px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    color: #1F2937;
    background: #fff 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") no-repeat right 12px center;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    cursor: pointer;
    transition: border-color 0.2s, box-shadow 0.2s;
    outline: none;
}
.isr-wrapper select:hover {
    border-color: #2AABB3;
}
.isr-wrapper select:focus {
    border-color: #2AABB3;
    box-shadow: 0 0 0 3px rgba(42,171,179,0.12);
}

/* Text inputs */
.isr-wrapper input[type="text"],
.isr-wrapper table.selection input[type="text"] {
    height: 40px;
    padding: 0 14px;
    border: 1.5px solid #D1D5DB;
    border-radius: 8px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    color: #1F2937;
    transition: border-color 0.2s, box-shadow 0.2s;
    outline: none;
    background: #fff;
}
.isr-wrapper input[type="text"]:hover {
    border-color: #2AABB3;
}
.isr-wrapper input[type="text"]:focus {
    border-color: #2AABB3;
    box-shadow: 0 0 0 3px rgba(42,171,179,0.12);
}

/* Textarea */
.isr-wrapper textarea {
    width: 100%;
    max-width: 500px;
    padding: 10px 14px;
    border: 1.5px solid #D1D5DB;
    border-radius: 8px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    color: #1F2937;
    resize: vertical;
    min-height: 100px;
    transition: border-color 0.2s, box-shadow 0.2s;
    outline: none;
}
.isr-wrapper textarea:hover { border-color: #2AABB3; }
.isr-wrapper textarea:focus {
    border-color: #2AABB3;
    box-shadow: 0 0 0 3px rgba(42,171,179,0.12);
}

/* Buttons */
.isr-wrapper input[type="submit"],
.isr-wrapper button[type="submit"] {
    height: 40px;
    padding: 0 24px;
    border: none;
    border-radius: 8px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
}
.isr-wrapper input[type="submit"][name="Update"],
.isr-wrapper input[type="submit"][name="Search"],
.isr-wrapper input[type="submit"][value*="Add to Requisition"] {
    background: linear-gradient(135deg, #2AABB3, #1E8F96);
    color: #fff;
    box-shadow: 0 2px 8px rgba(42,171,179,0.3);
}
.isr-wrapper input[type="submit"][name="Update"]:hover,
.isr-wrapper input[type="submit"][name="Search"]:hover,
.isr-wrapper input[type="submit"][value*="Add to Requisition"]:hover {
    background: linear-gradient(135deg, #1E8F96, #187278);
    box-shadow: 0 4px 16px rgba(42,171,179,0.4);
    transform: translateY(-1px);
}
.isr-wrapper input[type="submit"][name="Submit"] {
    background: linear-gradient(135deg, #52C41A, #3DAD0E);
    color: #fff;
    box-shadow: 0 2px 8px rgba(82,196,26,0.3);
    height: 44px;
    padding: 0 32px;
    font-size: 14px;
}
.isr-wrapper input[type="submit"][name="Submit"]:hover:not(:disabled) {
    background: linear-gradient(135deg, #3DAD0E, #2E9A00);
    transform: translateY(-1px);
}
.isr-wrapper input[type="submit"][name="Submit"]:disabled {
    background: #D1D5DB;
    color: #9CA3AF;
    box-shadow: none;
    cursor: not-allowed;
    transform: none;
}
.isr-wrapper input[type="submit"][name="Prev"],
.isr-wrapper input[type="submit"][name="Next"],
.isr-wrapper input[type="submit"][name="Previous"],
.isr-wrapper input[type="submit"][name="Go"],
.isr-wrapper input[type="submit"][name="Edit"] {
    background: #fff;
    color: #2AABB3;
    border: 1.5px solid #2AABB3;
}
.isr-wrapper input[type="submit"][name="Prev"]:hover,
.isr-wrapper input[type="submit"][name="Next"]:hover,
.isr-wrapper input[type="submit"][name="Previous"]:hover,
.isr-wrapper input[type="submit"][name="Go"]:hover,
.isr-wrapper input[type="submit"][name="Edit"]:hover {
    background: #E6F7F8;
}
.isr-wrapper input[type="submit"][name="Select"] {
    background: #F3F4F6;
    color: #2AABB3;
    border: 1px solid #E5E7EB;
    height: 34px;
    padding: 0 14px;
    font-size: 12px;
    font-weight: 600;
}
.isr-wrapper input[type="submit"][name="Select"]:hover {
    background: #E6F7F8;
    border-color: #2AABB3;
}

/* ── Disabled Submit Hint ── */
.isr-submit-hint {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: #9CA3AF;
    margin-left: 12px;
    font-style: italic;
}
.isr-submit-hint i { font-size: 13px; color: #FAAD14; }

/* ── Data Tables ── */
.isr-wrapper table.selection + br + table,
.isr-wrapper table.table1,
.isr-wrapper table[cellpadding="2"] {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    border-radius: 10px;
    overflow: hidden;
    border: 1px solid #E5E7EB;
}
.isr-wrapper table.table1 th,
.isr-wrapper table[cellpadding="2"] th {
    background: linear-gradient(135deg, #1E8F96, #2AABB3);
    color: #fff;
    font-weight: 600;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 12px 14px;
    text-align: left;
    font-family: 'Poppins', sans-serif;
    border: none !important;
    white-space: nowrap;
}
.isr-wrapper table.table1 td,
.isr-wrapper table[cellpadding="2"] td {
    padding: 10px 14px;
    font-size: 13px;
    font-family: 'Poppins', sans-serif;
    border-bottom: 1px solid #F0F0F0;
    color: #374151;
}
.isr-wrapper tr.EvenTableRows {
    background: #FAFBFC !important;
}
.isr-wrapper tr.OddTableRows {
    background: #fff !important;
}
.isr-wrapper tr.EvenTableRows:hover,
.isr-wrapper tr.OddTableRows:hover {
    background: #F0FAFB !important;
}

/* Line items table */
.isr-wrapper .line-items-table {
    width: 100%;
    border-collapse: separate;
    border-spacing: 0;
    border-radius: 10px;
    overflow: hidden;
    border: 1px solid #E5E7EB;
}
.isr-wrapper .line-items-table th {
    background: linear-gradient(135deg, #1E8F96, #2AABB3);
    color: #fff;
    font-weight: 600;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 12px 14px;
    text-align: left;
    font-family: 'Poppins', sans-serif;
    border: none;
}
.isr-wrapper .line-items-table td {
    padding: 10px 14px;
    font-size: 13px;
    border-bottom: 1px solid #F0F0F0;
    font-family: 'Poppins', sans-serif;
}
.isr-wrapper .line-items-table a {
    color: #2AABB3;
    text-decoration: none;
    font-weight: 500;
    padding: 4px 10px;
    border-radius: 6px;
    transition: background 0.2s;
}
.isr-wrapper .line-items-table a:hover {
    background: #E6F7F8;
}

/* Quantity input in results table */
.isr-wrapper input.number[type="text"] {
    width: 80px;
    text-align: center;
    height: 36px;
    font-weight: 600;
}

/* ── Message Styling ── */
.isr-wrapper .warn,
.isr-wrapper div[class*="msg"] {
    border-radius: 10px !important;
    font-family: 'Poppins', sans-serif !important;
    border: none !important;
    padding: 12px 18px !important;
    margin: 12px 0 !important;
}

/* ── Conditional Field Transitions ── */
#Jobno, #Customer, #Account, #ProductType, #Employee, #Patrol, #costglcode {
    transition: opacity 0.3s ease, max-height 0.3s ease;
}

/* ── Success alert ── */
.isr-success-box {
    background: linear-gradient(135deg, #F0FFF0, #E8F8E8);
    border: 1px solid #B7EB8F;
    border-left: 4px solid #52C41A;
    border-radius: 10px;
    padding: 20px 24px;
    margin: 20px 0;
}
.isr-success-box .req-no {
    font-size: 22px;
    font-weight: 700;
    color: #52C41A;
    margin: 8px 0;
}

/* ── Help text ── */
.isr-wrapper .page_help_text {
    background: #F0FAFB;
    border: 1px solid #D1EEF0;
    border-left: 4px solid #2AABB3;
    border-radius: 8px;
    padding: 12px 18px;
    font-size: 13px;
    color: #1E8F96;
    font-weight: 500;
}

/* ── Page Title Override ── */
.isr-wrapper .page_title_text {
    display: none;
}

/* ── Centre alignment ── */
.isr-wrapper .centre {
    text-align: center;
    padding: 16px 0;
}

/* ── Empty State ── */
.isr-empty-state {
    text-align: center;
    padding: 40px 20px;
    color: #9CA3AF;
}
.isr-empty-state i {
    font-size: 48px;
    color: #D1D5DB;
    margin-bottom: 12px;
}
.isr-empty-state p {
    font-size: 14px;
    margin: 0;
}

/* ── Step Indicator ── */
.isr-steps {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 0;
    margin-bottom: 24px;
}
.isr-step {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 10px 20px;
    font-size: 13px;
    font-weight: 500;
    color: #9CA3AF;
}
.isr-step.active {
    color: #2AABB3;
}
.isr-step.done {
    color: #52C41A;
}
.isr-step .step-num {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 700;
    font-size: 13px;
    border: 2px solid #E5E7EB;
    background: #fff;
}
.isr-step.active .step-num {
    border-color: #2AABB3;
    background: #2AABB3;
    color: #fff;
}
.isr-step.done .step-num {
    border-color: #52C41A;
    background: #52C41A;
    color: #fff;
}
.isr-step-line {
    width: 60px;
    height: 2px;
    background: #E5E7EB;
}
.isr-step-line.done {
    background: #52C41A;
}

/* ── Responsive ── */
@media (max-width: 1024px) {
    .isr-dashboard { grid-template-columns: repeat(2, 1fr); }
}
@media (max-width: 640px) {
    .isr-dashboard { grid-template-columns: 1fr; }
    .isr-banner { padding: 24px 20px; }
    .isr-banner h1 { font-size: 20px; }
    .isr-card-body { padding: 16px; }
    .isr-wrapper table.selection td:first-child { width: auto; display: block; }
    .isr-banner-actions { position: static; margin-top: 14px; }
    .isr-modal { width: 96vw; }
}
</style>

<div class="isr-wrapper">

<!-- ── Banner ── -->
<div class="isr-banner">
    <div class="isr-breadcrumb">
        <a href="index.php"><i class="fas fa-home"></i></a>
        <span class="sep">/</span>
        <a href="index.php">Inventory</a>
        <span class="sep">/</span>
        <span>Internal Stock Request</span>
    </div>
    <h1><i class="fas fa-boxes-stacked" style="margin-right:10px;opacity:0.9;"></i>Internal Stock Request</h1>
    <p>Create material requisitions for internal stock transfers, uniforms, consumables, and project jobs</p>
    <div class="isr-banner-actions">
        <button class="isr-help-btn" onclick="openHelpModal()">
            <i class="fas fa-circle-question"></i> How to Use
        </button>
    </div>
</div>

<!-- ── Help Modal ── -->
<div class="isr-modal-overlay" id="isrHelpModal">
    <div class="isr-modal">
        <div class="isr-modal-header">
            <h2><i class="fas fa-circle-question"></i> How to Create a Stock Request</h2>
            <button class="isr-modal-close" onclick="closeHelpModal()"><i class="fas fa-xmark"></i></button>
        </div>
        <div class="isr-modal-body">
            <div class="isr-help-step">
                <div class="isr-help-num">1</div>
                <div class="isr-help-content">
                    <h4>Fill in Request Details</h4>
                    <p>Select the <strong>Transaction Type</strong> (Small Jobs, Contract Jobs, Uniforms, or Consumables). Choose your <strong>Department</strong>, the <strong>Warehouse Location</strong> to request stock from, and set the <strong>Date Required</strong>. Additional fields will appear based on the transaction type selected.</p>
                </div>
            </div>
            <div class="isr-help-step">
                <div class="isr-help-num">2</div>
                <div class="isr-help-content">
                    <h4>Click &ldquo;Update Details&rdquo;</h4>
                    <p>Once you&rsquo;ve filled in the request information, click the <strong>Update Details</strong> button to save your selections. This unlocks the item search section below.</p>
                </div>
            </div>
            <div class="isr-help-step">
                <div class="isr-help-num">3</div>
                <div class="isr-help-content">
                    <h4>Search &amp; Add Items</h4>
                    <p>Use the <strong>Search Inventory</strong> section to find stock items. Choose a <strong>Stock Category</strong>, optionally filter by description or stock code, then click <strong>Search Now</strong>. In the results, enter the required quantity next to each item and click <strong>Add to Requisition</strong>.</p>
                </div>
            </div>
            <div class="isr-help-step">
                <div class="isr-help-num">4</div>
                <div class="isr-help-content">
                    <h4>Review &amp; Submit</h4>
                    <p>All added items appear in the <strong>Items Requested</strong> table. You can <strong>Edit</strong> quantities or <strong>Delete</strong> lines as needed. Once you have at least one item, the <strong>Submit Requisition</strong> button becomes active. Click it to submit your request for authorisation.</p>
                </div>
            </div>
            <div class="isr-help-step">
                <div class="isr-help-num">5</div>
                <div class="isr-help-content">
                    <h4>Authorisation</h4>
                    <p>After submission, your department authoriser will receive an email notification. They will review and approve or reject your request. You can track the status through the dashboard KPI cards at the top of this page.</p>
                </div>
            </div>

            <div class="isr-help-tip">
                <i class="fas fa-lightbulb"></i>
                <p><strong>Tip:</strong> The &ldquo;Available&rdquo; column in search results shows real-time stock availability (On Hand &minus; Demand + On Order). Check this before requesting large quantities. You can collapse the dashboard cards using the toggle to save screen space.</p>
            </div>
        </div>
        <div class="isr-modal-footer">
            <button onclick="closeHelpModal()">Got it, thanks!</button>
        </div>
    </div>
</div>

<?php
/* ── KPI Dashboard ── */
$userid = $_SESSION['UserID'];

$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'];

// Fetch KPI data
$kpi_pending = 0;
$kpi_approved = 0;
$kpi_total = 0;
$kpi_month = 0;

$kpiSQL = "SELECT
    COUNT(*) AS total_requests,
 SUM(CASE WHEN authorised = 0 OR authorised IS NULL THEN 1 ELSE 0 END) AS pending,
SUM(CASE WHEN authorised = 1 THEN 1 ELSE 0 END) AS approved,
    SUM(CASE WHEN despatchdate >= DATE_FORMAT(CURDATE(), '%Y-%m-01') THEN 1 ELSE 0 END) AS this_month
    FROM stockrequest
    WHERE initiator = '" . $realname . "'";
$kpiResult = DB_query($kpiSQL);
if ($kpiRow = DB_fetch_array($kpiResult)) {
    $kpi_total = isset($kpiRow['total_requests']) ? $kpiRow['total_requests'] : 0;
    $kpi_pending = isset($kpiRow['pending']) ? $kpiRow['pending'] : 0;
    $kpi_approved = isset($kpiRow['approved']) ? $kpiRow['approved'] : 0;
    $kpi_month = isset($kpiRow['this_month']) ? $kpiRow['this_month'] : 0;
}
?>

<!-- Dashboard Toggle -->
<div class="isr-dash-toggle" id="isrDashToggle" onclick="toggleDashboard()">
    <i class="fas fa-chevron-down"></i>
    <span>Dashboard Overview</span>
</div>

<div class="isr-dashboard-wrap" id="isrDashWrap">
    <div class="isr-dashboard">
        <div class="isr-kpi">
            <div class="isr-kpi-icon teal"><i class="fas fa-file-lines"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_total); ?></div>
            <div class="kpi-label">Total Requests</div>
        </div>
        <div class="isr-kpi" style="border-left-color:#FAAD14;">
            <div class="isr-kpi-icon orange"><i class="fas fa-clock"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_pending); ?></div>
            <div class="kpi-label">Pending Approval</div>
        </div>
        <div class="isr-kpi" style="border-left-color:#52C41A;">
            <div class="isr-kpi-icon green"><i class="fas fa-circle-check"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_approved); ?></div>
            <div class="kpi-label">Approved</div>
        </div>
        <div class="isr-kpi" style="border-left-color:#1890FF;">
            <div class="isr-kpi-icon blue"><i class="fas fa-calendar-day"></i></div>
            <div class="kpi-value"><?php echo number_format($kpi_month); ?></div>
            <div class="kpi-label">This Month</div>
        </div>
    </div>
</div>

<?php
// ── Process existing logic ──

if (isset($_GET['New'])) {
	unset($_SESSION['Transfer']);
	$_SESSION['Request'] = new StockRequest();
}

if (isset($_POST['Update'])) {
	$_SESSION['Request']->TransType=$_POST['TransType'];
	$_SESSION['Request']->Department=$_POST['Department'];
	$_SESSION['Request']->Location=$_POST['Location'] ;
	$_SESSION['Request']->DispatchDate=$_POST['DispatchDate'];
	$_SESSION['Request']->Jobno=$_POST['Jobno'];
	$_SESSION['Request']->Patrol=$_POST['Patrol'];
	$_SESSION['Request']->Client=$_POST['customer'];
	$_SESSION['Request']->Account=$_POST['account'];
	$_SESSION['Request']->ProductType=$_POST['ProductType'];
	$_SESSION['Request']->Narrative=$_POST['Narrative'];
	$_SESSION['Request']->Employee=$_POST['Employee'];
	$_SESSION['Request']->CostGLCode=$_POST['costglcode'];

	if ($_POST['Patrol'] == ''){
		$_SESSION['Request']->Patrol ='430';
	}
	if ($_POST['Jobno'] == ''){
		$_SESSION['Request']->Jobno ='0';
	}
	if ($_POST['account'] == ''){
		$_SESSION['Request']->Account ='0';
	}
}

if (isset($_POST['Edit'])) {
	$_SESSION['Request']->LineItems[$_POST['LineNumber']]->Quantity=$_POST['Quantity'];
}

if (isset($_GET['Delete'])) {
	unset($_SESSION['Request']->LineItems[$_GET['Delete']]);
	echo '<div style="background:#F0FFF0;border:1px solid #B7EB8F;border-left:4px solid #52C41A;border-radius:10px;padding:14px 20px;margin:12px 0;font-family:Poppins,sans-serif;font-size:13px;color:#389E0D;">';
	echo '<i class="fas fa-check-circle" style="margin-right:8px;"></i>' . _('The line was successfully deleted');
	echo '</div>';
}

foreach ($_POST as $key => $value) {
	if (mb_strstr($key,'StockID')) {
		$Index=mb_substr($key, 7);
		if (filter_number_format($_POST['Quantity'.$Index])>0) {
			$StockID=$value;
			$ItemDescription=$_POST['ItemDescription'.$Index];
			$DecimalPlaces=$_POST['DecimalPlaces'.$Index];
			$NewItem_array[$StockID] = filter_number_format($_POST['Quantity'.$Index]);
			$_POST['Units'.$StockID]=$_POST['Units'.$Index];
			$_SESSION['Request']->AddLine($StockID, $ItemDescription, $NewItem_array[$StockID], $_POST['Units'.$StockID], $DecimalPlaces);
		}
	}
}

if (isset($_POST['Submit'])) {
	DB_Txn_Begin();

	$RequestNo = GetNextTransNo(38, $db);
	$HeaderSQL="INSERT INTO stockrequest (dispatchid,
										loccode,
										departmentid,
										despatchdate,
										cost_glcode,
										jobno,
										patrollocation,
										transtype,
										client,
										account,
										producttype,
										employee,
										narrative,
										initiator)
									VALUES(
										'" . $RequestNo . "',
										'" . $_SESSION['Request']->Location . "',
										'" . $_SESSION['Request']->Department . "',
										'" . FormatDateForSQL($_SESSION['Request']->DispatchDate) . "',
										'" . $_SESSION['Request']->CostGLCode . "',
										'" . $_SESSION['Request']->Jobno . "',
										'" . $_SESSION['Request']->Patrol . "',
										'" . $_SESSION['Request']->TransType . "',
										'" . $_SESSION['Request']->Client . "',
										'" . $_SESSION['Request']->Account . "',
										'" . $_SESSION['Request']->ProductType . "',
										'" . $_SESSION['Request']->Employee. "',
										'" . $_SESSION['Request']->Narrative . "',
										'" . $realname . "')";
	$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The request header record could not be inserted because');
	$DbgMsg = _('The following SQL to insert the request header record was used');
	$Result = DB_query($HeaderSQL,$ErrMsg,$DbgMsg,true);

	$totalcost = 0;
	foreach ($_SESSION['Request']->LineItems as $LineItems) {
		$LineSQL="INSERT INTO stockrequestitems (dispatchitemsid,
												dispatchid,
												stockid,
												quantity,
												decimalplaces,
												uom)
											VALUES(
												'".$LineItems->LineNumber."',
												'".$RequestNo."',
												'".$LineItems->StockID."',
												'".$LineItems->Quantity."',
												'".$LineItems->DecimalPlaces."',
												'".$LineItems->UOM."')";
		$ErrMsg =_('CRITICAL ERROR') . '! ' . _('NOTE DOWN THIS ERROR AND SEEK ASSISTANCE') . ': ' . _('The request line record could not be inserted because');
		$DbgMsg = _('The following SQL to insert the request header record was used');
		$Result = DB_query($LineSQL,$ErrMsg,$DbgMsg,true);

		$EmailSQL="SELECT materialcost
				FROM stockmaster
				WHERE stockid = '" . $LineItems->StockID."'";
		$EmailResult = DB_query($EmailSQL);
		$myEmail=DB_fetch_array($EmailResult);
		$cost = $LineItems->Quantity * $myEmail['materialcost'];
		$totalcost = $totalcost + $cost;
	}

	$sql39 = "UPDATE stockrequest SET total_cost= '".$totalcost."'
						WHERE dispatchid= '" . $RequestNo . "'";
	$ErrMsg = _('The customer could not be updated because');
	$result39 = DB_query($sql39,$ErrMsg);

	$RequestID = $RequestID - 1;
	$SQL = "SELECT departmentid,initiator
			FROM stockrequest
			WHERE dispatchid='" . $RequestID. "'";
	$result = DB_query($SQL);
	$myrowuser = DB_fetch_array($result);
	if ($myrowuser) {
		$department = $myrowuser['departmentid'];
		$initiator = $myrowuser['initiator'];
	}

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

	$ravinesh ='rdeo@wormaldfj.com';
	$sharukh ='msharukh@wormaldfj.com';
	$sachin = 'sachinebusiness@gmail.com';

	$EmailSQL="SELECT email
				FROM www_users, department
				WHERE department.authoriser = www_users.userid
					AND department.departmentid = '" . $_SESSION['Request']->Department ."'";
	$EmailResult = DB_query($EmailSQL);
	if ($myEmail=DB_fetch_array($EmailResult)){
		$ConfirmationText = _('This internal stock request-'.$RequestNo.' has been created and is waiting for your authorization'. ' ' . _('by user') . ' ' . $userid . ' ' . _('at ') . ' ' . Date('d-m-Y H:i:s'). ' . You will need to go to the ERP and check this stock request number and approve or reject. Stock Request No: '.$RequestNo.'. Click here to go directly : "https://ebusinescloudservers.com/wormalderp/InternalStockRequestAuthorisation.php"');
		$ConfirmationText1 = $RequestNo._(' This internal stock request is created by you and is pending approval');
		$EmailSubject = _('Stock Request needs your authorization');

		$emailcc = 'sachinebusiness@gmail.com';

		$mail = new PHPMailer(true);
		$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($myEmail['email'], 'recipient ');
		$mail->isHTML(true);
		$mail->Subject = $EmailSubject;
		$mail->Body    = $ConfirmationText;
		$mail->send();
	}

	DB_Txn_Commit();

	echo '<div class="isr-success-box">';
	echo '<i class="fas fa-check-circle" style="color:#52C41A;font-size:24px;"></i>';
	echo '<p style="margin:8px 0 0;font-weight:600;color:#1F2937;">Material Requisition Submitted Successfully</p>';
	echo '<p style="margin:4px 0 0;font-size:13px;color:#6B7280;">' . _('The Material Requisition has been entered and now needs to be authorised so that transfer between warehouse and transfer to a job can take place') . '</p>';
	echo '<div class="req-no">Requisition No: '. $RequestNo . '</div>';
	echo '<a href="'. htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?New=Yes" style="display:inline-flex;align-items:center;gap:8px;margin-top:12px;padding:10px 24px;background:linear-gradient(135deg,#2AABB3,#1E8F96);color:#fff;border-radius:8px;text-decoration:none;font-weight:600;font-size:13px;"><i class="fas fa-plus"></i>' . _('Create Another Request') . '</a>';
	echo '</div>';
	include('includes/footer.inc');
	unset($_SESSION['Request']);
	exit;
}

// ── Step Indicators ──
$hasLocation = isset($_SESSION['Request']->Location) && $_SESSION['Request']->Location != '';
$hasLineItems = isset($_SESSION['Request']->LineItems) && count($_SESSION['Request']->LineItems) > 0;
?>

<!-- Step Progress -->
<div class="isr-steps">
    <div class="isr-step <?php echo $hasLocation ? 'done' : 'active'; ?>">
        <span class="step-num"><?php echo $hasLocation ? '<i class="fas fa-check" style="font-size:11px;"></i>' : '1'; ?></span>
        <span>Request Details</span>
    </div>
    <div class="isr-step-line <?php echo $hasLocation ? 'done' : ''; ?>"></div>
    <div class="isr-step <?php echo $hasLocation ? ($hasLineItems ? 'done' : 'active') : ''; ?>">
        <span class="step-num"><?php echo $hasLineItems ? '<i class="fas fa-check" style="font-size:11px;"></i>' : '2'; ?></span>
        <span>Add Items</span>
    </div>
    <div class="isr-step-line <?php echo $hasLineItems ? 'done' : ''; ?>"></div>
    <div class="isr-step <?php echo $hasLineItems ? 'active' : ''; ?>">
        <span class="step-num">3</span>
        <span>Submit</span>
    </div>
</div>

<?php
// ── Edit Line Form ──
if (isset($_GET['Edit'])) {
	echo '<div class="isr-card">';
	echo '<div class="isr-card-header"><i class="fas fa-pen-to-square"></i><div><h3>' . _('Edit Request Line') . '</h3><span class="subtitle">Modify the quantity for this line item</span></div></div>';
	echo '<div class="isr-card-body">';
	echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post">';
    echo '<div>';
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
	echo '<table class="selection">';
	echo '<tr>
			<td>' . _('Line Number') . '</td>
			<td><strong>' . $_SESSION['Request']->LineItems[$_GET['Edit']]->LineNumber . '</strong></td>
		</tr>
		<tr>
			<td>' . _('Stock Code') . '</td>
			<td><code style="background:#F3F4F6;padding:4px 12px;border-radius:6px;font-weight:600;color:#2AABB3;">' . $_SESSION['Request']->LineItems[$_GET['Edit']]->StockID . '</code></td>
		</tr>
		<tr>
			<td>' . _('Item Description') . '</td>
			<td>' . $_SESSION['Request']->LineItems[$_GET['Edit']]->ItemDescription . '</td>
		</tr>
		<tr>
			<td>' . _('Unit of Measure') . '</td>
			<td>' . $_SESSION['Request']->LineItems[$_GET['Edit']]->UOM . '</td>
		</tr>
		<tr>
			<td>' . _('Quantity Requested') . '</td>
			<td><input type="text" class="number" name="Quantity" value="' . locale_number_format($_SESSION['Request']->LineItems[$_GET['Edit']]->Quantity, $_SESSION['Request']->LineItems[$_GET['Edit']]->DecimalPlaces) . '" style="width:120px;" /></td>
		</tr>';
	echo '<input type="hidden" name="LineNumber" value="' . $_SESSION['Request']->LineItems[$_GET['Edit']]->LineNumber . '" />';
	echo '</table>';
	echo '<div class="centre">
			<input type="submit" name="Edit" value="' . _('Update Line') . '" />
		</div>
        </div>
		</form>';
	echo '</div></div>';
	include('includes/footer.inc');
	exit;
}

// ── Main Request Form ──
echo '<div class="isr-card">';
echo '<div class="isr-card-header"><i class="fas fa-clipboard-list"></i><div><h3>Request Details</h3><span class="subtitle">Fill in the stock requisition information</span></div></div>';
echo '<div class="isr-card-body">';

echo '<form action="'. htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

echo '<table class="selection">';

// Transaction Type
echo '<tr>
		<td><i class="fas fa-exchange-alt" style="color:#2AABB3;margin-right:6px;"></i>' . _('Transaction Type') . '</td>';
echo '<td><select name="TransType" id="TransType" required="required">';
if (isset($_SESSION['Request']->TransType)){
	echo '<option selected="True" value="' .$_SESSION['Request']->TransType. '">'. $_SESSION['Request']->TransType. '</option>';
	echo '<option value="SmallJobs">' . _('Small Jobs') .'</option>';
	echo '<option value="ContractJobs">' . _('Contract Jobs') .'</option>';
	echo '<option value="Consumables">' . _('Consumables') .'</option>';
} else {
	echo '<option value="">' . _('Select Transaction Type') . '</option>';
	echo '<option value="SmallJobs">' . _('Small Jobs') .'</option>';
	echo '<option value="ContractJobs">' . _('Contract Jobs') .'</option>';
	echo '<option value="Uniforms">' . _('Uniforms') .'</option>';
	echo '<option value="Consumables">' . _('Consumables') .'</option>';
}
echo '</select></td></tr>';

// Department - Keep all existing user-based logic
echo '<tr>
		<td><i class="fas fa-building" style="color:#2AABB3;margin-right:6px;"></i>' . _('Department') . '</td>';
echo '<td><select name="Department" required="required">';

if ($userid =='nisha'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 7";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='schand' || $userid =='stephanie' || $userid =='waqa'|| $userid =='manueli'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 6";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='lusi' || $userid =='riaz'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 9 OR departmentid = 10";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='mosheed' || $userid =='ronil'||$userid =='roneelp'||$userid =='saula'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 2";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='rowen' || $userid =='rramlu'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 8 or departmentid = 21";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='ragnesh'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 3";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='ilimo' ||$userid =='annie' || $userid =='salata' ||$userid =='sera'||$userid =='semi'|| $userid =='jokaveti'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 1";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='mere' || $userid =='crispus' || $userid =='lina'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 9 or departmentid = 10";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='mkhan' ||$userid =='walesi'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 22";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='serge' ||$userid =='ranjeeta'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 18";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='sureta' ||$userid =='mereseini' ||$userid =='mere'){
	$SQL = "SELECT departmentid, departmentname FROM department where departmentid = 11";
	$result=DB_query($SQL);
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
} elseif ($userid =='admin' || $userid =='ravinesh' || $userid =='rtaito' || $userid =='eseta' || $userid =='shiv'|| $userid =='sharukh') {
	$SQL = "SELECT departmentid, departmentname FROM department";
	$result=DB_query($SQL);
	echo '<option value="0"> ' . _('Choose Department') . '</option>';
	while ($myrow=DB_fetch_array($result)){
		if (isset($_SESSION['Request']->Department) AND $_SESSION['Request']->Department==$myrow['departmentid']){
			echo '<option selected="True" value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		} else {
			echo '<option value="' . $myrow['departmentid'] . '">' . htmlspecialchars($myrow['departmentname'], ENT_QUOTES,'UTF-8') . '</option>';
		}
	}
}

echo '</select></td></tr>';

// Cost GL Code
echo '<tr id="costglcode_row">
		<td><i class="fas fa-calculator" style="color:#2AABB3;margin-right:6px;"></i>' . _('Choose Cost GL') . '</td>';
$sql="SELECT name, oldglcode FROM oldglcode
	WHERE category = 'Direct Cost - General Expense'
	OR category = 'Direct Cost - Labor Cost'
	OR category = 'Direct Cost - Staff Cost'
	OR category = 'Direct Cost- Consumable'";
$result=DB_query($sql);
echo '<td><select name="costglcode" id="costglcode">
		<option value="0">' . _('Select a cost GL Code') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_SESSION['Request']->CostGLCode) AND $_SESSION['Request']->CostGLCode==$myrow['oldglcode']){
		echo '<option selected="True" value="' . $myrow['oldglcode'] . '">' . $myrow['oldglcode'].' - ' .htmlspecialchars($myrow['name'], ENT_QUOTES,'UTF-8') . '</option>';
	} else {
		echo '<option value="' . $myrow['oldglcode'] . '">' . $myrow['oldglcode'].' - ' .htmlspecialchars($myrow['name'], ENT_QUOTES,'UTF-8') . '</option>';
	}
}
echo '</select></td></tr>';

// Location
echo '<tr>
		<td><i class="fas fa-warehouse" style="color:#2AABB3;margin-right:6px;"></i>' . _('Request Stock From') . '</td>';
$sql="SELECT locations.loccode, locationname
	FROM locations
	INNER JOIN locationusers ON locationusers.loccode=locations.loccode AND locationusers.userid='" .  $_SESSION['UserID'] . "' AND locationusers.canupd=1
	WHERE internalrequest = 1
	ORDER BY loccode ASC";
$result=DB_query($sql);
echo '<td><select name="Location" required="required">
		<option value="">' . _('Select a Location') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_SESSION['Request']->Location) AND $_SESSION['Request']->Location==$myrow['loccode']){
		echo '<option selected="True" value="' . $myrow['loccode'] . '">' . $myrow['loccode'].' - ' .htmlspecialchars($myrow['locationname'], ENT_QUOTES,'UTF-8') . '</option>';
	} else {
		echo '<option value="' . $myrow['loccode'] . '">' . $myrow['loccode'].' - ' .htmlspecialchars($myrow['locationname'], ENT_QUOTES,'UTF-8') . '</option>';
	}
}
echo '</select></td></tr>';

// Date
echo '<tr>
		<td><i class="fas fa-calendar" style="color:#2AABB3;margin-right:6px;"></i>' . _('Date Required') . '</td>';
echo '<td><input type="text" class="date" alt="'.$_SESSION['DefaultDateFormat'].'" name="DispatchDate" maxlength="10" size="11" value="' . $_SESSION['Request']->DispatchDate . '" style="width:180px;" /></td></tr>';

// Job No
echo '<tr id="Jobno_row">
		<td><i class="fas fa-briefcase" style="color:#2AABB3;margin-right:6px;"></i>' . _('Project / Job No') . '</td>';
$sql="SELECT projectid, project_name, wip_expense FROM projectdetails";
$result=DB_query($sql);
echo '<td><select name="Jobno" id="Jobno">
		<option value="">' . _('Select a project/jobno') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_SESSION['Request']->Jobno) AND $_SESSION['Request']->Jobno==$myrow['projectid']){
		echo '<option selected="True" value="' . $myrow['projectid'] . '">' . htmlspecialchars($myrow['project_name']).' - ' .htmlspecialchars($myrow['wip_expense'].' - '.$myrow['projectid'], ENT_QUOTES,'UTF-8') . '</option>';
	} else {
		echo '<option value="' . $myrow['projectid'] . '">' . htmlspecialchars($myrow['project_name']).' - ' .htmlspecialchars($myrow['wip_expense'].' - '.$myrow['projectid'], ENT_QUOTES,'UTF-8') . '</option>';
	}
}
echo '</select></td></tr>';

// Patrol Location
echo '<tr id="Patrol_row">
		<td><i class="fas fa-map-marker-alt" style="color:#2AABB3;margin-right:6px;"></i>' . _('Patrol / Client Site') . '</td>';
echo '<td><select name="Patrol" id="Patrol">';
$SQL = "SELECT clientid, patrollocation FROM guardforceclient";
$result=DB_query($SQL);
echo '<option value="0">' . _('Choose patrol client location') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_SESSION['Request']->Patrol) AND $_SESSION['Request']->Patrol==$myrow['clientid']){
		echo '<option selected="True" value="' . $myrow['clientid'] . '">' . htmlspecialchars($myrow['patrollocation'], ENT_QUOTES,'UTF-8').'-'.$myrow['clientid']  .'</option>';
	} else {
		echo '<option value="' . $myrow['clientid'] . '">' . htmlspecialchars($myrow['patrollocation'], ENT_QUOTES,'UTF-8').' - ' .$myrow['clientid'] .'</option>';
	}
}
echo '</select></td></tr>';

// Customer
echo '<tr id="Customer_row">
		<td><i class="fas fa-user-tie" style="color:#2AABB3;margin-right:6px;"></i>' . _('Customer') . '</td>';
echo '<td><select name="customer" id="Customer">';
$SQL = "SELECT debtorno, name FROM debtorsmaster";
$result=DB_query($SQL);
echo '<option value="0">' . _('Choose Customer') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_SESSION['Request']->Client) AND $_SESSION['Request']->Client==$myrow['debtorno']){
		echo '<option selected="True" value="' . $myrow['debtorno'] . '">' . htmlspecialchars($myrow['name'], ENT_QUOTES,'UTF-8').'-'.$myrow['debtorno']  .'</option>';
	} else {
		echo '<option value="' . $myrow['debtorno'] . '">' . htmlspecialchars($myrow['name'], ENT_QUOTES,'UTF-8').' - ' .$myrow['debtorno'] .'</option>';
	}
}
echo '</select></td></tr>';

// Account Number
echo '<tr id="Account_row">
		<td><i class="fas fa-hashtag" style="color:#2AABB3;margin-right:6px;"></i>' . _('Account Number') . '</td>';
echo '<td><select name="account" id="Account" placeholder="Account Number">';
echo '</select></td></tr>';

// Product Type
echo '<tr id="ProductType_row">
		<td><i class="fas fa-tags" style="color:#2AABB3;margin-right:6px;"></i>' . _('Product Type') . '</td>';
echo '<td><select name="ProductType" id="ProductType">';
$SQL = "SELECT accountcode, accountname FROM chartmaster where group_ ='Sales'";
$result=DB_query($SQL);
echo '<option value="0">' . _('Choose Sales Category') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_POST['salesgl']) AND $_POST['salesgl']==$myrow['accountcode']){
		echo '<option selected="selected" value="' . $myrow['accountcode'] . '">' . $myrow['accountname'].' - ' .$myrow['accountcode']  .'</option>';
	} else {
		echo '<option value="' . $myrow['accountcode'] . '">' . $myrow['accountname'].' - ' .$myrow['accountcode'] .'</option>';
	}
}
echo '</select></td></tr>';

// Employee
echo '<tr id="Employee_row">
		<td><i class="fas fa-id-badge" style="color:#2AABB3;margin-right:6px;"></i>' . _('Employee') . '</td>';
echo '<td><select name="Employee" id="Employee">';
$SQL = "SELECT employeeid, first_name, middle_name, last_name FROM employeemaster";
$result=DB_query($SQL);
echo '<option value="0">' . _('Choose employee') . '</option>';
while ($myrow=DB_fetch_array($result)){
	if (isset($_SESSION['Request']->Employee) AND $_SESSION['Request']->Employee==$myrow['employeeid']){
		echo '<option selected="True" value="' . $myrow['employeeid'] . '">' . $myrow['first_name'].'-'. $myrow['last_name'].'-'.$myrow['employeeid']  .'</option>';
	} else {
		echo '<option value="' . $myrow['employeeid'] . '">' .  $myrow['first_name'].'-'. $myrow['last_name'].' - ' .$myrow['employeeid'] .'</option>';
	}
}
echo '</select></td></tr>';

// Narrative
echo '<tr>
		<td style="vertical-align:top;padding-top:14px;"><i class="fas fa-comment-dots" style="color:#2AABB3;margin-right:6px;"></i>' . _('Narrative') . '</td>
		<td><textarea name="Narrative" cols="30" rows="5">' . $_SESSION['Request']->Narrative . '</textarea></td>
	</tr>';

echo '</table>';

echo '<div class="centre">
		<input type="submit" name="Update" value="' . _('Update Details') . '" />
	</div>
    </div>
	</form>';
echo '</div></div>';  // close card-body and card

if (!isset($_SESSION['Request']->Location)) {
	echo '</div>'; // close wrapper
	include('includes/footer.inc');
	exit;
}

// ── Line Items Table ──
$i = 0;
$lineItemCount = isset($_SESSION['Request']->LineItems) ? count($_SESSION['Request']->LineItems) : 0;

echo '<div class="isr-card">';
echo '<div class="isr-card-header"><i class="fas fa-list-check"></i><div><h3>Items Requested</h3><span class="subtitle">Review and manage requested items</span></div></div>';
echo '<div class="isr-card-body">';

echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

if ($lineItemCount > 0) {
	echo '<table class="line-items-table">
	<tr>
		<th>' .  _('Line #') . '</th>
		<th>' .  _('Item Code') . '</th>
		<th>' .  _('Description'). '</th>
		<th>' .  _('Qty Required'). '</th>
		<th>' .  _('UOM'). '</th>
		<th>' .  _('Actions'). '</th>
	</tr>';

	$k=0;
	foreach ($_SESSION['Request']->LineItems as $LineItems) {
		$bgClass = ($k==1) ? 'EvenTableRows' : 'OddTableRows';
		$k = ($k==1) ? 0 : 1;
		echo '<tr class="'.$bgClass.'">
				<td><span style="background:#E6F7F8;color:#1E8F96;padding:2px 10px;border-radius:12px;font-weight:600;font-size:12px;">' . $LineItems->LineNumber . '</span></td>
				<td><code style="background:#F3F4F6;padding:3px 10px;border-radius:6px;font-weight:600;color:#2AABB3;font-size:12px;">' . $LineItems->StockID . '</code></td>
				<td>' . $LineItems->ItemDescription . '</td>
				<td class="number" style="font-weight:700;">' . locale_number_format($LineItems->Quantity, $LineItems->DecimalPlaces) . '</td>
				<td>' . $LineItems->UOM . '</td>
				<td>
					<a href="'. htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?Edit='.$LineItems->LineNumber.'"><i class="fas fa-pen" style="margin-right:4px;font-size:11px;"></i>' . _('Edit') . '</a>
					<a href="'. htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '?Delete='.$LineItems->LineNumber.'" style="color:#FF4D4F;margin-left:8px;"><i class="fas fa-trash" style="margin-right:4px;font-size:11px;"></i>' . _('Delete') . '</a>
				</td>
			</tr>';
	}
	echo '</table>';
} else {
	echo '<div class="isr-empty-state">';
	echo '<i class="fas fa-inbox"></i>';
	echo '<p>No items added yet. Search for stock items below to add them.</p>';
	echo '</div>';
}

echo '<div class="centre">';
if ($lineItemCount > 0) {
	echo '<input type="submit" name="Submit" value="' . _('Submit Requisition') . '" />';
} else {
	echo '<input type="submit" name="Submit" value="' . _('Submit Requisition') . '" disabled="disabled" />';
	echo '<span class="isr-submit-hint"><i class="fas fa-info-circle"></i>Add at least one item before submitting</span>';
}
echo '</div>
    </div>
    </form>';
echo '</div></div>'; // close card

// ── Stock Search ──
echo '<div class="isr-card">';
echo '<div class="isr-card-header"><i class="fas fa-search"></i><div><h3>Search Inventory</h3><span class="subtitle">Find and add items to your requisition</span></div></div>';
echo '<div class="isr-card-body">';

echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post">';
echo '<div>';
echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';

// Category selection based on user permissions
if ($userid == 'schand' || $userid == 'stephanie' || $userid == 'waqa'|| $userid == 'nisha'|| $userid =='manueli' ){
	$SQL = "SELECT stockcategory.categoryid, stockcategory.categorydescription
			FROM stockcategory
			WHERE stockcategory.categoryid='FIRE'
			OR stockcategory.categoryid='CON'
			OR stockcategory.categoryid='SEC'
			ORDER BY stockcategory.categorydescription";
} elseif ($userid == 'lusi' || $userid == 'manueli' || $userid == 'lina' || $userid == 'crispus' || $userid == 'mere' || $userid =='riaz'){
	$SQL = "SELECT stockcategory.categoryid, stockcategory.categorydescription
			FROM stockcategory
			WHERE stockcategory.categoryid='SEC'
			OR stockcategory.categoryid='CON'
			OR stockcategory.categoryid='M'
			ORDER BY stockcategory.categorydescription";
} elseif ($userid == 'ilimo' ||$userid =='semi'|| $userid =='jokaveti'){
	$SQL = "SELECT stockcategory.categoryid, stockcategory.categorydescription
			FROM stockcategory
			WHERE stockcategory.categoryid='CON'
			OR stockcategory.categoryid='OFFICE'
			ORDER BY stockcategory.categorydescription";
} else {
	$SQL = "SELECT stockcategory.categoryid, stockcategory.categorydescription
			FROM stockcategory
			WHERE stockcategory.categoryid='SEC'
			OR stockcategory.categoryid='FIRE'
			OR stockcategory.categoryid='CON'
			OR stockcategory.categoryid='OFFICE'
			OR stockcategory.categoryid='M'
			ORDER BY stockcategory.categorydescription";
}

$result1 = DB_query($SQL);
if (!isset($_POST['StockCat'])) { $_POST['StockCat'] = ''; }

echo '<table class="selection">
	<tr>
		<td><i class="fas fa-layer-group" style="color:#2AABB3;margin-right:6px;"></i>' . _('Stock Category') . '</td>
		<td><select name="StockCat">';
while ($myrow1 = DB_fetch_array($result1)) {
	if ($myrow1['categoryid'] == $_POST['StockCat']) {
		echo '<option selected="True" value="' . $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
	} else {
		echo '<option value="' . $myrow1['categoryid'] . '">' . $myrow1['categorydescription'] . '</option>';
	}
}
echo '</select></td></tr>';

echo '<tr>
		<td><i class="fas fa-font" style="color:#2AABB3;margin-right:6px;"></i>' . _('Search by Description') . '</td>';
if (isset($_POST['Keywords'])) {
	echo '<td><input type="text" name="Keywords" value="' . $_POST['Keywords'] . '" size="35" maxlength="35" placeholder="Enter partial description..." /></td>';
} else {
	echo '<td><input type="text" name="Keywords" size="35" maxlength="35" placeholder="Enter partial description..." /></td>';
}
echo '</tr>';

echo '<tr>
		<td><i class="fas fa-barcode" style="color:#2AABB3;margin-right:6px;"></i><b>' . _('OR') . '</b> ' . _('Stock Code') . '</td>';
if (isset($_POST['StockCode'])) {
	echo '<td><input type="text" autofocus="autofocus" name="StockCode" value="' . $_POST['StockCode'] . '" size="35" maxlength="35" placeholder="Enter stock code..." /></td>';
} else {
	echo '<td><input type="text" name="StockCode" size="35" maxlength="35" placeholder="Enter stock code..." /></td>';
}
echo '</tr></table>';

echo '<div class="centre">
		<input type="submit" name="Search" value="' . _('Search Now') . '" />
	</div>
    </div>
	</form>';
echo '</div></div>'; // close search card

// ── Search Results ──
if (isset($_POST['Search']) or isset($_POST['Next']) or isset($_POST['Prev'])){
	if ($_POST['Keywords']!='' AND $_POST['StockCode']=='') {
		echo '<div style="background:#FFF4E6;border:1px solid #FFD591;border-left:4px solid #FAAD14;border-radius:10px;padding:12px 18px;margin:12px 0;font-size:13px;color:#AD6800;font-family:Poppins,sans-serif;"><i class="fas fa-info-circle" style="margin-right:8px;"></i>' . _('Searching by item description') . '</div>';
	} elseif ($_POST['StockCode']!='' AND $_POST['Keywords']=='') {
		echo '<div style="background:#FFF4E6;border:1px solid #FFD591;border-left:4px solid #FAAD14;border-radius:10px;padding:12px 18px;margin:12px 0;font-size:13px;color:#AD6800;font-family:Poppins,sans-serif;"><i class="fas fa-info-circle" style="margin-right:8px;"></i>' . _('Searching by stock code') . '</div>';
	} elseif ($_POST['Keywords']=='' AND $_POST['StockCode']=='') {
		echo '<div style="background:#FFF4E6;border:1px solid #FFD591;border-left:4px solid #FAAD14;border-radius:10px;padding:12px 18px;margin:12px 0;font-size:13px;color:#AD6800;font-family:Poppins,sans-serif;"><i class="fas fa-info-circle" style="margin-right:8px;"></i>' . _('Searching by stock category') . '</div>';
	}

	if (isset($_POST['Keywords']) AND mb_strlen($_POST['Keywords'])>0) {
		$SearchString = '%' . str_replace(' ', '%', $_POST['Keywords']) . '%';
		$SQL = "SELECT stockmaster.stockid, stockmaster.description, stockmaster.units as stockunits, stockmaster.decimalplaces
				FROM stockmaster
				WHERE stockmaster.discontinued=0
					AND stockmaster.description " . LIKE . " '" . $SearchString . "'
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
				ORDER BY stockmaster.stockid";
	} elseif (mb_strlen($_POST['StockCode'])>0){
		$SearchString = '%' . $_POST['StockCode'] . '%';
		$SQL = "SELECT stockmaster.stockid, stockmaster.description, stockmaster.units as stockunits, stockmaster.decimalplaces
				FROM stockmaster
				WHERE stockmaster.discontinued=0
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
					AND stockmaster.stockid='" . $_POST['StockCode'] . "'
				ORDER BY stockmaster.stockid";
	} else {
		$SQL = "SELECT stockmaster.stockid, stockmaster.description, stockmaster.units as stockunits, stockmaster.decimalplaces
				FROM stockmaster
				WHERE stockmaster.discontinued=0
					AND stockmaster.categoryid='" . $_POST['StockCat'] . "'
				ORDER BY stockmaster.stockid";
	}

	if (isset($_POST['Next'])) { $Offset = $_POST['NextList']; }
	if (isset($_POST['Prev'])) { $Offset = $_POST['Previous']; }
	if (!isset($Offset) or $Offset<0) { $Offset=0; }

	$SQL = $SQL . ' LIMIT ' . $_SESSION['DefaultDisplayRecordsMax'] . ' OFFSET ' . ($_SESSION['DefaultDisplayRecordsMax']*$Offset);

	$ErrMsg = _('There is a problem selecting the part records to display because');
	$DbgMsg = _('The SQL used to get the part selection was');
	$SearchResult = DB_query($SQL,$ErrMsg, $DbgMsg);

	if (DB_num_rows($SearchResult)==0){
		echo '<div style="background:#FFF1F0;border:1px solid #FFA39E;border-left:4px solid #FF4D4F;border-radius:10px;padding:12px 18px;margin:12px 0;font-size:13px;color:#CF1322;font-family:Poppins,sans-serif;"><i class="fas fa-exclamation-circle" style="margin-right:8px;"></i>' . _('No products found matching the criteria') . '</div>';
	}
	if (DB_num_rows($SearchResult)<$_SESSION['DisplayRecordsMax']){
		$Offset=0;
	}
}

// ── Display Search Results with stock availability ──
if (isset($SearchResult) && DB_num_rows($SearchResult) > 0) {
	$j = 1;

	echo '<div class="isr-card">';
	echo '<div class="isr-card-header"><i class="fas fa-boxes-packing"></i><div><h3>Search Results</h3><span class="subtitle">Enter quantities and add items to your requisition</span></div></div>';
	echo '<div class="isr-card-body">';

	echo '<form action="' . htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES, 'UTF-8') . '" method="post" id="orderform">';
	echo '<div>';
	echo '<input type="hidden" name="FormID" value="' . $_SESSION['FormID'] . '" />';
	echo '<table class="table1">
	<tr>
		<td>
			<input type="hidden" name="Previous" value="'.($Offset-1).'" />
			<input tabindex="'.($j+8).'" type="submit" name="Prev" value="'._('Prev').'" /></td>
		<td style="text-align:center" colspan="6">
			<input type="hidden" name="order_items" value="1" />
			<input tabindex="'.($j+9).'" type="submit" value="'._('Add to Requisition').'" /></td>
		<td>
			<input type="hidden" name="NextList" value="'.($Offset+1).'" />
			<input tabindex="'.($j+10).'" type="submit" name="Next" value="'._('Next').'" /></td>
	</tr>
	<tr>
		<th>' . _('Code') . '</th>
		<th>' . _('Description') . '</th>
		<th>' . _('Units') . '</th>
		<th>' . _('On Hand') . '</th>
		<th>' . _('Demand') . '</th>
		<th>' . _('On Order') . '</th>
		<th>' . _('Available') . '</th>
		<th>' . _('Quantity') . '</th>
	</tr>';

	$k=0;
	$i=0;
	while ($myrow=DB_fetch_array($SearchResult)) {
		if ($myrow['decimalplaces']=='') {
			$DecimalPlacesSQL="SELECT decimalplaces FROM stockmaster WHERE stockid='" .$myrow['stockid'] . "'";
			$DecimalPlacesResult = DB_query($DecimalPlacesSQL);
			$DecimalPlacesRow = DB_fetch_array($DecimalPlacesResult);
			$DecimalPlaces = $DecimalPlacesRow['decimalplaces'];
		} else {
			$DecimalPlaces=$myrow['decimalplaces'];
		}

		$QOHSQL = "SELECT sum(locstock.quantity) AS qoh FROM locstock
					WHERE locstock.stockid='" .$myrow['stockid'] . "' AND
					loccode = '" . $_SESSION['Request']->Location . "'";
		$QOHResult =  DB_query($QOHSQL);
		$QOHRow = DB_fetch_array($QOHResult);
		$QOH = $QOHRow['qoh'];

		$sql = "SELECT SUM(salesorderdetails.quantity-salesorderdetails.qtyinvoiced) AS dem
				FROM salesorderdetails INNER JOIN salesorders
				ON salesorders.orderno = salesorderdetails.orderno
				WHERE salesorders.fromstkloc='" . $_SESSION['Request']->Location . "'
				AND salesorderdetails.completed=0
				AND salesorders.quotation=0
				AND salesorderdetails.stkcode='" . $myrow['stockid'] . "'";
		$ErrMsg = _('The demand for this product cannot be retrieved because');
		$DemandResult = DB_query($sql,$ErrMsg);
		$DemandRow = DB_fetch_row($DemandResult);
		$DemandQty = ($DemandRow[0] != null) ? $DemandRow[0] : 0;

		$sql = "SELECT SUM(purchorderdetails.quantityord-purchorderdetails.quantityrecd)*purchorderdetails.conversionfactor AS dem
				FROM purchorderdetails LEFT JOIN purchorders
				ON purchorderdetails.orderno=purchorders.orderno
				WHERE purchorderdetails.completed=0
				AND purchorders.status<>'Cancelled'
				AND purchorders.status<>'Rejected'
				AND purchorders.status<>'Completed'
				AND purchorderdetails.itemcode='" . $myrow['stockid'] . "'";
		$ErrMsg = _('The order details for this product cannot be retrieved because');
		$PurchResult = DB_query($sql,$ErrMsg);
		$PurchRow = DB_fetch_row($PurchResult);
		$PurchQty = ($PurchRow[0]!=null) ? $PurchRow[0] : 0;

		$sql = "SELECT SUM(woitems.qtyreqd - woitems.qtyrecd) AS dedm
				FROM woitems
				WHERE stockid='" . $myrow['stockid'] ."'";
		$ErrMsg = _('The order details for this product cannot be retrieved because');
		$WoResult = DB_query($sql,$ErrMsg);
		$WoRow = DB_fetch_row($WoResult);
		$WoQty = ($WoRow[0]!=null) ? $WoRow[0] : 0;

		$bgClass = ($k==1) ? 'EvenTableRows' : 'OddTableRows';
		$k = ($k==1) ? 0 : 1;

		$OnOrder = $PurchQty + $WoQty;
		$Available = $QOH - $DemandQty + $OnOrder;

		$availColor = ($Available > 0) ? '#52C41A' : '#FF4D4F';

		echo '<tr class="'.$bgClass.'">
			<td><code style="background:#F3F4F6;padding:3px 10px;border-radius:6px;font-weight:600;color:#2AABB3;font-size:12px;">' . $myrow['stockid'] . '</code></td>
			<td>' . $myrow['description'] . '</td>
			<td>' . $myrow['stockunits'] . '</td>
			<td class="number">' . locale_number_format($QOH,$DecimalPlaces) . '</td>
			<td class="number">' . locale_number_format($DemandQty,$DecimalPlaces) . '</td>
			<td class="number">' . locale_number_format($OnOrder, $DecimalPlaces) . '</td>
			<td class="number" style="font-weight:700;color:'.$availColor.';">' . locale_number_format($Available,$DecimalPlaces) . '</td>
			<td><input class="number" ' . ($i==0 ? 'autofocus="autofocus"':'') . ' tabindex="'.($j+7).'" type="text" size="6" name="Quantity'.$i.'" value="0" />
			<input type="hidden" name="StockID'.$i.'" value="'.$myrow['stockid'].'" />
			</td>
		</tr>';
		echo '<input type="hidden" name="DecimalPlaces'.$i.'" value="' . $myrow['decimalplaces'] . '" />';
		echo '<input type="hidden" name="ItemDescription'.$i.'" value="' . $myrow['description'] . '" />';
		echo '<input type="hidden" name="Units'.$i.'" value="' . $myrow['stockunits'] . '" />';
		$i++;
	}

	echo '<tr>
			<td><input type="hidden" name="Previous" value="'.($Offset-1).'" />
				<input tabindex="'.($j+7).'" type="submit" name="Prev" value="'._('Prev').'" /></td>
			<td style="text-align:center" colspan="6"><input type="hidden" name="order_items" value="1" />
				<input tabindex="'.($j+8).'" type="submit" value="'._('Add to Requisition').'" /></td>
			<td><input type="hidden" name="NextList" value="'.($Offset+1).'" />
				<input tabindex="'.($j+9).'" type="submit" name="Next" value="'._('Next').'" /></td>
		</tr>';

	echo '</table></div></form>';
	echo '</div></div>'; // close results card
}

echo '</div>'; // close isr-wrapper
?>

<!-- ── JavaScript: Field Visibility, Dashboard Toggle & Help Modal ── -->
<script>
// Help Modal
function openHelpModal() {
	document.getElementById('isrHelpModal').classList.add('active');
	document.body.style.overflow = 'hidden';
}
function closeHelpModal() {
	document.getElementById('isrHelpModal').classList.remove('active');
	document.body.style.overflow = '';
}
// Close on overlay click
document.getElementById('isrHelpModal').addEventListener('click', function(e) {
	if (e.target === this) closeHelpModal();
});
// Close on Escape key
document.addEventListener('keydown', function(e) {
	if (e.key === 'Escape') closeHelpModal();
});

$(document).ready(function(){

	// Customer/Account AJAX (preserve existing logic)
	$("select[name='customer']").change(function(){
		var debtorno = $(this).val();
		var userid = '<?php echo $userid; ?>';

		// User-department mapping
		var deptMap = {
			'schand':   {department:6, depart:0},
			'manueli':  {department:6, depart:0},
			'stephanie':{department:6, depart:0},
			'waqa':     {department:6, depart:0},
			'nisha':    {department:7, depart:0},
			'lusi':     {department:9, depart:10},
			'riaz':     {department:9, depart:10},
			'serge':    {department:18, depart:10},
			'vani':     {department:2, depart:0},
			'roneelp':  {department:2, depart:0},
			'ronil':    {department:2, depart:0},
			'saula':    {department:2, depart:0},
			'ilimo':    {department:1, depart:0},
			'jokaveti': {department:1, depart:0},
			'semi':     {department:1, depart:0},
			'rramlu':   {department:8, depart:21},
			'rowen':    {department:8, depart:21},
			'ragnesh':  {department:3, depart:0},
			'mkhan':    {department:22, depart:0},
			'walesi':   {department:22, depart:0},
			'sera':     {department:1, depart:0},
			'salata':   {department:1, depart:0},
			'annie':    {department:1, depart:0},
			'mere':     {department:11, depart:0},
			'lina':     {department:9, depart:10},
			'crispus':  {department:9, depart:10},
			'sureta':   {department:11, depart:0},
			'mereseini':{department:11, depart:0}
		};

		var userDept = deptMap[userid] || {department:0, depart:0};

		if(debtorno) {
			$.ajax({
				url: "invoice/accountnumber.php",
				dataType: 'Json',
				data: {'id':debtorno, 'department':userDept.department, 'depart':userDept.depart},
				success: function(data) {
					$('select[name="account"]').empty();
					$.each(data, function(key, value) {
						$('select[name="account"]').append('<option value="'+ key +'">'+ value +'</option>');
					});
				}
			});
		} else {
			$('select[name="account"]').empty();
		}
	});

	// Conditional field visibility with smooth transitions
	var $jobRow = $('#Jobno_row, #Jobno');
	var $custRow = $('#Customer_row, #Customer');
	var $acctRow = $('#Account_row, #Account');
	var $prodRow = $('#ProductType_row, #ProductType');
	var $empRow = $('#Employee_row, #Employee');
	var $patrolRow = $('#Patrol_row, #Patrol');
	var $costRow = $('#costglcode_row, #costglcode');

	function hideAllConditional() {
		$jobRow.closest('tr').hide();
		$custRow.closest('tr').hide();
		$acctRow.closest('tr').hide();
		$prodRow.closest('tr').hide();
		$empRow.closest('tr').hide();
		$patrolRow.closest('tr').hide();
		$costRow.closest('tr').hide();
	}

	hideAllConditional();

	$('#TransType').change(function(){
		var val = $(this).val();
		hideAllConditional();

		if (val == 'SmallJobs') {
			$costRow.closest('tr').fadeIn(300);
			$custRow.closest('tr').fadeIn(300);
			$acctRow.closest('tr').fadeIn(300);
			$prodRow.closest('tr').fadeIn(300);
		} else if (val == 'Uniforms') {
			$empRow.closest('tr').fadeIn(300);
			$patrolRow.closest('tr').fadeIn(300);
		} else if (val == 'Consumables') {
			$empRow.closest('tr').fadeIn(300);
			$patrolRow.closest('tr').fadeIn(300);
		} else if (val == 'ContractJobs') {
			$jobRow.closest('tr').fadeIn(300);
		}
	});

	// Trigger on load if value already set
	if ($('#TransType').val()) {
		$('#TransType').trigger('change');
	}
});

// Dashboard toggle with localStorage persistence
function toggleDashboard() {
	var wrap = document.getElementById('isrDashWrap');
	var toggle = document.getElementById('isrDashToggle');
	var isCollapsed = wrap.classList.contains('collapsed');

	if (isCollapsed) {
		wrap.classList.remove('collapsed');
		toggle.classList.remove('collapsed');
		localStorage.setItem('isrDashCollapsed', 'false');
	} else {
		wrap.classList.add('collapsed');
		toggle.classList.add('collapsed');
		localStorage.setItem('isrDashCollapsed', 'true');
	}
}

// Restore dashboard state
(function(){
	if (localStorage.getItem('isrDashCollapsed') === 'true') {
		document.getElementById('isrDashWrap').classList.add('collapsed');
		document.getElementById('isrDashToggle').classList.add('collapsed');
	}
})();
</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'];
}

function GetRptLinks($GroupID) {
	global $db, $RootPath, $ReportList;
	require_once('reportwriter/languages/en_US/reports.php');
	require_once('reportwriter/admin/defaults.php');
	$GroupID=$ReportList[$GroupID];
	$Title= array(_('Custom Reports'), _('Standard Reports and Forms'));

	$sql= "SELECT id, reporttype, defaultreport, groupname, reportname
			FROM reports
			ORDER BY groupname, reportname";
	$Result=DB_query($sql,'','',false,true);
	$ReportList = '';
	while ($Temp = DB_fetch_array($Result)) $ReportList[] = $Temp;

	$RptLinks = '';
	for ($Def=1; $Def>=0; $Def--) {
        $RptLinks .= '<li class="menu_group_headers">';
        $RptLinks .= '<b>' .  $Title[$Def] . '</b>';
        $RptLinks .= '</li>';
		$NoEntries = true;
		if ($ReportList) {
			foreach ($ReportList as $Report) {
				if ($Report['groupname']==$GroupID AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/ReportMaker.php?action=go&amp;reportid=' . $Report['id'] . '">' . _($Report['reportname']) . '</a></p>';
					$RptLinks .= '</li>';
					$NoEntries = false;
				}
			}
			$NoForms = true;
			foreach ($ReportList as $Report) {
				$Group=explode(':',$Report['groupname']);
				if ($NoForms AND $Group[0]==$GroupID AND $Report['reporttype']=='frm' AND $Report['defaultreport']==$Def) {
                    $RptLinks .= '<li class="menu_group_item">';
					$RptLinks .= '<img src="' . $RootPath . '/css/' . $_SESSION['Theme'] . '/images/folders.gif" width="16" height="13" alt="" />&nbsp;';
					$RptLinks .= '<p>&bull; <a href="' . $RootPath . '/reportwriter/FormMaker.php?id=' . $Report['groupname'] . '"></p>';
					$RptLinks .= $FormGroups[$Report['groupname']] . '</a>';
					$RptLinks .= '</li>';
					$NoForms = false;
					$NoEntries = false;
				}
			}
		}
		if ($NoEntries) $RptLinks .= '<li class="menu_group_item">' . _('There are no reports to show!') . '</li>';
	}
	return $RptLinks;
}
?>