<?php
$tenant = trim((string)($_REQUEST['tenant'] ?? ''));
$tenant = trim($tenant, "/\\ \t\n\r\0\x0B");

if ($tenant !== '' && file_exists('../../' . $tenant . '/config.php')) {
    require_once('../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

function printScheduleDefaultPrefs(): array
{
    return [
        'itemnumber'   => ['label' => 'Item ID',      'visible' => true],
        'description'  => ['label' => 'Description',  'visible' => true],
        'manufacturer' => ['label' => 'Manufacturer', 'visible' => true],
        'make_model'   => ['label' => 'Make/Model',   'visible' => true],
        'type'         => ['label' => 'Type',         'visible' => true],
        'condition'    => ['label' => 'Condition',    'visible' => true],
        'plantnumber'  => ['label' => 'Plant No.',    'visible' => true],
        'serialnumber' => ['label' => 'Serial',       'visible' => true],
        'locname'      => ['label' => 'Location',     'visible' => true],
        'subloc'       => ['label' => 'Sub-location', 'visible' => true],
        'postcode'     => ['label' => 'Post Code',    'visible' => true],
        'lastReport'   => ['label' => 'Result',       'visible' => true],
        'duedate'      => ['label' => 'Due',          'visible' => true],
    ];
}

function printScheduleNormalisePrefs($prefs): array
{
    $defaults = printScheduleDefaultPrefs();
    $prefs = is_array($prefs) ? $prefs : [];

    if (isset($prefs['model']) && !isset($prefs['make_model'])) {
        $prefs['make_model'] = $prefs['model'];
    }

    foreach ($defaults as $key => $default) {
        if (!isset($prefs[$key]) || !is_array($prefs[$key])) {
            $prefs[$key] = $default;
            continue;
        }

        $prefs[$key]['label'] = isset($prefs[$key]['label']) && trim((string)$prefs[$key]['label']) !== ''
            ? (string)$prefs[$key]['label']
            : $default['label'];

        if (array_key_exists('visible', $prefs[$key])) {
            $prefs[$key]['visible'] = (bool)$prefs[$key]['visible'];
        } elseif (array_key_exists('enabled', $prefs[$key])) {
            $prefs[$key]['visible'] = (bool)$prefs[$key]['enabled'];
        } else {
            $prefs[$key]['visible'] = (bool)$default['visible'];
        }
    }

    return $prefs;
}

function printScheduleLoadPrefs(mysqli $con): array
{
    $prefs = [];

    $stmt = $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;
            }
        }
        $stmt->close();
    }

    return printScheduleNormalisePrefs($prefs);
}

function printScheduleColumnVisible(array $prefs, string $key): bool
{
    return !isset($prefs[$key]['visible']) || (bool)$prefs[$key]['visible'];
}

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

function printScheduleValue($value): string
{
    return htmlspecialchars((string)($value ?? ''), ENT_QUOTES, 'UTF-8');
}

