<?php
require_once __DIR__ . '/common.php';

$api = enrep_api_require_key();
$clientnumber = enrep_request_int('clientnumber', 0);
$itemnumber = enrep_request_int('itemnumber', 0);
$locnumber = enrep_request_int('locnumber', 0);
$includeArchived = enrep_request_int('include_archived', 0) === 1;
$page = enrep_api_page();
$limit = (int)$page['per_page'];
$offset = (int)$page['offset'];

$statusSql = $includeArchived ? '' : ' AND i.`statuslive`=1';
$dateSql = '';
$dateSql .= enrep_api_unix_exact_date_filter('i.`currdate`', 'last_examination_date');
$dateSql .= enrep_api_unix_exact_date_filter('i.`duedate`', 'next_examination_due_date');
$dateSql .= enrep_api_unix_date_filter('i.`currdate`', 'last_examination_from', 'last_examination_to');
$dateSql .= enrep_api_unix_date_filter('i.`duedate`', 'next_examination_due_from', 'next_examination_due_to');
$rows = [];

if ($itemnumber > 0 && $clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT i.*, l.`locname`, l.`postcode` AS site_postcode
        FROM `itemdetails` i
        LEFT JOIN `locations` l ON l.`locnumber` = i.`locnumber` AND l.`clientnumber` = i.`clientnumber`
        WHERE i.`clientnumber`=? AND i.`itemnumber`=? $statusSql $dateSql
        LIMIT 1
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Asset lookup unavailable');
    }
    $stmt->bind_param('ii', $clientnumber, $itemnumber);
} elseif ($itemnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT i.*, l.`locname`, l.`postcode` AS site_postcode
        FROM `itemdetails` i
        LEFT JOIN `locations` l ON l.`locnumber` = i.`locnumber` AND l.`clientnumber` = i.`clientnumber`
        WHERE i.`itemnumber`=? $statusSql $dateSql
        LIMIT 1
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Asset lookup unavailable');
    }
    $stmt->bind_param('i', $itemnumber);
} elseif ($locnumber > 0 && $clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT i.*, l.`locname`, l.`postcode` AS site_postcode
        FROM `itemdetails` i
        LEFT JOIN `locations` l ON l.`locnumber` = i.`locnumber` AND l.`clientnumber` = i.`clientnumber`
        WHERE i.`clientnumber`=? AND i.`locnumber`=? $statusSql $dateSql
        ORDER BY i.`desc` ASC, i.`itemnumber` ASC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Asset lookup unavailable');
    }
    $stmt->bind_param('iiii', $clientnumber, $locnumber, $limit, $offset);
} elseif ($locnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT i.*, l.`locname`, l.`postcode` AS site_postcode
        FROM `itemdetails` i
        LEFT JOIN `locations` l ON l.`locnumber` = i.`locnumber` AND l.`clientnumber` = i.`clientnumber`
        WHERE i.`locnumber`=? $statusSql $dateSql
        ORDER BY i.`desc` ASC, i.`itemnumber` ASC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Asset lookup unavailable');
    }
    $stmt->bind_param('iii', $locnumber, $limit, $offset);
} elseif ($clientnumber > 0) {
    $stmt = $GLOBALS['con']->prepare("
        SELECT i.*, l.`locname`, l.`postcode` AS site_postcode
        FROM `itemdetails` i
        LEFT JOIN `locations` l ON l.`locnumber` = i.`locnumber` AND l.`clientnumber` = i.`clientnumber`
        WHERE i.`clientnumber`=? $statusSql $dateSql
        ORDER BY l.`locname` ASC, i.`subloc` ASC, i.`desc` ASC, i.`itemnumber` ASC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Asset lookup unavailable');
    }
    $stmt->bind_param('iii', $clientnumber, $limit, $offset);
} else {
    $stmt = $GLOBALS['con']->prepare("
        SELECT i.*, l.`locname`, l.`postcode` AS site_postcode
        FROM `itemdetails` i
        LEFT JOIN `locations` l ON l.`locnumber` = i.`locnumber` AND l.`clientnumber` = i.`clientnumber`
        WHERE 1=1 $statusSql $dateSql
        ORDER BY l.`locname` ASC, i.`subloc` ASC, i.`desc` ASC, i.`itemnumber` ASC
        LIMIT ? OFFSET ?
    ");
    if (!$stmt) {
        enrep_api_fail(500, 'Asset lookup unavailable');
    }
    $stmt->bind_param('ii', $limit, $offset);
}

$stmt->execute();
$result = $stmt->get_result();
$stmt->close();

while ($row = mysqli_fetch_assoc($result)) {
    $rows[] = [
        'clientnumber' => (int)$row['clientnumber'],
        'locnumber' => (int)$row['locnumber'],
        'itemnumber' => (int)$row['itemnumber'],
        'site_name' => enrep_api_nullable_string($row['locname'] ?? ''),
        'site_postcode' => enrep_api_nullable_string($row['site_postcode'] ?? ''),
        'asset_code' => enrep_api_nullable_string($row['code'] ?? ''),
        'asset_description' => enrep_api_nullable_string($row['desc'] ?? ''),
        'safe_working_load' => enrep_api_nullable_string($row['swl'] ?? ''),
        'plant_number' => enrep_api_nullable_string($row['plantnumber'] ?? ''),
        'serial_number' => enrep_api_nullable_string($row['serialnumber'] ?? ''),
        'ancillary_number' => enrep_api_nullable_string($row['ancillarynumber'] ?? ''),
        'manufacturer' => enrep_api_nullable_string($row['manf'] ?? ''),
        'model' => enrep_api_nullable_string($row['model'] ?? ''),
        'date_of_manufacture' => enrep_api_nullable_string($row['dateofmanf'] ?? ''),
        'sub_location' => enrep_api_nullable_string($row['subloc'] ?? ''),
        'detailed_location' => enrep_api_nullable_string($row['detailedloc'] ?? ''),
        'last_examination_date' => enrep_api_date($row['currdate'] ?? ''),
        'next_examination_due_date' => enrep_api_date($row['duedate'] ?? ''),
        'last_examination_result' => enrep_api_nullable_string($row['lastReport'] ?? ''),
        'condition' => enrep_api_nullable_string($row['condition'] ?? ''),
        'regulations' => enrep_api_nullable_string($row['regulations'] ?? ''),
        'report_type' => enrep_api_nullable_string($row['reptype'] ?? ''),
        'linked_chain' => enrep_api_nullable_string($row['linked'] ?? ''),
        'nfc_reference' => enrep_api_nullable_string($row['nfc'] ?? ''),
        'notes' => enrep_api_nullable_string($row['itemnotes'] ?? ''),
        'is_live' => (int)($row['statuslive'] ?? 0) === 1,
    ];
}

enrep_api_json([
    'ok' => true,
    'data' => $itemnumber > 0 ? ($rows[0] ?? null) : $rows,
    'meta' => $itemnumber > 0 ? null : enrep_api_meta($page, count($rows)),
]);
