<?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);

// ── Whitelisted tables (table => [accode column(s), file]) ──────────────────
// 'party' mode: table has a generic `accode` (party) plus one bank/cash col.
// 'dual' mode: table has two "own account" columns and no separate party
// leg at all (currently just Contra: fromac/toac, transfers between the
// company's own Bank/Cash accounts).
// 'voucher' mode: table has no account column of its own at all — every line
// lives in a separate *tran table (currently just JV: jv/jvtran, an N-line
// Dr/Cr voucher), so search matches on voucher no. / narration instead.
$allowedTables = [
    'bankrecp' => ['mode' => 'party', 'col' => 'bankac', 'file' => 'bankrecp.php'],
    'bankpay'  => ['mode' => 'party', 'col' => 'bankac', 'file' => 'bankpay.php'],
    'cashrecp' => ['mode' => 'party', 'col' => 'cashac', 'file' => 'cashrecp.php'],
    'cashpay'  => ['mode' => 'party', 'col' => 'cashac', 'file' => 'cashpay.php'],
    'discountgiven' => ['mode' => 'party', 'col' => 'cashac', 'file' => 'discountgiven.php'],
    'discounttaken' => ['mode' => 'party', 'col' => 'cashac', 'file' => 'discounttaken.php'],
    'contra'   => ['mode' => 'dual', 'col' => 'fromac', 'col2' => 'toac', 'file' => 'contra.php'],
    'jv'       => ['mode' => 'voucher', 'trandb' => 'jvtran', 'file' => 'jv.php'],
];

$table = isset($_POST['table']) && isset($allowedTables[$_POST['table']]) ? $_POST['table'] : 'bankrecp';
$cfg   = $allowedTables[$table];
$mode  = $cfg['mode'];
$col   = $cfg['col'];
$file  = $cfg['file'];
$keyfld = 'vouchno';

$search = isset($_POST['search']) ? mysqli_real_escape_string($conn, trim($_POST['search'])) : '';
$page   = isset($_POST['page']) ? max(1, (int)$_POST['page']) : 1;

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

if ($mode === 'voucher') {
    $trandb = $cfg['trandb'];
    $where  = "WHERE 1=1";
    if ($search != '') {
        $where .= " AND (m.`narr` LIKE '%$search%' OR m.`vouchno` LIKE '%$search%')";
    }

    $totalRes = mysqli_query($conn, "SELECT COUNT(*) AS cnt FROM `$table` m $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 m.`vouchno`, m.`vouchdt`, m.`narr`,
                (SELECT SUM(t.`dr`) FROM `$trandb` t WHERE t.`vouchno` = m.`vouchno`) AS amount
         FROM `$table` m
         $where
         ORDER BY m.`vouchno` DESC LIMIT $pagesize OFFSET $offset") or die(mysqli_error($conn));
} elseif ($mode === 'dual') {
    $col2  = $cfg['col2'];
    $where = "WHERE 1=1";
    if ($search != '') {
        $where .= " AND (a.`name` LIKE '%$search%' OR b.`name` LIKE '%$search%' OR m.`vouchno` LIKE '%$search%')";
    }

    $totalRes = mysqli_query($conn,
        "SELECT COUNT(*) AS cnt FROM `$table` m
         LEFT JOIN `accmast` a ON a.`accode` = m.`$col`
         LEFT JOIN `accmast` b ON b.`accode` = m.`$col2`
         $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 m.`vouchno`, m.`vouchdt`, m.`amount`, a.`name` AS bankname, b.`name` AS partyname
         FROM `$table` m
         LEFT JOIN `accmast` a ON a.`accode` = m.`$col`
         LEFT JOIN `accmast` b ON b.`accode` = m.`$col2`
         $where
         ORDER BY m.`vouchno` DESC LIMIT $pagesize OFFSET $offset") or die(mysqli_error($conn));
} else {
    $where = "WHERE 1=1";
    if ($search != '') {
        $where .= " AND (a.`name` LIKE '%$search%' OR m.`vouchno` LIKE '%$search%')";
    }

    $totalRes = mysqli_query($conn,
        "SELECT COUNT(*) AS cnt FROM `$table` m
         LEFT JOIN `accmast` a ON a.`accode` = m.`accode`
         $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 m.`vouchno`, m.`vouchdt`, m.`amount`, m.`currency`, a.`name` AS partyname, b.`name` AS bankname
         FROM `$table` m
         LEFT JOIN `accmast` a ON a.`accode` = m.`accode`
         LEFT JOIN `accmast` b ON b.`accode` = m.`$col`
         $where
         ORDER BY m.`vouchno` DESC LIMIT $pagesize OFFSET $offset") or die(mysqli_error($conn));
}

$rows = '';
$alt  = false;
while ($row = mysqli_fetch_array($result)) {
    $bg  = $alt ? '#f8fafc' : '#fff';
    $alt = !$alt;
    $dt  = $row['vouchdt'] != '0000-00-00' ? date('d-m-Y', strtotime($row['vouchdt'])) : '';
    $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['vouchno'] . '\'">'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;font-weight:600;">' . $row['vouchno'] . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . $dt . '</td>';
    if ($mode === 'voucher') {
        $rows .= '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;font-weight:500;color:#1e293b;">' . htmlspecialchars($row['narr'] ?? '') . '</td>';
    } else {
        $rows .= '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . htmlspecialchars($row['bankname'] ?? '') . '</td>'
               . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;font-weight:500;color:#1e293b;">' . htmlspecialchars($row['partyname'] ?? '') . '</td>';
    }
    $rows .= '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;text-align:right;">' . number_format((float)$row['amount'], 2) . ' ' . htmlspecialchars($row['currency'] ?? '') . '</td>';
    $rows .= '</tr>';
}

if ($total == 0) {
    $cols = ($mode === 'voucher') ? 4 : 5;
    $rows = '<tr><td colspan="' . $cols . '" 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,
]);
?>
