0 THEN d.ClientID ELSE COALESCE(t.ClientID,o.customer_id,0) END AS CustomerID, COALESCE(NULLIF(d.order_id,0),NULLIF(o.parent_order_id,0),t.OrderID) AS ShippingOrderID, (SELECT MAX(h.TransactionDate) FROM ClientDeviceTransactionHistory h WHERE h.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND h.DeviceID=d.DeviceID AND h.EventType='device_shipped') AS ShippedAt, CASE WHEN d.ClientID>0 THEN 'registered' WHEN d.order_id>0 OR EXISTS ( SELECT 1 FROM ClientDeviceTransactionHistory h WHERE h.ClientDeviceTransactionID=t.ClientDeviceTransactionID AND h.DeviceID=d.DeviceID AND h.EventType='device_shipped' ) THEN 'shipped' WHEN EXISTS (SELECT 1 FROM ClientDeviceTransaction tx WHERE (tx.DeviceID<>'' AND tx.DeviceID=d.DeviceID) OR (tx.ICCID<>'' AND tx.ICCID=d.ICCID) OR (tx.SimHash<>'' AND tx.SimHash=d.SimHash)) THEN 'linked' ELSE 'in_stock' END AS TrackerStatus FROM ClientDevices d LEFT JOIN ClientDeviceTransaction t ON t.ClientDeviceTransactionID=( SELECT t2.ClientDeviceTransactionID FROM ClientDeviceTransaction t2 WHERE t2.DeviceID=d.DeviceID AND t2.DeviceID<>'' AND t2.ClientID>0 ORDER BY t2.ClientDeviceTransactionID DESC LIMIT 1) LEFT JOIN wp_wc_orders o ON o.id=COALESCE(NULLIF(d.order_id,0),t.OrderID)"; } private static function rows(PDO $db,$sql,array $args=[]) { $s=$db->prepare($sql); if(!$s || !$s->execute($args)) throw new RuntimeException('Inventory query failed'); return $s->fetchAll(PDO::FETCH_ASSOC); } public static function load(PDO $db,array $input) { $base=self::baseSQL(); $totals=['in_stock'=>0,'shipped'=>0,'registered'=>0,'linked'=>0]; foreach(self::rows($db,'SELECT TrackerStatus,COUNT(*) AS n FROM ('.$base.') inv GROUP BY TrackerStatus') as $r) { $totals[$r['TrackerStatus']]=(int)$r['n']; } $status=is_string($input['tracker_status']??null)?$input['tracker_status']:'all'; if(!array_key_exists($status,$totals)) $status='all'; $search=is_string($input['search']??null)?substr(trim($input['search']),0,120):''; $where=[];$args=[]; if($status!=='all') {$where[]='inv.TrackerStatus=?';$args[]=$status;} if($search!=='') { // Literal substring, with an additional dashless tracker-code match. $term='%'.strtr($search,['!'=>'!!','%'=>'!%','_'=>'!_']).'%'; $where[]="(inv.SimHash LIKE ? ESCAPE '!' OR inv.DeviceID LIKE ? ESCAPE '!' OR inv.ICCID LIKE ? ESCAPE '!' OR inv.NameTag LIKE ? ESCAPE '!' OR REPLACE(inv.SimHash,'-','') LIKE ? ESCAPE '!')"; $args=array_merge($args,[$term,$term,$term,$term,str_replace('-','',$term)]); } $whereSQL=$where?' WHERE '.implode(' AND ',$where):''; $count=self::rows($db,'SELECT COUNT(*) AS n FROM ('.$base.') inv'.$whereSQL,$args); $total=(int)$count[0]['n']; $size=25; $page=max(1,min((int)($input['page']??1),max(1,(int)ceil($total/$size)))); $offset=($page-1)*$size; $pageSQL='SELECT inv.* FROM ('.$base.') inv'.$whereSQL.' ORDER BY inv.SimHash,inv.ClientDevicesID LIMIT '.$size.' OFFSET '.$offset; $rows=self::rows($db,"SELECT p.*, COALESCE(NULLIF(TRIM(CONCAT(COALESCE(a.FirstName,''),' ',COALESCE(a.LastName,''))),''), NULLIF(TRIM(CONCAT(COALESCE(b.first_name,''),' ',COALESCE(b.last_name,''))),''),'') AS CustomerName, COALESCE(NULLIF(l.Email,''),NULLIF(c.UserName,''),b.email,'') AS CustomerEmail FROM (".$pageSQL.") p LEFT JOIN Client c ON c.ClientID=p.CustomerID LEFT JOIN ClientAccounts a ON a.ClientID=p.CustomerID AND a.ClientLocationID=( SELECT ca.ClientLocationID FROM ClientAccounts ca WHERE ca.ClientID=p.CustomerID AND ca.RecordStatus=1 ORDER BY ca.UpdateDateTime DESC,ca.ClientLocationID DESC LIMIT 1) LEFT JOIN ClientLocation l ON l.ClientLocationID=a.ClientLocationID AND l.ClientID=p.CustomerID AND l.RecordStatus=1 LEFT JOIN wp_wc_order_addresses b ON b.order_id=p.ShippingOrderID AND b.address_type='billing' ORDER BY p.SimHash,p.ClientDevicesID",$args); return ['inventory'=>$rows,'tracker_totals'=>$totals,'inventory_page'=>$page, 'inventory_page_size'=>$size,'inventory_total'=>$total]; } }