<?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 = 'godown';

// ── Whitelisted fields (key => actual column) ───────────────────────────────
$allowedFields = [
    'id'      => 'code',
    'name'    => 'name',
    'country' => 'country',
];

$field    = isset($_POST['field'])    && isset($allowedFields[$_POST['field']])    ? $allowedFields[$_POST['field']]    : 'code';
$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'] == 'code' ? 'code' : 'code';

$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 `code`,`name`,`country` FROM `$maindb` $where
     ORDER BY `$sortfld` $sortord LIMIT $pagesize OFFSET $offset") or die(mysqli_error($conn));

$rows = '';
$alt  = false;
while ($row = mysqli_fetch_array($result)) {
    $bg  = $alt ? '#f8fafc' : '#fff';
    $alt = !$alt;
    $rows .= '<tr class="srch-row" style="cursor:pointer;background:' . $bg . ';transition:background .1s;"'
        . ' onmouseover="this.style.background=\'#eff6ff\'"'
        . ' onmouseout="this.style.background=\'' . $bg . '\'"'
        . ' onclick="window.location.href=\'' . $file . '?mode=edit&' . $keyfld . '=' . $row['code'] . '\'">'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;font-weight:600;">' . $row['code'] . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;font-weight:500;color:#1e293b;">' . htmlspecialchars($row['name']) . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . htmlspecialchars($row['country']) . '</td>'
        . '</tr>';
}

if ($total == 0) {
    $rows = '<tr><td colspan="3" style="text-align:center;padding:24px;color:#94a3b8;">No records found.</td></tr>';
}

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