<?php
$_REQUEST['src'] = "ext2";
require_once('../../functions/global.php');

$start = isset($_POST['start']) ? $_POST['start'] : 0;
$length = isset($_POST['length']) ? $_POST['length'] : 10;
$draw = $_POST['draw'];
$order = $_POST['order'][0];
$columnIndex = $order['column'];
$columnName = $_POST['columns'][$columnIndex]['data'];
$columnDirection = $order['dir'];
$clientNumber = $_POST['clientNumber'];
$searchTerm = $_POST['search']['value'];

$query = " SELECT 
itemdetails.*, 
locations.*, 
latest_report.result AS latest_report_result, 
latest_report.insdate AS latest_report_insdate
FROM 
itemdetails 
LEFT JOIN 
locations 
ON 
itemdetails.clientnumber = locations.clientnumber 
AND itemdetails.locnumber = locations.locnumber
LEFT JOIN (
SELECT 
    clientnumber, 
    itemnumber, 
    result, 
    insdate,
    ROW_NUMBER() OVER (PARTITION BY clientnumber, itemnumber ORDER BY insdate DESC) as rn
FROM 
    reportitems
) AS latest_report 
ON 
itemdetails.clientnumber = latest_report.clientnumber 
AND itemdetails.itemnumber = latest_report.itemnumber
AND latest_report.rn = 1
WHERE 
itemdetails.clientnumber = ? 
AND itemdetails.statuslive = '1' 
AND (
    itemdetails.itemnumber LIKE ? 
    OR itemdetails.plantnumber LIKE ? 
    OR itemdetails.serialnumber LIKE ? 
    OR locations.postcode LIKE ?
)
ORDER BY 
$columnName $columnDirection
LIMIT 
?, ?";

$searchTermWithWildcards = '%' . $searchTerm . '%';

$stmt = $con->prepare($query);
$stmt->bind_param("issssii", $clientNumber, $searchTermWithWildcards, $searchTermWithWildcards, $searchTermWithWildcards, $searchTermWithWildcards, $start, $length);
$stmt->execute();
$resultFiltered = $stmt->get_result();

$data = array();
while ($row = $resultFiltered->fetch_assoc()) {
    $data[] = $row;
}

// Count the total filtered records (for the current page)
$filteredRecords = count($data);

// Construct your SQL query for total records without limit
$queryTotal = "SELECT COUNT(*) AS totalRecords FROM itemdetails 
    WHERE clientnumber = ? AND `statuslive`=1 AND 
    (itemnumber LIKE ? OR plantnumber LIKE ? OR serialnumber LIKE ?)";

$stmtTotal = $con->prepare($queryTotal);
$stmtTotal->bind_param("isss", $clientNumber, $searchTermWithWildcards, $searchTermWithWildcards, $searchTermWithWildcards);
$stmtTotal->execute();
$resultTotal = $stmtTotal->get_result();
$totalRecords = mysqli_fetch_assoc($resultTotal)['totalRecords'];

// Prepare response for DataTables
$response = array(
    "draw" => intval($draw),
    "recordsTotal" => $totalRecords, // Total records in your database table
    "recordsFiltered" => $totalRecords, // Total records after applying search criteria and limit
    "data" => $data // Data to be displayed in the DataTable
);

echo json_encode($response);
?>