<?php
if (isset($_REQUEST['tenant']) && file_exists('../../../' . $_REQUEST['tenant'] . '/config.php')) {
    require_once('../../../' . $_REQUEST['tenant'] . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

$con = $GLOBALS['con'] ?? null;
$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$itemnumber = (int)($_REQUEST['itemnumber'] ?? 0);
$mode = (string)($_REQUEST['mode'] ?? 'details');
$tenant = (string)($_REQUEST['tenant'] ?? (defined('TENANT_URL') ? TENANT_URL : ''));
$rootUrl = defined('ROOT_URL') ? ROOT_URL : '';

if (!$con || $clientnumber < 1 || $itemnumber < 1) {
    echo '<div class="alert alert-danger">Unable to load item.</div>';
    exit;
}

$stmt = $con->prepare("
    SELECT
        a.itemnumber,
        a.clientnumber,
        a.locnumber,
        a.`desc` AS description,
        a.plantnumber,
        a.serialnumber,
        a.model,
        a.manf,
        a.dateofmanf,
        a.swl,
        a.subloc,
        a.code,
        a.lastReport,
        a.duedate,
        a.linked,
        a.itemnotes,
        b.locname,
        b.postcode,
        b.locaddress1,
        b.locaddress2,
        b.locaddress3,
        b.locaddress4,
        b.locnotes,
        COALESCE(dp.frequency, '') AS frequency
    FROM itemdetails a
    LEFT JOIN locations b ON b.locnumber = a.locnumber
    LEFT JOIN (
        SELECT code, MAX(frequency) AS frequency
        FROM dd_plant
        GROUP BY code
    ) dp ON dp.code = a.code
    WHERE a.clientnumber = ? AND a.itemnumber = ?
    LIMIT 1
");
$stmt->bind_param('ii', $clientnumber, $itemnumber);
$stmt->execute();
$res = $stmt->get_result();
$row = $res ? $res->fetch_assoc() : null;
$stmt->close();

if (!$row) {
    echo '<div class="alert alert-warning">Item not found.</div>';
    exit;
}

function assetMobileModalValue($value): string
{
    $value = trim((string)$value);
    return $value !== '' ? htmlspecialchars($value, ENT_QUOTES, 'UTF-8') : '<span class="text-muted">-</span>';
}

function assetMobileModalDate($value): string
{
    $value = (int)$value;
    return $value > 0 ? date('d-m-Y', $value) : '<span class="text-muted">NDS</span>';
}

function assetMobileModalPrefs(): array
{
    $defaults = [
        'itemnumber' => 'Asset ID',
        'description' => 'Description',
        'plantnumber' => 'Plant',
        'serialnumber' => 'Serial',
        'locname' => 'Location',
        'subloc' => 'Sub-location',
        'postcode' => 'Postcode',
        'duedate' => 'Due',
        'lastReport' => 'Result',
        'manufacturer' => 'Manufacturer',
        'make_model' => 'Model',
    ];

    $prefs = [];
    if (!empty($GLOBALS['con'])) {
        $stmt = $GLOBALS['con']->prepare("SELECT `asset_table_prefs` FROM `system` WHERE `id`='1' LIMIT 1");
        if ($stmt) {
            $stmt->execute();
            $stmt->bind_result($prefsJson);
            if ($stmt->fetch() && trim((string)$prefsJson) !== '') {
                $decoded = json_decode((string)$prefsJson, true);
                if (is_array($decoded)) {
                    $prefs = $decoded;
                    if (isset($prefs['model']) && !isset($prefs['make_model'])) {
                        $prefs['make_model'] = $prefs['model'];
                    }
                }
            }
            $stmt->close();
        }
    }

    foreach ($defaults as $key => $label) {
        if (!isset($prefs[$key]['label']) || trim((string)$prefs[$key]['label']) === '') {
            $prefs[$key]['label'] = $label;
        }
    }

    return $prefs;
}

function assetMobileModalLabel(array $prefs, string $key): string
{
    return htmlspecialchars(strtoupper((string)($prefs[$key]['label'] ?? $key)), ENT_QUOTES, 'UTF-8');
}

$assetModalPrefs = assetMobileModalPrefs();

if ($mode === 'actions') {
    $archiveMode = ((string)($_REQUEST['filter'] ?? '') === 'archive') ? 'activate' : 'archive';
    $archiveIcon = $archiveMode === 'activate' ? 'fad fa-upload' : 'fad fa-archive';
    $archiveTitle = $archiveMode === 'activate' ? 'Reinstate' : 'Archive';
    $data = (int)$row['clientnumber'] . '|' . (int)$row['locnumber'] . '|' . (int)$row['itemnumber'];
    $description = htmlspecialchars((string)$row['description'], ENT_QUOTES, 'UTF-8');
    ?>
<div class="asset-modal-action-grid">
    <?php if (trim((string)$row['locnotes']) !== '') { ?>
    <a href="javascript:void(0)" class="btn btn-secondary"
        onclick="loadModalContent('<?= $rootUrl ?>/includes/master/notes.php?type=locations&locnumber=<?= (int)$row['locnumber'] ?>&tenant=<?= htmlspecialchars($tenant, ENT_QUOTES, 'UTF-8') ?>','locationBox','modal-md',1060,'true','Location Notes','close')">
        <i class="fad fa-location-question"></i> Location Notes
    </a>
    <?php } ?>
    <a href="javascript:void(0)" class="btn btn-secondary formButton"
        data-values="<?= $data ?>" data-href="<?= $rootUrl ?>/includes/master/form.php">
        <i class="fad fa-file-alt"></i> New Report
    </a>
    <a href="index.php?t=includes/master&p=items.php&data=<?= $data ?>&view=list" class="btn btn-secondary">
        <i class="fad fa-copy"></i> Complete Reports
    </a>
    <a href="javascript:void(0)" class="btn btn-secondary transferButton"
        data-values="<?= $data ?>|<?= $description ?>" data-href="<?= $rootUrl ?>/includes/master/transfer.php">
        <i class="fad fa-exchange-alt"></i> Move
    </a>
    <a href="javascript:void(0)" class="btn btn-secondary cloneButton"
        data-values="<?= $data ?>|<?= $description ?>" data-href="<?= $rootUrl ?>/includes/master/clone.php">
        <i class="fad fa-clone"></i> Clone
    </a>
    <a href="javascript:void(0)" class="btn btn-secondary archiveButton"
        data-values="<?= $data ?>|<?= $archiveMode ?>" data-href="<?= $rootUrl ?>/includes/master/archive.php">
        <i class="<?= $archiveIcon ?>"></i> <?= $archiveTitle ?>
    </a>
    <a href="index.php?t=includes/master&p=asset.php&view=edit_attached&data=<?= $data ?>" class="btn btn-secondary">
        <i class="fad fa-info-circle"></i> Edit
    </a>
    <?php if (trim((string)$row['itemnotes']) !== '') { ?>
    <a href="javascript:void(0)" class="btn unique-color-dark text-light"
        onclick="loadModalContent('<?= $rootUrl ?>/includes/master/notes.php?type=itemdetails&itemnumber=<?= (int)$row['itemnumber'] ?>&tenant=<?= htmlspecialchars($tenant, ENT_QUOTES, 'UTF-8') ?>','notesBox','modal-md',1060,'true','Item Notes','close')">
        <i class="fad fa-file-exclamation"></i> Item Notes
    </a>
    <?php } ?>
</div>
<style>
.asset-modal-action-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(145px, 1fr));
    gap: .5rem;
}
.asset-modal-action-grid .btn {
    min-height: 44px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: .4rem;
    white-space: normal;
}
</style>
<?php
    exit;
}
?>
<div class="asset-mobile-detail-list">
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'itemnumber') ?>:</span> <?= (int)$row['itemnumber'] ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'description') ?>:</span> <?= assetMobileModalValue($row['description']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'plantnumber') ?>:</span> <?= assetMobileModalValue($row['plantnumber']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'serialnumber') ?>:</span> <?= assetMobileModalValue($row['serialnumber']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'locname') ?>:</span> <?= assetMobileModalValue($row['locname']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'subloc') ?>:</span> <?= assetMobileModalValue($row['subloc']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'postcode') ?>:</span> <?= assetMobileModalValue($row['postcode']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'duedate') ?>:</span> <?= assetMobileModalDate($row['duedate']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'lastReport') ?>:</span> <?= assetMobileModalValue($row['lastReport']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'manufacturer') ?>:</span> <?= assetMobileModalValue($row['manf']) ?></div>
    <div><span><?= assetMobileModalLabel($assetModalPrefs, 'make_model') ?>:</span> <?= assetMobileModalValue($row['model']) ?></div>
    <div><span>DATE OF MANUFACTURE:</span> <?= assetMobileModalValue($row['dateofmanf']) ?></div>
    <div><span>SWL:</span> <?= assetMobileModalValue($row['swl']) ?></div>
    <div><span>FREQUENCY:</span> <?= assetMobileModalValue($row['frequency']) ?></div>
</div>
<style>
.asset-mobile-detail-list {
    display: grid;
    grid-template-columns: repeat(2, minmax(0, 1fr));
    gap: .55rem .9rem;
}
.asset-mobile-detail-list>div {
    padding: .5rem 0;
    border-bottom: 1px solid rgba(0,0,0,.08);
    overflow-wrap: anywhere;
}
.asset-mobile-detail-list span {
    color: #6c757d;
    font-size: .78rem;
    text-transform: uppercase;
    font-weight: 500;
}
@media (max-width: 575.98px) {
    .asset-mobile-detail-list {
        grid-template-columns: 1fr;
    }
}
</style>
