<?php
session_name('CAKEPHP');
session_start();
error_reporting(0);

if (empty($_SESSION['ACGCompanyId'])) { exit; }

$keyword = isset($_POST['keyword']) ? trim($_POST['keyword']) : '';
if (strlen($keyword) < 2) { exit; }

$con = mysqli_connect("127.0.0.1", "root", "", "herp_amch");
if (!$con) { exit; }

$safe  = mysqli_real_escape_string($con, $keyword);
$hroot = 'http://' . $_SERVER['HTTP_HOST'] . '/git/PHP_564/mimhans-2.0/';
$herp  = 'http://' . $_SERVER['HTTP_HOST'] . '/git/PHP_564/mimhans-3.0/herp/';

$results = [];

// --- HMIS side-nav forms (forms table) ---
$sql = mysqli_query($con,
    "SELECT lebel AS label, url AS href, 'hmis' AS src
     FROM forms
     WHERE lebel LIKE '%{$safe}%'
     ORDER BY lebel ASC
     LIMIT 15"
);
if ($sql) {
    while ($r = mysqli_fetch_assoc($sql)) {
        $results[] = [
            'label' => $r['label'],
            'href'  => $hroot . $r['href'],
        ];
    }
}

// --- HERP ERP modules_form ---
$sql2 = mysqli_query($con,
    "SELECT mf.frm_name AS label, mf.frm_url AS route,
            mf.id AS frmid, mf.moduleid AS modid
     FROM modules_form mf
     WHERE mf.frm_name LIKE '%{$safe}%'
       AND mf.status = 'Y'
     ORDER BY mf.frm_name ASC
     LIMIT 10"
);
if ($sql2) {
    while ($r = mysqli_fetch_assoc($sql2)) {
        $url = $herp . 'index.php?route=' . ltrim($r['route'], '/')
             . '&modid=' . intval($r['modid'])
             . '&frmid=' . intval($r['frmid']);
        $results[] = [
            'label' => $r['label'],
            'href'  => $url,
        ];
    }
}

if (empty($results)) {
    echo '<ul><li style="padding:6px 12px; color:#999; font-size:12px;">No results found</li></ul>';
    exit;
}

echo '<ul>';
foreach ($results as $item) {
    $h = htmlspecialchars($item['href']);
    $l = htmlspecialchars($item['label']);
    echo "<li><a href=\"{$h}\">{$l}</a></li>";
}
echo '</ul>';
