<?php
ob_start();
require("dbconnect.php");
require("config.php");
require("function.php");
if (!isset($_SESSION["username_".$dbname])) { 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;
$where = '';
if ($search != '') $where = "WHERE d.remarks LIKE '%$search%'";
$total = (int)(mysqli_fetch_assoc(mysqli_query($conn,"SELECT COUNT(*) AS c FROM damage d $where"))['c'] ?? 0);
$pages = max(1,(int)ceil($total/$pagesize));
if ($page > $pages) $page = $pages;
$offset = ($page-1)*$pagesize;
$res = mysqli_query($conn,"SELECT d.* FROM damage d $where ORDER BY d.vouchno DESC LIMIT $pagesize OFFSET $offset");
$rows=''; $alt=false;
while ($row=mysqli_fetch_assoc($res)) {
    $bg=$alt?'#f8fafc':'#fff'; $alt=!$alt;
    $dt=$row['vouchdt']&&$row['vouchdt']!='0000-00-00'?date('d-m-Y',strtotime($row['vouchdt'])):'';
    $rows.='<tr style="cursor:pointer;background:'.$bg.';" onmouseover="this.style.background=\'#eff6ff\'" onmouseout="this.style.background=\''.$bg.'\'" onclick="window.location.href=\'damage.php?mode=edit&vouchno='.$row['vouchno'].'\'">'
        .'<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;color:#64748b;font-weight:600;">DMG#'.$row['vouchno'].'</td>'
        .'<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;">'.$dt.'</td>'
        .'<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;font-weight:500;">'.htmlspecialchars($row['remarks']??'').'</td>'
        .'<td style="padding:8px 14px;border-bottom:1px solid #f1f5f9;text-align:right;font-weight:600;">'.number_format((float)$row['totqty'],2).'</td>'
        .'</tr>';
}
if (!$total) $rows='<tr><td colspan="4" 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]);
