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

$search = isset($_POST['search']) ? mysqli_real_escape_string($conn, trim($_POST['search'])) : '';
$page   = isset($_POST['page']) ? max(1, (int)$_POST['page']) : 1;
$pagesize = 8;
$_ut    = (int)($_SESSION["usertype_".$dbname] ?? 0);
$_ac    = (int)($_SESSION["agentcode_".$dbname] ?? 0);

$whereParts = [];
if ($search != '') {
    $whereParts[] = "(p.shipmarka LIKE '%$search%' OR p.remarks LIKE '%$search%' OR c.name LIKE '%$search%' OR s.name LIKE '%$search%')";
}
if ($_ut === 3 && $_ac > 0) {
    $whereParts[] = "p.salesman='$_ac'";
}
$where = $whereParts ? ('WHERE ' . implode(' AND ', $whereParts)) : '';

$totalRes = mysqli_query($conn,
    "SELECT COUNT(*) AS cnt FROM `purchase` p
     LEFT JOIN `accmast` c ON c.accode = p.customer
     LEFT JOIN `accmast` s ON s.accode = p.supplier
     $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 p.*, c.name AS customername, s.name AS suppliername
     FROM `purchase` p
     LEFT JOIN `accmast` c ON c.accode = p.customer
     LEFT JOIN `accmast` s ON s.accode = p.supplier
     $where
     ORDER BY p.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=\'purchase.php?mode=edit&vouchno=' . $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>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;font-weight:500;color:#1e293b;">' . htmlspecialchars($row['suppliername'] ?? '') . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . htmlspecialchars($row['customername'] ?? '') . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;">' . htmlspecialchars($row['shipmarka']) . '</td>'
        . '<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;text-align:right;">' . number_format((float)$row['totamt'], 2) . '</td>'
        . '</tr>';
}

if ($total == 0) {
    $rows = '<tr><td colspan="6" 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,
]);
