<?php
ob_start();
require("dbconnect.php");
require("config.php");
require("function.php");

if (!isset($_SESSION["username_" . $dbname])) {
    header('Content-Type: application/json');
    echo json_encode(['rows' => '', 'total' => 0, 'page' => 1, 'pages' => 1]);
    exit;
}

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);

$maindb = 'product';

// ── Whitelisted fields (key => actual column) ───────────────────────────────
$allowedFields = [
    'id'            => 'id',
    'name'          => 'name',
    'cost'          => 'cost',
    'amount'        => 'amount',
    'unit'          => 'unit',
    'unitpercarton' => 'unitpercarton',
    'gstpercent'    => 'gstpercent',
    'hsncode'       => 'hsncode',
];

$field    = isset($_POST['field'])    && isset($allowedFields[$_POST['field']])    ? $allowedFields[$_POST['field']]    : 'id';
$operator = isset($_POST['operator']) && $_POST['operator'] == '='                 ? '='                                  : 'LIKE';
$sortfld  = isset($_POST['sortfield']) && isset($allowedFields[$_POST['sortfield']]) ? $allowedFields[$_POST['sortfield']] : 'name';
$sortord  = isset($_POST['sortorder']) && strtoupper($_POST['sortorder']) == 'DESC' ? 'DESC' : 'ASC';
$search   = isset($_POST['search'])  ? mysqli_real_escape_string($conn, trim($_POST['search'])) : '';
$page     = isset($_POST['page'])    ? max(1, (int)$_POST['page']) : 1;
$file     = isset($_POST['file'])    && preg_match('/^[a-zA-Z0-9_]+\.php$/', $_POST['file']) ? $_POST['file'] : 'index.php';
$keyfld   = isset($_POST['keyfld'])  && $_POST['keyfld'] == 'id' ? 'id' : 'id';

$pagesize = 8;
$offset   = ($page - 1) * $pagesize;

$where = "";
if ($search != '') {
    if ($operator == '=') {
        $where = "WHERE `$field`='$search'";
    } else {
        $where = "WHERE `$field` LIKE '%$search%'";
    }
}

$totalRes = mysqli_query($conn, "SELECT COUNT(*) AS cnt FROM `$maindb` $where") or die(mysqli_error($conn));
$total    = (int) mysqli_fetch_assoc($totalRes)['cnt'];
$pages    = max(1, (int) ceil($total / $pagesize));
if ($page > $pages) $page = $pages;
$offset   = ($page - 1) * $pagesize;

$result = mysqli_query($conn,
    "SELECT `id`,`name`,`cost`,`amount`,`unit`,`unitpercarton`,`gstpercent`,`hsncode` FROM `$maindb` $where
     ORDER BY `$sortfld` $sortord LIMIT $pagesize OFFSET $offset") or die(mysqli_error($conn));

$rows = '';
while ($row = mysqli_fetch_array($result)) {
    $rows .= '<tr class="srch-row"'
        . ' onclick="window.location.href=\'' . $file . '?mode=edit&' . $keyfld . '=' . $row['id'] . '\'">'
        . '<td class="srch-id">' . $row['id'] . '</td>'
        . '<td class="srch-name">' . htmlspecialchars($row['name']) . '</td>'
        . '<td class="srch-val">' . number_format((float)$row['cost'], 2) . '</td>'
        . '<td class="srch-val">' . number_format((float)$row['amount'], 2) . '</td>'
        . '<td class="srch-val">' . htmlspecialchars($row['unit']) . '</td>'
        . '<td class="srch-val">' . number_format((float)$row['unitpercarton'], 2) . '</td>'
        . '<td class="srch-val">' . number_format((float)$row['gstpercent'], 2) . '</td>'
        . '<td class="srch-val">' . htmlspecialchars($row['hsncode']) . '</td>'
        . '</tr>';
}

if ($total == 0) {
    $rows = '<tr><td colspan="8" class="srch-empty">No records found.</td></tr>';
}

header('Content-Type: application/json');
echo json_encode([
    'rows'  => $rows,
    'total' => $total,
    'page'  => $page,
    'pages' => $pages,
]);
