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

$tenant = enrep_tenant_segment($_POST['tenant'] ?? $_GET['tenant'] ?? null);
if ($tenant !== '' && !defined('CONFIG_LOADED')) {
    require_once '../../' . $tenant . '/config.php';
}

assetmanager_require_user();

$con = $GLOBALS['con'] ?? null;
if (!$con instanceof mysqli) {
    assetmanager_json_response(['success' => false, 'message' => 'Tenant database connection unavailable.', 'rows' => []]);
}
$con->set_charset('utf8mb4');

$clientnumber = enrep_request_int('clientnumber', 0);
if ($clientnumber <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Client number is required.', 'rows' => []]);
}
assetmanager_json_require_client_access($con, $clientnumber);
if (!assetmanager_client_enabled($con, $tenant, $clientnumber)) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset Manager is not enabled for this client.', 'rows' => []]);
}

$rows = [];
$supplements = [];
$includeEnrepAssets = assetmanager_enrep_assets_enabled($con, $tenant, $clientnumber);

if ($includeEnrepAssets && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT source_itemnumber, custom_fields_json, status_key
        FROM assetmanager_assets
        WHERE clientnumber=?
          AND tenant_key=?
          AND source_type='enrep_item'
          AND source_itemnumber IS NOT NULL
          AND archived='0'
    ");
    if ($stmt) {
        $stmt->bind_param('is', $clientnumber, $tenant);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $itemnumber = (int)($row['source_itemnumber'] ?? 0);
            if ($itemnumber > 0) {
                $supplement = assetmanager_decode_json($row['custom_fields_json'] ?? '');
                $supplement['status_key'] = (string)($row['status_key'] ?? '');
                $supplements[$itemnumber] = $supplement;
            }
        }
        $stmt->close();
    }
}

if ($includeEnrepAssets) {
    [$siteSql, $siteTypes, $siteParams] = assetmanager_client_site_filter_sql($con, $clientnumber, 'a.locnumber');
    $stmt = $con->prepare("
        SELECT
            a.itemnumber,
            a.desc,
            a.plantnumber,
            a.serialnumber,
            a.manf,
            a.model,
            a.dateofmanf,
            a.duedate,
            a.lastReport,
            a.subloc,
            a.statuslive,
            l.locname
        FROM itemdetails a
        LEFT JOIN locations l ON l.locnumber = a.locnumber
        WHERE a.clientnumber=?
          AND a.statuslive='1'
          {$siteSql}
        ORDER BY a.desc ASC, a.plantnumber ASC
    ");
    if ($stmt) {
        $types = 'i' . $siteTypes;
        $params = array_merge([$clientnumber], $siteParams);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $itemnumber = (int)($row['itemnumber'] ?? 0);
            $supplement = $supplements[$itemnumber] ?? [];
            $nickname = trim((string)($supplement['nickname'] ?? ''));
            $inspectionSubloc = trim((string)($row['subloc'] ?? ''));
            $liveSubloc = trim((string)($supplement['live_subloc'] ?? ''));
            if ($liveSubloc === '') {
                $liveSubloc = $inspectionSubloc;
            }
            $rows[] = [
                'source' => 'enrep_item',
                'source_label' => 'Scheduled',
                'asset_id' => 0,
                'itemnumber' => $itemnumber,
                'title' => $nickname !== '' ? $nickname : (string)($row['desc'] ?? ''),
                'master_title' => (string)($row['desc'] ?? ''),
                'plantnumber' => (string)($row['plantnumber'] ?? ''),
                'serialnumber' => (string)($row['serialnumber'] ?? ''),
                'registration_mark' => (string)($supplement['registration_mark'] ?? ''),
                'manufacturer' => (string)($row['manf'] ?? ''),
                'model' => (string)($row['model'] ?? ''),
                'dateofmanf' => !empty($row['dateofmanf']) ? date('d-m-Y', (int) $row['dateofmanf']) : '',
                'location' => (string)($row['locname'] ?? ''),
                'subloc' => $liveSubloc,
                'live_subloc' => $liveSubloc,
                'inspection_subloc' => $inspectionSubloc,
                'subloc_source' => trim($liveSubloc) !== trim($inspectionSubloc) ? 'assetmanager_live' : 'enrep_inspection',
                'status' => (string)($supplement['operational_status'] ?? $supplement['status_key'] ?? 'active'),
                'asset_class' => (string)($supplement['asset_class'] ?? ''),
                'hire_enabled' => !empty($supplement['hire_enabled']) || (string)($supplement['asset_class'] ?? '') === 'hire_plant' ? 1 : 0,
                'inspection_result' => (string)($row['lastReport'] ?? ''),
                'duedate' => !empty($row['duedate']) ? date('d-m-Y', (int) $row['duedate']) : '',
                'protected' => true,
                'supplement' => $supplement,
            ];
        }
        $stmt->close();
    }
}

if (assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT id, asset_title, plantnumber, serialnumber, status_key, core_fields_json, custom_fields_json, module_data_json
        FROM assetmanager_assets
        WHERE clientnumber=?
          AND tenant_key=?
          AND source_type='assetmanager_item'
          AND archived='0'
        ORDER BY asset_title ASC, plantnumber ASC
    ");
    if ($stmt) {
        $stmt->bind_param('is', $clientnumber, $tenant);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $core = assetmanager_decode_json($row['core_fields_json'] ?? '');
            $custom = assetmanager_decode_json($row['custom_fields_json'] ?? '');
            $moduleData = assetmanager_decode_json($row['module_data_json'] ?? '');
            $liveSubloc = trim((string)($custom['live_subloc'] ?? ''));
            if ($liveSubloc === '') {
                $liveSubloc = (string)($custom['subloc'] ?? '');
            }
            $rows[] = [
                'source' => 'assetmanager_item',
                'source_label' => 'Added',
                'asset_id' => (int)($row['id'] ?? 0),
                'itemnumber' => 0,
                'title' => (string)($row['asset_title'] ?? ''),
                'plantnumber' => (string)($row['plantnumber'] ?? ''),
                'serialnumber' => (string)($row['serialnumber'] ?? ''),
                'registration_mark' => (string)($custom['registration_mark'] ?? $core['registration_mark'] ?? ''),
                'manufacturer' => (string)($core['manufacturer'] ?? ''),
                'model' => (string)($core['model'] ?? ''),
                'dateofmanf' => (string)($core['dateofmanf'] ?? ''),
                'location' => (string)($custom['location_label'] ?? ''),
                'subloc' => $liveSubloc,
                'live_subloc' => $liveSubloc,
                'inspection_subloc' => '',
                'subloc_source' => 'assetmanager_live',
                'status' => (string)($row['status_key'] ?? 'active'),
                'asset_class' => (string)($custom['asset_class'] ?? ''),
                'hire_enabled' => !empty($custom['hire_enabled']) || (string)($custom['asset_class'] ?? '') === 'hire_plant' ? 1 : 0,
                'inspection_result' => '',
                'duedate' => '',
                'protected' => false,
                'module_data' => $moduleData,
            ];
        }
        $stmt->close();
    }
}

assetmanager_json_response([
    'success' => true,
    'rows' => $rows,
    'total' => count($rows),
]);