<?php
/* Enhanced ERP Dashboard - React + AI Reports */
error_reporting(E_ALL & ~E_NOTICE);
$PageSecurity=0;

include('includes/session.inc');
$Title=_('ERP Home');
include('includes/newheader.php');

// Get user info for the dashboard greeting
$userid = $_SESSION['UserID'];
$realname_dash = isset($_SESSION['UsersRealName']) ? $_SESSION['UsersRealName'] : (isset($realname) ? $realname : 'User');
$isAdmin = ($userid == 'admin');

// Check if user has AI access
$aiAllowedUsers = array('admin', 'sharukh', 'ravinesh', 'jprasad', 'nitika', 'mike', 'mikejamieson', 'joseph', 'losa', 'mkhan', 'ravneet', 'mosheed', 'priyakumar');
$hasAiAccess = in_array($userid, $aiAllowedUsers);
?>

<!-- React CDN Dependencies -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.23.9/babel.min.js"></script>

<style>
  /* ========== Force full width & override parent styles ========== */
  .m-content { padding: 0 !important; }
  .m-portlet { margin: 0 !important; box-shadow: none !important; border: none !important; }
  .m-portlet__body { padding: 0 !important; }
  .m-subheader { display: none !important; }

  /* ========== ERP Dashboard Theme - e-Business Brand ========== */
  :root {
    --eb-primary: #2AABB3;
    --eb-primary-dark: #1E8F96;
    --eb-primary-deeper: #187278;
    --eb-surface: #F0F4F7;
    --eb-card-bg: #FFFFFF;
    --eb-text: #1A2332;
    --eb-text-muted: #6B7B8D;
    --eb-border: #E2E8F0;
    --eb-shadow: 0 1px 3px rgba(42,171,179,0.06), 0 4px 12px rgba(0,0,0,0.04);
    --eb-shadow-hover: 0 4px 16px rgba(42,171,179,0.14), 0 8px 24px rgba(0,0,0,0.06);
    --eb-radius: 10px;
  }

  #erp-dashboard-root {
    font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif;
    padding: 20px 24px 30px 24px;
    background: var(--eb-surface);
    min-height: calc(100vh - 70px);
  }

  /* Dashboard Header - e-Business brand teal */
  .erp-dash-header {
    background: linear-gradient(135deg, var(--eb-primary-deeper) 0%, var(--eb-primary-dark) 30%, var(--eb-primary) 70%, #38C4CC 100%);
    border-radius: 14px;
    padding: 32px 36px;
    margin-bottom: 24px;
    color: #fff;
    position: relative;
    overflow: hidden;
  }
  .erp-dash-header::before {
    content: '';
    position: absolute;
    top: -60%;
    right: -8%;
    width: 380px;
    height: 380px;
    background: radial-gradient(circle, rgba(255,255,255,0.12) 0%, transparent 70%);
    border-radius: 50%;
    pointer-events: none;
  }
  .erp-dash-header::after {
    content: '';
    position: absolute;
    bottom: -50%;
    left: 15%;
    width: 250px;
    height: 250px;
    background: radial-gradient(circle, rgba(255,255,255,0.06) 0%, transparent 70%);
    border-radius: 50%;
    pointer-events: none;
  }
  .erp-dash-header .erp-brand-shape {
    position: absolute;
    right: 40px;
    top: 50%;
    transform: translateY(-50%);
    width: 130px;
    height: 130px;
    border: 3px solid rgba(255,255,255,0.15);
    border-radius: 50%;
    clip-path: inset(0 50% 0 0);
    pointer-events: none;
  }
  .erp-dash-header .erp-brand-shape-2 {
    position: absolute;
    right: 60px;
    top: 50%;
    transform: translateY(-50%);
    width: 95px;
    height: 95px;
    border: 2px solid rgba(255,255,255,0.1);
    border-radius: 50%;
    clip-path: inset(0 0 0 50%);
    pointer-events: none;
  }
  .erp-dash-header h2 {
    margin: 0 0 6px 0;
    font-size: 24px;
    font-weight: 600;
    letter-spacing: -0.3px;
    position: relative;
    z-index: 1;
    text-shadow: 0 1px 2px rgba(0,0,0,0.1);
  }
  .erp-dash-header p {
    margin: 0;
    font-size: 13.5px;
    opacity: 0.85;
    position: relative;
    z-index: 1;
  }
  .erp-dash-header .erp-date-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    background: rgba(255,255,255,0.18);
    padding: 5px 14px;
    border-radius: 20px;
    font-size: 12px;
    margin-top: 12px;
    backdrop-filter: blur(4px);
    position: relative;
    z-index: 1;
    font-weight: 500;
  }

  /* Category Section */
  .erp-category-section {
    margin-bottom: 22px;
    opacity: 0;
    animation: erpFadeInUp 0.4s ease forwards;
  }
  .erp-category-section:nth-child(1) { animation-delay: 0s; }
  .erp-category-section:nth-child(2) { animation-delay: 0.04s; }
  .erp-category-section:nth-child(3) { animation-delay: 0.08s; }
  .erp-category-section:nth-child(4) { animation-delay: 0.12s; }
  .erp-category-section:nth-child(5) { animation-delay: 0.16s; }
  .erp-category-section:nth-child(6) { animation-delay: 0.2s; }
  .erp-category-section:nth-child(7) { animation-delay: 0.24s; }
  .erp-category-section:nth-child(8) { animation-delay: 0.28s; }
  .erp-category-section:nth-child(9) { animation-delay: 0.32s; }
  .erp-category-section:nth-child(10) { animation-delay: 0.36s; }
  .erp-category-section:nth-child(11) { animation-delay: 0.4s; }

  .erp-category-title {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 14px;
    padding-bottom: 10px;
    border-bottom: 2px solid var(--eb-border);
  }
  .erp-category-title .erp-cat-icon {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 16px;
    color: #fff;
    flex-shrink: 0;
  }
  .erp-category-title h3 {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
    color: var(--eb-text);
    letter-spacing: -0.2px;
  }
  .erp-category-title .erp-cat-count {
    font-size: 11px;
    color: var(--eb-text-muted);
    background: #E8EDF2;
    padding: 2px 8px;
    border-radius: 10px;
    font-weight: 500;
  }

  /* Quick Link Cards */
  .erp-links-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(185px, 1fr));
    gap: 12px;
  }
  .erp-link-card {
    background: var(--eb-card-bg);
    border: 1px solid var(--eb-border);
    border-radius: var(--eb-radius);
    padding: 16px 14px;
    text-decoration: none !important;
    color: var(--eb-text) !important;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
    transition: all 0.22s ease;
    cursor: pointer;
    box-shadow: var(--eb-shadow);
    position: relative;
    overflow: hidden;
  }
  .erp-link-card::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 2.5px;
    background: var(--eb-primary);
    transform: scaleX(0);
    transition: transform 0.22s ease;
  }
  .erp-link-card:hover {
    box-shadow: var(--eb-shadow-hover);
    border-color: var(--eb-primary);
    transform: translateY(-2px);
    text-decoration: none !important;
    color: var(--eb-text) !important;
  }
  .erp-link-card:hover::after {
    transform: scaleX(1);
  }
  .erp-link-card:hover .erp-link-icon {
    transform: scale(1.1);
  }
  .erp-link-card .erp-link-icon {
    width: 40px;
    height: 40px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 18px;
    transition: transform 0.22s ease;
    flex-shrink: 0;
  }
  .erp-link-card .erp-link-name {
    font-size: 12.5px;
    font-weight: 500;
    line-height: 1.35;
    color: var(--eb-text);
  }

  /* Category color themes */
  .erp-theme-teal     { background: linear-gradient(135deg, #1E8F96, #2AABB3); }
  .erp-theme-blue     { background: linear-gradient(135deg, #1B5E8F, #2B7EC5); }
  .erp-theme-green    { background: linear-gradient(135deg, #059669, #10B981); }
  .erp-theme-orange   { background: linear-gradient(135deg, #D97706, #F59E0B); }
  .erp-theme-purple   { background: linear-gradient(135deg, #7C3AED, #8B5CF6); }
  .erp-theme-red      { background: linear-gradient(135deg, #DC2626, #EF4444); }
  .erp-theme-indigo   { background: linear-gradient(135deg, #4338CA, #6366F1); }
  .erp-theme-pink     { background: linear-gradient(135deg, #DB2777, #EC4899); }
  .erp-theme-slate    { background: linear-gradient(135deg, #475569, #64748B); }
  .erp-theme-amber    { background: linear-gradient(135deg, #B45309, #D97706); }
  .erp-theme-cyan     { background: linear-gradient(135deg, #0891B2, #22D3EE); }

  .erp-icon-bg-teal   { background: rgba(42,171,179,0.1); color: #1E8F96; }
  .erp-icon-bg-blue   { background: rgba(43,126,197,0.1); color: #1B5E8F; }
  .erp-icon-bg-green  { background: rgba(16,185,129,0.1); color: #059669; }
  .erp-icon-bg-orange { background: rgba(245,158,11,0.1); color: #D97706; }
  .erp-icon-bg-purple { background: rgba(139,92,246,0.1); color: #7C3AED; }
  .erp-icon-bg-red    { background: rgba(239,68,68,0.1); color: #DC2626; }
  .erp-icon-bg-indigo { background: rgba(99,102,241,0.1); color: #4338CA; }
  .erp-icon-bg-pink   { background: rgba(236,72,153,0.1); color: #DB2777; }
  .erp-icon-bg-slate  { background: rgba(100,116,139,0.1); color: #475569; }
  .erp-icon-bg-amber  { background: rgba(217,119,6,0.1); color: #B45309; }
  .erp-icon-bg-cyan   { background: rgba(8,145,178,0.1); color: #0891B2; }

  /* Search box */
  .erp-search-wrap {
    margin-bottom: 22px;
    position: relative;
  }
  .erp-search-wrap input {
    width: 100%;
    padding: 13px 16px 13px 44px;
    border: 1.5px solid var(--eb-border);
    border-radius: var(--eb-radius);
    font-size: 14px;
    font-family: 'Poppins', sans-serif;
    background: var(--eb-card-bg);
    color: var(--eb-text);
    box-shadow: var(--eb-shadow);
    transition: all 0.2s;
    outline: none;
    box-sizing: border-box;
  }
  .erp-search-wrap input:focus {
    border-color: var(--eb-primary);
    box-shadow: 0 0 0 3px rgba(42,171,179,0.12);
  }
  .erp-search-wrap input::placeholder {
    color: var(--eb-text-muted);
    font-size: 13px;
  }
  .erp-search-wrap .erp-search-icon {
    position: absolute;
    left: 15px;
    top: 50%;
    transform: translateY(-50%);
    color: var(--eb-text-muted);
    font-size: 16px;
    display: flex;
  }

  /* ========== AI Reports Panel ========== */
  .ai-panel {
    background: var(--eb-card-bg);
    border: 1.5px solid var(--eb-border);
    border-radius: 14px;
    margin-bottom: 24px;
    box-shadow: var(--eb-shadow);
    overflow: hidden;
  }
  .ai-panel-header {
    background: linear-gradient(135deg, #187278 0%, #1E8F96 40%, #2AABB3 100%);
    padding: 18px 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    user-select: none;
  }
  .ai-panel-header:hover { opacity: 0.95; }
  .ai-panel-header-left {
    display: flex;
    align-items: center;
    gap: 12px;
    color: #fff;
  }
  .ai-panel-header-left .ai-icon {
    width: 38px;
    height: 38px;
    background: rgba(255,255,255,0.2);
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
  }
  .ai-panel-header-left h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
  }
  .ai-panel-header-left span {
    font-size: 12px;
    opacity: 0.8;
  }
  .ai-panel-toggle {
    color: #fff;
    font-size: 20px;
    transition: transform 0.3s;
    background: none;
    border: none;
    cursor: pointer;
    padding: 4px 8px;
  }
  .ai-panel-toggle.open { transform: rotate(180deg); }
  .ai-panel-body {
    padding: 24px;
    display: none;
  }
  .ai-panel-body.open { display: block; }
  .ai-input-row {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  .ai-input-row input {
    flex: 1;
    padding: 13px 16px;
    border: 1.5px solid var(--eb-border);
    border-radius: var(--eb-radius);
    font-size: 14px;
    font-family: 'Poppins', sans-serif;
    background: #FAFBFC;
    color: var(--eb-text);
    outline: none;
    transition: all 0.2s;
  }
  .ai-input-row input:focus {
    border-color: var(--eb-primary);
    box-shadow: 0 0 0 3px rgba(42,171,179,0.12);
    background: #fff;
  }
  .ai-input-row input::placeholder {
    color: #9CA3AF;
    font-size: 13px;
  }
  .ai-btn {
    padding: 13px 28px;
    background: linear-gradient(135deg, #1E8F96, #2AABB3);
    color: #fff;
    border: none;
    border-radius: var(--eb-radius);
    font-family: 'Poppins', sans-serif;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    white-space: nowrap;
    display: flex;
    align-items: center;
    gap: 8px;
  }
  .ai-btn:hover { opacity: 0.9; transform: translateY(-1px); }
  .ai-btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
  }
  .ai-suggestions {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 16px;
  }
  .ai-suggestion-chip {
    padding: 6px 14px;
    background: #F0F9FA;
    border: 1px solid #D1ECEE;
    border-radius: 20px;
    font-size: 12px;
    color: #1E8F96;
    cursor: pointer;
    transition: all 0.2s;
    font-family: 'Poppins', sans-serif;
  }
  .ai-suggestion-chip:hover {
    background: #D1ECEE;
    border-color: #2AABB3;
  }
  .ai-status {
    padding: 16px 20px;
    border-radius: var(--eb-radius);
    margin-top: 16px;
    font-size: 13px;
    line-height: 1.6;
  }
  .ai-status.loading {
    background: #FFF7ED;
    border: 1px solid #FED7AA;
    color: #9A3412;
  }
  .ai-status.error {
    background: #FEF2F2;
    border: 1px solid #FECACA;
    color: #991B1B;
  }
  .ai-status.success {
    background: #F0FDF4;
    border: 1px solid #BBF7D0;
    color: #166534;
  }
  .ai-sql-box {
    background: #1E293B;
    color: #E2E8F0;
    padding: 14px 18px;
    border-radius: 8px;
    font-family: 'Courier New', monospace;
    font-size: 12px;
    line-height: 1.6;
    margin: 12px 0;
    overflow-x: auto;
    white-space: pre-wrap;
    word-break: break-all;
  }
  .ai-results-table-wrap {
    overflow-x: auto;
    margin-top: 16px;
    border: 1px solid var(--eb-border);
    border-radius: 8px;
  }
  .ai-results-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12.5px;
  }
  .ai-results-table th {
    background: #F1F5F9;
    padding: 10px 14px;
    text-align: left;
    font-weight: 600;
    color: var(--eb-text);
    border-bottom: 2px solid var(--eb-border);
    white-space: nowrap;
    position: sticky;
    top: 0;
  }
  .ai-results-table td {
    padding: 9px 14px;
    border-bottom: 1px solid #F1F5F9;
    color: var(--eb-text);
    max-width: 250px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  .ai-results-table tr:hover td {
    background: #F8FAFC;
  }
  .ai-results-table tr:nth-child(even) td {
    background: #FAFBFC;
  }
  .ai-results-table tr:nth-child(even):hover td {
    background: #F1F5F9;
  }
  .ai-results-meta {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 12px;
    font-size: 12px;
    color: var(--eb-text-muted);
  }
  .ai-export-btn {
    padding: 6px 16px;
    background: #F1F5F9;
    border: 1px solid var(--eb-border);
    border-radius: 6px;
    font-size: 12px;
    color: var(--eb-text);
    cursor: pointer;
    font-family: 'Poppins', sans-serif;
    transition: all 0.2s;
  }
  .ai-export-btn:hover {
    background: #E2E8F0;
  }
  @keyframes aiPulse {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.5; }
  }
  .ai-loading-dots {
    display: inline-flex;
    gap: 4px;
    margin-left: 8px;
  }
  .ai-loading-dots span {
    width: 6px;
    height: 6px;
    background: #9A3412;
    border-radius: 50%;
    animation: aiPulse 1.2s infinite;
  }
  .ai-loading-dots span:nth-child(2) { animation-delay: 0.2s; }
  .ai-loading-dots span:nth-child(3) { animation-delay: 0.4s; }

  /* Responsive */
  @media (max-width: 992px) {
    .erp-links-grid { grid-template-columns: repeat(3, 1fr); }
  }
  @media (max-width: 768px) {
    #erp-dashboard-root { padding: 12px 14px 20px 14px; }
    .erp-links-grid { grid-template-columns: repeat(2, 1fr); gap: 8px; }
    .erp-dash-header { padding: 22px 20px; border-radius: 10px; }
    .erp-dash-header h2 { font-size: 18px; }
    .erp-dash-header p { font-size: 12px; }
    .erp-link-card { padding: 12px 10px; }
    .erp-link-card .erp-link-icon { width: 34px; height: 34px; font-size: 15px; }
    .erp-link-card .erp-link-name { font-size: 11.5px; }
    .ai-input-row { flex-direction: column; }
    .ai-panel-body { padding: 16px; }
  }

  @keyframes erpFadeInUp {
    from { opacity: 0; transform: translateY(12px); }
    to { opacity: 1; transform: translateY(0); }
  }
</style>

<!-- React Dashboard Mount Point -->
<div id="erp-dashboard-root"></div>

<script type="text/babel">
const { useState, useMemo, useCallback, useRef } = React;

const ERP_USER = {
  name: "<?php echo addslashes($realname_dash); ?>",
  userId: "<?php echo addslashes($userid); ?>",
  hasAiAccess: <?php echo $hasAiAccess ? 'true' : 'false'; ?>
};

// SVG Icons
const Icons = {
  search: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>,
  users: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>,
  package: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m7.5 4.27 9 5.15"/><path d="M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z"/><path d="m3.3 7 8.7 5 8.7-5"/><path d="M12 22V12"/></svg>,
  shoppingCart: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/></svg>,
  dollarSign: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" x2="12" y1="2" y2="22"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>,
  fileText: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"/><path d="M14 2v4a2 2 0 0 0 2 2h4"/><path d="M10 9H8"/><path d="M16 13H8"/><path d="M16 17H8"/></svg>,
  truck: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"/><path d="M15 18H9"/><path d="M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"/><circle cx="17" cy="18" r="2"/><circle cx="7" cy="18" r="2"/></svg>,
  building: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="16" height="20" x="4" y="2" rx="2" ry="2"/><path d="M9 22v-4h6v4"/><path d="M8 6h.01"/><path d="M16 6h.01"/><path d="M12 6h.01"/><path d="M12 10h.01"/><path d="M12 14h.01"/><path d="M16 10h.01"/><path d="M16 14h.01"/><path d="M8 10h.01"/><path d="M8 14h.01"/></svg>,
  creditCard: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="14" x="2" y="5" rx="2"/><line x1="2" x2="22" y1="10" y2="10"/></svg>,
  briefcase: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16"/><rect width="20" height="14" x="2" y="6" rx="2"/></svg>,
  shield: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"/></svg>,
  receipt: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8"/><path d="M12 17.5v-11"/></svg>,
  monitor: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="14" x="2" y="3" rx="2"/><line x1="8" x2="16" y1="21" y2="21"/><line x1="12" x2="12" y1="17" y2="21"/></svg>,
  clipboard: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="8" height="4" x="8" y="2" rx="1" ry="1"/><path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"/><path d="M12 11h4"/><path d="M12 16h4"/><path d="M8 11h.01"/><path d="M8 16h.01"/></svg>,
  calendar: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/></svg>,
  home: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/><polyline points="9,22 9,12 15,12 15,22"/></svg>,
  barChart: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="12" x2="12" y1="20" y2="10"/><line x1="18" x2="18" y1="20" y2="4"/><line x1="6" x2="6" y1="20" y2="16"/></svg>,
  book: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H20v20H6.5a2.5 2.5 0 0 1 0-5H20"/></svg>,
  wrench: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z"/></svg>,
  billing: () => <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="20" height="14" x="2" y="5" rx="2"/><path d="M2 10h20"/></svg>,
  sparkle: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m12 3-1.912 5.813a2 2 0 0 1-1.275 1.275L3 12l5.813 1.912a2 2 0 0 1 1.275 1.275L12 21l1.912-5.813a2 2 0 0 1 1.275-1.275L21 12l-5.813-1.912a2 2 0 0 1-1.275-1.275L12 3Z"/></svg>,
  chevronDown: () => <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m6 9 6 6 6-6"/></svg>,
  download: () => <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/></svg>,
  send: () => <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="m22 2-7 20-4-9-9-4Z"/><path d="M22 2 11 13"/></svg>
};

// Dashboard Data
const dashboardCategories = [
  {
    id: 'approvals', title: 'Approvals & Quick Actions', icon: 'shield', theme: 'red',
    links: [
      { name: 'Authorize Stock Request', href: 'InternalStockRequestAuthorisation.php', icon: 'shield' },
      { name: 'PO Authorization', href: 'PO_AuthoriseMyOrders.php', icon: 'clipboard' },
      { name: 'Stock Requests', href: 'StockRequest.php', icon: 'package' },
    ]
  },
  {
    id: 'customers', title: 'Customers & CRM', icon: 'users', theme: 'blue',
    links: [
      { name: 'Customer Search', href: 'SelectCustomer.php', icon: 'users' },
      { name: 'Sales Prospecting', href: 'prospecting.php', icon: 'barChart' },
      { name: 'Customer Contracts', href: 'AllClientContracts.php', icon: 'fileText' },
      { name: 'Customer Master', href: 'CustomerMaster.php', icon: 'clipboard' },
    ]
  },
  {
    id: 'sales', title: 'Sales & Invoicing', icon: 'dollarSign', theme: 'green',
    links: [
      { name: 'Easy Invoicing', href: 'Invoicing.php', icon: 'receipt' },
      { name: 'Quotations', href: 'Quotations.php', icon: 'fileText' },
      { name: 'General Billing', href: 'Billing.php', icon: 'creditCard' },
      { name: 'POS Transactions', href: 'POSTrans-nosdc.php', icon: 'shoppingCart' },
      { name: 'Outstanding Orders', href: 'SelectSalesOrder.php', icon: 'clipboard' },
      { name: 'Sales Dashboard', href: 'SalesDashboard.php', icon: 'barChart' },
    ]
  },
  {
    id: 'projects', title: 'Project Management', icon: 'briefcase', theme: 'purple',
    links: [
      { name: 'Projects / Jobs', href: 'project.php', icon: 'briefcase' },
      { name: 'Monitoring Billing', href: 'MonitoringBilling.php', icon: 'billing' },
      { name: 'Technician Worksheets', href: 'technician_worksheet.php', icon: 'wrench' },
      { name: 'Small Jobs Insights', href: 'SmallProjects_Insights.php', icon: 'barChart' },
      { name: 'Contract Insights', href: 'ContractProjects_Insights.php', icon: 'barChart' },
    ]
  },
  {
    id: 'debtors', title: 'Debtors & Receipts', icon: 'receipt', theme: 'orange',
    links: [
      { name: 'Enter Receipts', href: 'Receipts.php', icon: 'receipt' },
      { name: 'Debtors Dashboard', href: 'DebtorsDashboard.php', icon: 'barChart' },
      { name: 'Aged Debtors', href: 'AllAgingReport.php', icon: 'calendar' },
      { name: 'Print Statements', href: 'Statements.php', icon: 'fileText' },
      { name: 'Invoice Reconciliation', href: 'InvoiceRecon1.php', icon: 'clipboard' },
    ]
  },
  {
    id: 'purchasing', title: 'Purchasing & Suppliers', icon: 'truck', theme: 'teal',
    links: [
      { name: 'Search Supplier', href: 'SelectSupplier.php', icon: 'users' },
      { name: 'New Purchase Order', href: 'PO_Header.php?NewOrder=Yes', icon: 'shoppingCart' },
      { name: 'Purchase Orders', href: 'PO_SelectOSPurchOrder.php', icon: 'clipboard' },
      { name: 'Supplier Transactions', href: 'SuppliersTransactions.php', icon: 'dollarSign' },
      { name: 'Supplier Payments', href: 'SuppliersPayment.php', icon: 'creditCard' },
    ]
  },
  {
    id: 'inventory', title: 'Inventory Management', icon: 'package', theme: 'indigo',
    links: [
      { name: 'Search Items', href: 'SelectProduct.php', icon: 'package' },
      { name: 'Stock Transfers', href: 'StockTransfers.php?New=Yes', icon: 'truck' },
      { name: 'Stock Adjustments', href: 'StockAdjustments.php', icon: 'wrench' },
      { name: 'Inventory Valuation', href: 'InventoryValuation.php', icon: 'dollarSign' },
      { name: 'Inventory Dashboard', href: 'InventoryDashboard.php', icon: 'barChart' },
      { name: 'Enter Stock Counts', href: 'StockCountsNew.php', icon: 'clipboard' },
    ]
  },
  {
    id: 'hrms', title: 'Human Resources', icon: 'users', theme: 'pink',
    links: [
      { name: 'Employee Management', href: 'employee.php', icon: 'users' },
      { name: 'Rostering', href: 'rostering.php', icon: 'calendar' },
      { name: 'Timesheet', href: 'timesheet.php', icon: 'calendar' },
      { name: 'Leave Management', href: 'absent_management.php', icon: 'calendar' },
      
      { name: 'Payroll Dashboard', href: 'PayRunsAll.php', icon: 'dollarSign' },
      { name: 'PayRun Manual', href: 'PayRunsManual.php', icon: 'dollarSign' },
      { name: 'PayRun Management', href: 'PayRunsManagement.php', icon: 'dollarSign' },
    ]
  },
  {
    id: 'banking', title: 'Banking & General Ledger', icon: 'building', theme: 'slate',
    links: [
      { name: 'Bank Payments', href: 'Payments.php?NewPayment=Yes', icon: 'creditCard' },
      { name: 'Bank Receipts', href: 'CustomerReceipt.php?NewReceipt=Yes&Type=GL', icon: 'receipt' },
      { name: 'Journal Entry', href: 'GLJournal.php', icon: 'fileText' },
      { name: 'Trial Balance', href: 'GLTrialBalance.php', icon: 'barChart' },
      { name: 'Profit & Loss', href: 'GLProfit_Loss.php', icon: 'barChart' },
      { name: 'Balance Sheet', href: 'GLBalanceSheet.php', icon: 'fileText' },
    ]
  },
  {
    id: 'assets', title: 'Asset Management', icon: 'monitor', theme: 'amber',
    links: [
      { name: 'Asset Register', href: 'FixedAssetRegister.php', icon: 'clipboard' },
      { name: 'Add New Asset', href: 'FixedAssetItems.php', icon: 'monitor' },
      { name: 'Depreciation Journal', href: 'FixedAssetDepreciation.php', icon: 'dollarSign' },
    ]
  },
  {
    id: 'resources', title: 'Resources & Tools', icon: 'book', theme: 'cyan',
    links: [
      { name: 'Policies', href: 'Policies.php', icon: 'fileText' },
      { name: 'SOPs', href: 'SOP.php', icon: 'book' },
      { name: 'Video Tutorials', href: 'ManualsVideo.php', icon: 'monitor' },
      { name: 'Departments', href: 'department.php', icon: 'building' },
      { name: 'Task Management', href: 'TaskManagement.php', icon: 'clipboard' },
    ]
  }
];

// Suggested AI queries
const aiSuggestions = [
  "Accounts with 180 days plus aging with name and account number",
  "Total net wages payout for the latest pay run"
];

// AI Reports Panel Component
function AIReportsPanel() {
  const [isOpen, setIsOpen] = useState(false);
  const [question, setQuestion] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [error, setError] = useState(null);
  const inputRef = useRef(null);

  const handleSubmit = useCallback(async (q) => {
    const query = q || question;
    if (!query.trim()) return;

    setLoading(true);
    setError(null);
    setResult(null);

    try {
      const response = await fetch('ai-api/ai_query.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ question: query.trim() })
      });

      const data = await response.json();

      if (data.error) {
        setError(data.error + (data.sql && ERP_USER.userId === 'admin' ? '\n\nGenerated SQL:\n' + data.sql : ''));
      } else if (data.success) {
        setResult(data);
      }
    } catch (err) {
      setError('Failed to connect to AI service. Please try again.');
    } finally {
      setLoading(false);
    }
  }, [question]);

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !loading) handleSubmit();
  };

  const handleSuggestionClick = (suggestion) => {
    setQuestion(suggestion);
    handleSubmit(suggestion);
  };

  const exportCSV = useCallback(() => {
    if (!result) return;
    const headers = result.columns.join(',');
    const rows = result.rows.map(row =>
      result.columns.map(col => {
        const val = (row[col] || '').toString().replace(/"/g, '""');
        return `"${val}"`;
      }).join(',')
    );
    const csv = [headers, ...rows].join('\n');
    const blob = new Blob([csv], { type: 'text/csv' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'ai_report_' + new Date().toISOString().slice(0, 10) + '.csv';
    a.click();
    URL.revokeObjectURL(url);
  }, [result]);

  return (
    <div className="ai-panel">
      <div className="ai-panel-header" onClick={() => setIsOpen(!isOpen)}>
        <div className="ai-panel-header-left">
          <div className="ai-icon"><Icons.sparkle /></div>
          <div>
            <h3>AI Report Assistant</h3>
            <span>Ask questions about your business data in plain English</span>
          </div>
        </div>
        <button className={`ai-panel-toggle ${isOpen ? 'open' : ''}`}>
          <Icons.chevronDown />
        </button>
      </div>

      <div className={`ai-panel-body ${isOpen ? 'open' : ''}`}>
        <div className="ai-input-row">
          <input
            ref={inputRef}
            type="text"
            placeholder="Ask a question... e.g. &quot;Show me top 10 overdue customers&quot;"
            value={question}
            onChange={(e) => setQuestion(e.target.value)}
            onKeyPress={handleKeyPress}
            disabled={loading}
          />
          <button className="ai-btn" onClick={() => handleSubmit()} disabled={loading || !question.trim()}>
            <Icons.send />
            {loading ? 'Thinking...' : 'Ask AI'}
          </button>
        </div>

        <div className="ai-suggestions">
          {aiSuggestions.map((s, i) => (
            <span key={i} className="ai-suggestion-chip" onClick={() => !loading && handleSuggestionClick(s)}>
              {s}
            </span>
          ))}
        </div>

        {loading && (
          <div className="ai-status loading">
            Analyzing your question and querying the database
            <span className="ai-loading-dots">
              <span></span><span></span><span></span>
            </span>
            <br/>This may take 15-45 seconds on first query.
          </div>
        )}

        {error && (
          <div className="ai-status error">
            <strong>Error:</strong> {error}
          </div>
        )}

        {result && (
          <div>
            <div className="ai-status success">
              <strong>Query successful!</strong> Found {result.rowCount} record{result.rowCount !== 1 ? 's' : ''}.
              {result.truncated && ' (Showing first 500 rows)'}
            </div>

            {ERP_USER.userId === 'admin' && <div className="ai-sql-box">{result.sql}</div>}

            {result.rows.length > 0 && (
              <div>
                <div className="ai-results-table-wrap" style={{ maxHeight: '450px', overflowY: 'auto' }}>
                  <table className="ai-results-table">
                    <thead>
                      <tr>
                        {result.columns.map((col, i) => (
                          <th key={i}>{col.replace(/_/g, ' ').toUpperCase()}</th>
                        ))}
                      </tr>
                    </thead>
                    <tbody>
                      {result.rows.map((row, ri) => (
                        <tr key={ri}>
                          {result.columns.map((col, ci) => (
                            <td key={ci} title={row[col]}>{row[col]}</td>
                          ))}
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
                <div className="ai-results-meta">
                  <span>{result.rowCount} row{result.rowCount !== 1 ? 's' : ''} returned</span>
                  <button className="ai-export-btn" onClick={exportCSV}>
                    <Icons.download /> Export CSV
                  </button>
                </div>
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// Components
function LinkCard({ name, href, icon, theme }) {
  const IconComponent = Icons[icon] || Icons.home;
  return (
    <a href={href} className="erp-link-card">
      <div className={`erp-link-icon erp-icon-bg-${theme}`}><IconComponent /></div>
      <span className="erp-link-name">{name}</span>
    </a>
  );
}

function CategorySection({ category, searchTerm }) {
  const filteredLinks = useMemo(() => {
    if (!searchTerm) return category.links;
    const term = searchTerm.toLowerCase();
    return category.links.filter(link => link.name.toLowerCase().includes(term));
  }, [category.links, searchTerm]);

  if (filteredLinks.length === 0) return null;
  const IconComponent = Icons[category.icon] || Icons.home;

  return (
    <div className="erp-category-section">
      <div className="erp-category-title">
        <div className={`erp-cat-icon erp-theme-${category.theme}`}><IconComponent /></div>
        <h3>{category.title}</h3>
        <span className="erp-cat-count">{filteredLinks.length} items</span>
      </div>
      <div className="erp-links-grid">
        {filteredLinks.map((link, idx) => (
          <LinkCard key={idx} name={link.name} href={link.href} icon={link.icon} theme={category.theme} />
        ))}
      </div>
    </div>
  );
}

function ERPDashboard() {
  const [searchTerm, setSearchTerm] = useState('');
  const today = new Date();
  const dateStr = today.toLocaleDateString('en-US', { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });

  const getGreeting = () => {
    const hour = today.getHours();
    if (hour < 12) return 'Good Morning';
    if (hour < 17) return 'Good Afternoon';
    return 'Good Evening';
  };

  const visibleCategories = useMemo(() => {
    if (!searchTerm) return dashboardCategories;
    return dashboardCategories.filter(cat =>
      cat.links.some(link => link.name.toLowerCase().includes(searchTerm.toLowerCase()))
    );
  }, [searchTerm]);

  const totalLinks = dashboardCategories.reduce((sum, cat) => sum + cat.links.length, 0);

  return (
    <div>
      <div className="erp-dash-header">
        <div className="erp-brand-shape"></div>
        <div className="erp-brand-shape-2"></div>
        <h2>{getGreeting()}, {ERP_USER.name}</h2>
        <p>e-Business ERP System &mdash; {totalLinks} quick access modules</p>
        <div className="erp-date-badge">
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M8 2v4"/><path d="M16 2v4"/><rect width="18" height="18" x="3" y="4" rx="2"/><path d="M3 10h18"/></svg>
          {dateStr}
        </div>
      </div>

      {ERP_USER.hasAiAccess && <AIReportsPanel />}

      <div className="erp-search-wrap">
        <span className="erp-search-icon"><Icons.search /></span>
        <input
          type="text"
          placeholder="Search modules... (e.g. Invoice, Stock, Employee, Payroll, GL)"
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
        />
      </div>

      {visibleCategories.map(category => (
        <CategorySection key={category.id} category={category} searchTerm={searchTerm} />
      ))}

      {visibleCategories.length === 0 && (
        <div style={{ textAlign: 'center', padding: '50px 20px', color: 'var(--eb-text-muted)', fontSize: '14px' }}>
          No modules found matching "<strong>{searchTerm}</strong>"
        </div>
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('erp-dashboard-root'));
root.render(<ERPDashboard />);
</script>

<?php
if (isset($SupplierLogin) AND $SupplierLogin==1){
    // Supplier portal
} elseif (isset($CustomerLogin) AND $CustomerLogin==1){
    // Customer portal
}
if (isset($_GET['Application'])){
    $_SESSION['Module'] = $_GET['Application'];
}
?>