function printScheduleColumnExists(mysqli $con, string $table, string $column): bool
{
    $stmt = $con->prepare("
        SELECT COUNT(*)
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE TABLE_SCHEMA = DATABASE()
          AND TABLE_NAME = ?
          AND COLUMN_NAME = ?
    ");
    if (!$stmt) {
        return false;
    }

    $stmt->bind_param('ss', $table, $column);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    return (int)$count > 0;
}

function printScheduleStatusClass(int $dueDate): array
{
    if ($dueDate < 1) {
        return ['status_colour color secondary-color', 'No Date Stored'];
    }

    $now = time();
    if ($dueDate < $now) {
        return ['status_colour color danger-color-dark', 'Overdue'];
    }
    if ($dueDate < strtotime('+1 month', $now)) {
        return ['status_colour color warning-color-dark', 'Pending'];
    }

    return ['status_colour color success-color-dark', 'Not Due'];
}

function printScheduleResultBadge($result): string
{
    $result = trim((string)$result);
    if ($result === '') {
        return '<span class="badge badge-pill bg-light text-dark" style="font-size:10px">N/E</span>';
    }

    $upper = strtoupper($result);
    $class = 'secondary-color';
    if (in_array($upper, ['PASS', 'SATISFACTORY'], true)) {
        $class = 'success-color-dark';
    } elseif (in_array($upper, ['FAIL', 'UNSATISFACTORY', 'URGENT'], true)) {
        $class = 'danger-color-dark';
    } elseif ($upper === 'DEFECTS') {
        $class = 'warning-color-dark';
    } elseif ($upper === 'OBS') {
        $class = 'special-color';
    } elseif ($upper === 'PNA') {
        $class = 'stylish-color-dark';
    }

    return '<span class="badge badge-pill d-block ' . $class . ' text-light" style="font-size:10px">' . printScheduleValue($result) . '</span>';
}

function printScheduleRenderCell(string $key, array $row): string
{
    switch ($key) {
        case 'itemnumber':
            return printScheduleValue($row['itemnumber'] ?? '');
        case 'description':
            $description = printScheduleValue($row['description'] ?? '');
            $frequency = trim((string)($row['frequency'] ?? ''));
            if ($frequency !== '') {
                $description .= ' <span class="badge badge-pill unique-color-dark text-light" style="font-size:9px">' . printScheduleValue($frequency) . '</span>';
            }
            return $description;
        case 'manufacturer':
            return printScheduleValue($row['manf'] ?? '');
        case 'make_model':
            return printScheduleValue($row['model'] ?? '');
        case 'type':
            return printScheduleValue(($row['system_type'] ?? '') !== '' ? $row['system_type'] : ($row['code'] ?? ''));
        case 'condition':
            return printScheduleValue($row['asset_condition'] ?? '');
        case 'plantnumber':
            return printScheduleValue($row['plantnumber'] ?? '');
        case 'serialnumber':
            return printScheduleValue($row['serialnumber'] ?? '');
        case 'locname':
            return printScheduleValue($row['locname'] ?? '');
        case 'subloc':
            return printScheduleValue($row['subloc'] ?? '');
        case 'postcode':
            return printScheduleValue($row['postcode'] ?? '');
        case 'lastReport':
            return printScheduleResultBadge($row['lastReport'] ?? '');
        case 'duedate':
            $dueDate = (int)($row['duedate'] ?? 0);
            return $dueDate > 0 ? date('d-m-Y', $dueDate) : '<span class="badge badge-pill bg-light text-dark" style="font-size:10px">NDS</span>';
    }

    return '';
}

$con = $GLOBALS['con'] ?? null;
if (!$con instanceof mysqli) {
    echo '<div class="alert alert-danger">Unable to load schedule: database connection not available.</div>';
    exit;
}

$con->set_charset('utf8mb4');

$clientnumber = (int)($_REQUEST['clientnumber'] ?? 0);
$location = (int)($_REQUEST['location'] ?? 0);
$locationName = trim((string)($_REQUEST['name'] ?? ''));

$prefs = printScheduleLoadPrefs($con);
$columnOrder = [
    'itemnumber',
    'description',
    'manufacturer',
    'make_model',
    'type',
    'condition',
    'plantnumber',
    'serialnumber',
    'locname',
    'subloc',
    'postcode',
    'lastReport',
    'duedate',
];

$visibleColumns = array_values(array_filter($columnOrder, static function ($key) use ($prefs) {
    return printScheduleColumnVisible($prefs, $key);
}));

if (empty($visibleColumns)) {
    $visibleColumns = ['itemnumber', 'description', 'duedate'];
}

$hasPlantFrequency = printScheduleColumnExists($con, 'dd_plant', 'frequency');
$hasSystemType = printScheduleColumnExists($con, 'itemdetails', 'system_type');
$hasAssetCondition = printScheduleColumnExists($con, 'itemdetails', 'asset_condition');

$frequencySelect = $hasPlantFrequency ? "COALESCE(dp.frequency, '') AS frequency" : "'' AS frequency";
$systemTypeSelect = $hasSystemType ? "COALESCE(a.system_type, '') AS system_type" : "'' AS system_type";
$assetConditionSelect = $hasAssetCondition ? "COALESCE(a.asset_condition, '') AS asset_condition" : "'' AS asset_condition";
$plantJoin = $hasPlantFrequency ? "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.statuslive = '1'";
$types = 'i';
$params = [$clientnumber];

if ($location > 0) {
    $where .= " AND a.locnumber = ?";
    $types .= 'i';
    $params[] = $location;
}

$sql = "
    SELECT
        a.itemnumber,
        a.locnumber,
        a.`desc` AS description,
        a.code,
        a.plantnumber,
        a.serialnumber,
        a.model,
        a.dateofmanf,
        a.manf,
        a.duedate,
        a.lastReport,
        a.subloc,
        b.locname,
        b.postcode,
        {$frequencySelect},
        {$systemTypeSelect},
        {$assetConditionSelect}
    FROM itemdetails a
    LEFT JOIN locations b ON a.locnumber = b.locnumber
    {$plantJoin}
    WHERE {$where}
    ORDER BY
        CASE WHEN a.duedate IS NULL OR a.duedate = 0 THEN 1 ELSE 0 END ASC,
        a.duedate ASC,
        a.itemnumber ASC
";

$stmt = $con->prepare($sql);
if (!$stmt) {
    echo '<div class="alert alert-danger">Unable to load schedule: ' . printScheduleValue(mysqli_error($con)) . '</div>';
    exit;
}

$stmt->bind_param($types, ...$params);
$stmt->execute();
$items = $stmt->get_result();
$stmt->close();

$rowsHtml = '';
while ($row = mysqli_fetch_assoc($items)) {
    [$statusClass, $statusTitle] = printScheduleStatusClass((int)($row['duedate'] ?? 0));

    $rowsHtml .= '<tr>';
    $rowsHtml .= '<td class="' . $statusClass . '" style="width:20px"><div class="' . $statusClass . '" style="font-size:0">' . printScheduleValue($statusTitle) . '</div></td>';

    foreach ($visibleColumns as $key) {
        $class = $key === 'lastReport' ? ' class="text-center p-0"' : '';
        $rowsHtml .= '<td' . $class . '>' . printScheduleRenderCell($key, $row) . '</td>';
    }

    $rowsHtml .= '</tr>';
}

$headersHtml = '<th class="no-sort noExport text-center p-0" width="20px">&nbsp;</th>';
foreach ($visibleColumns as $key) {
    $class = $key === 'duedate' ? ' class="date-uk"' : '';
    $headersHtml .= '<th' . $class . '>' . printScheduleColumnLabel($prefs, $key) . '</th>';
}

$clientName = function_exists('getClientName') ? getClientName($clientnumber) : '';
$clientAddress = function_exists('getClientAddress') ? getClientAddress($clientnumber) : '';
$locationSuffix = $location > 0 && $locationName !== '' ? '@ ' . $locationName : '';

$pdf = '
<table class="table table-sm" width="100%">
<tbody>
<tr valign="top">
<td width="80%" valign="top"><h3>Schedule - ' . printScheduleValue($clientName) . ' ' . printScheduleValue($locationSuffix) . '</h3></td>
<td width="20%" align="right" valign="top" style="font-family: serif; font-size: 8pt; color: #000000; font-weight: bold;">' . $clientAddress . '</td>
</tr>
</tbody>
</table>

<table id="coverDetails" class="table table-sm table-striped" width="100%">
<thead class="table-dark headRow text-light">
<tr class="headrow">
' . $headersHtml . '
</tr>
</thead>
<tbody>
' . $rowsHtml . '
</tbody>
</table>';

echo $pdf;
?>
