<?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.', 'notices' => []]);
}
$con->set_charset('utf8mb4');

$clientnumber = enrep_request_int('clientnumber', 0);
if ($clientnumber <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Client number is required.', 'notices' => []]);
}
assetmanager_json_require_client_access($con, $clientnumber);
assetmanager_json_require_client_enabled($con, $tenant, $clientnumber);

$settings = assetmanager_get_client_settings($con, $tenant, $clientnumber);
$modules = $settings['modules'] ?? [];
$includeEnrepAssets = !empty($settings['permissions']['include_enrep_assets']);
$assetSourceSql = $includeEnrepAssets ? '' : " AND a.source_type<>'enrep_item'";
$notices = [];

$addNotice = static function (array $notice) use (&$notices): void {
    $severityWeight = ['critical' => 0, 'warning' => 1, 'info' => 2];
    $notice['severity'] = $notice['severity'] ?? 'info';
    $notice['weight'] = $severityWeight[$notice['severity']] ?? 2;
    $notices[] = $notice;
};

$hasReportActionText = static function ($value): bool {
    $text = strtolower(trim((string)($value ?? '')));
    return $text !== '' && !in_array($text, ['n/a', 'na', 'none', 'not applicable', 'null'], true);
};

$shortReportText = static function ($value): string {
    $text = trim(preg_replace('/\s+/', ' ', (string)($value ?? '')));
    if (strlen($text) <= 180) {
        return $text;
    }
    return substr($text, 0, 177) . '...';
};

if (!empty($modules['maintenance']) && assetmanager_table_exists($con, 'assetmanager_maintenance') && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT w.id, w.summary, w.status_key, w.due_at, a.asset_title, a.source_type, a.source_itemnumber, a.id AS asset_id
        FROM assetmanager_maintenance w
        INNER JOIN assetmanager_assets a ON a.id=w.asset_id AND a.tenant_key=w.tenant_key AND a.clientnumber=w.clientnumber
        WHERE w.tenant_key=? AND w.clientnumber=? AND w.record_type='work_order' AND w.status_key IN ('open','in_progress') AND w.due_at IS NOT NULL AND w.due_at < NOW(){$assetSourceSql}
        ORDER BY w.due_at ASC
        LIMIT 5
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $addNotice([
                'severity' => 'critical',
                'module' => 'maintenance',
                'type' => 'job_overdue',
                'title' => 'Overdue job',
                'message' => (string)$row['summary'],
                'meta' => trim((string)$row['asset_title'] . ' | Due ' . assetmanager_format_date($row['due_at'] ?? '')),
                'source' => (string)$row['source_type'],
                'source_id' => (string)$row['source_type'] === 'enrep_item' ? (int)$row['source_itemnumber'] : (int)$row['asset_id'],
            ]);
        }
        $stmt->close();
    }

    if (assetmanager_table_exists($con, 'assetmanager_maintenance')) {
        $stmt = $con->prepare("
            SELECT d.id, d.summary, d.priority_key AS severity_key, d.created_at AS reported_at, a.asset_title, a.source_type, a.source_itemnumber, a.id AS asset_id
            FROM assetmanager_maintenance d
            INNER JOIN assetmanager_assets a ON a.id=d.asset_id AND a.tenant_key=d.tenant_key AND a.clientnumber=d.clientnumber
            WHERE d.tenant_key=? AND d.clientnumber=? AND d.record_type='defect' AND d.status_key IN ('open','in_progress','reported'){$assetSourceSql}
            ORDER BY FIELD(d.priority_key, 'critical', 'high', 'medium', 'low'), d.created_at ASC
            LIMIT 5
        ");
        if ($stmt) {
            $stmt->bind_param('si', $tenant, $clientnumber);
            $stmt->execute();
            $res = $stmt->get_result();
            while ($row = $res->fetch_assoc()) {
                $severity = in_array((string)$row['severity_key'], ['critical', 'high'], true) ? 'critical' : 'warning';
                $addNotice([
                    'severity' => $severity,
                    'module' => 'maintenance',
                    'type' => 'defect_open',
                    'title' => 'Open defect',
                    'message' => (string)$row['summary'],
                    'meta' => trim((string)$row['asset_title'] . ' | ' . (string)$row['severity_key']),
                    'source' => (string)$row['source_type'],
                    'source_id' => (string)$row['source_type'] === 'enrep_item' ? (int)$row['source_itemnumber'] : (int)$row['asset_id'],
                ]);
            }
            $stmt->close();
        }
    }

    if (assetmanager_table_exists($con, 'assetmanager_maintenance')) {
        $stmt = $con->prepare("
            SELECT s.id, s.summary AS schedule_type, s.due_at AS next_due_at, a.asset_title, a.source_type, a.source_itemnumber, a.id AS asset_id
            FROM assetmanager_maintenance s
            INNER JOIN assetmanager_assets a ON a.id=s.asset_id AND a.tenant_key=s.tenant_key AND a.clientnumber=s.clientnumber
            WHERE s.tenant_key=? AND s.clientnumber=? AND s.record_type='schedule' AND s.status_key='active' AND s.due_at IS NOT NULL AND s.due_at < NOW(){$assetSourceSql}
            ORDER BY s.due_at ASC
            LIMIT 5
        ");
        if ($stmt) {
            $stmt->bind_param('si', $tenant, $clientnumber);
            $stmt->execute();
            $res = $stmt->get_result();
            while ($row = $res->fetch_assoc()) {
                $addNotice([
                    'severity' => 'warning',
                    'module' => 'maintenance',
                    'type' => 'schedule_overdue',
                    'title' => 'Schedule overdue',
                    'message' => ucwords(str_replace('_', ' ', (string)$row['schedule_type'])),
                    'meta' => trim((string)$row['asset_title'] . ' | Due ' . assetmanager_format_date($row['next_due_at'] ?? '')),
                    'source' => (string)$row['source_type'],
                    'source_id' => (string)$row['source_type'] === 'enrep_item' ? (int)$row['source_itemnumber'] : (int)$row['asset_id'],
                ]);
            }
            $stmt->close();
        }
    }
}

if ($includeEnrepAssets && !empty($modules['maintenance']) && assetmanager_table_exists($con, 'itemdetails') && assetmanager_table_exists($con, 'reportitems')) {
    [$siteSql, $siteTypes, $siteParams] = assetmanager_client_site_filter_sql($con, $clientnumber, 'a.locnumber');
    $stmt = $con->prepare("
        SELECT a.itemnumber, a.desc, a.plantnumber, a.lastReport, l.locname
        FROM itemdetails a
        LEFT JOIN locations l ON l.locnumber=a.locnumber
        WHERE a.clientnumber=?
          AND a.statuslive='1'
          AND UPPER(TRIM(COALESCE(a.lastReport, ''))) IN ('URGENT', 'DEFECTS', 'DEFECT', 'OBS', 'PNA')
          {$siteSql}
        ORDER BY CASE UPPER(TRIM(COALESCE(a.lastReport, '')))
            WHEN 'URGENT' THEN 1
            WHEN 'DEFECTS' THEN 2
            WHEN 'DEFECT' THEN 2
            WHEN 'OBS' THEN 3
            WHEN 'PNA' THEN 4
            ELSE 5
        END, a.desc ASC
        LIMIT 20
    ");
    if ($stmt) {
        $types = 'i' . $siteTypes;
        $params = array_merge([$clientnumber], $siteParams);
        $stmt->bind_param($types, ...$params);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($item = $res->fetch_assoc()) {
            $itemnumber = (int)($item['itemnumber'] ?? 0);
            if ($itemnumber <= 0) {
                continue;
            }

            $latest = [];
            $report = $con->prepare("
                SELECT repnumber, insdate, result, reportdata
                FROM reportitems
                WHERE clientnumber=? AND itemnumber=?
                ORDER BY ABS(repitem) DESC
                LIMIT 1
            ");
            if ($report) {
                $report->bind_param('ii', $clientnumber, $itemnumber);
                $report->execute();
                $latest = $report->get_result()->fetch_assoc() ?: [];
                $report->close();
            }

            $reportData = assetmanager_decode_json($latest['reportdata'] ?? '');
            $lastReport = strtoupper(trim((string)($item['lastReport'] ?? $latest['result'] ?? '')));
            $assetName = trim((string)($item['desc'] ?? 'Asset'));
            $metaParts = array_filter([
                trim((string)($item['plantnumber'] ?? '')),
                trim((string)($item['locname'] ?? '')),
                !empty($latest['repnumber']) ? 'Report ' . (string)$latest['repnumber'] : '',
                !empty($latest['insdate']) ? 'Inspected ' . assetmanager_format_date($latest['insdate']) : '',
            ]);
            $meta = implode(' | ', $metaParts);

            if ($hasReportActionText($reportData['adefect'] ?? '') || $lastReport === 'URGENT') {
                $addNotice([
                    'severity' => 'critical',
                    'module' => 'maintenance',
                    'type' => 'enrep_urgent',
                    'title' => 'Urgent EnRep report',
                    'message' => $assetName,
                    'meta' => $meta,
                    'detail' => $shortReportText($reportData['adefect'] ?? 'Urgent inspection result recorded.'),
                    'source' => 'enrep_item',
                    'source_id' => $itemnumber,
                ]);
            }

            if ($hasReportActionText($reportData['bdefect'] ?? '') || in_array($lastReport, ['DEFECTS', 'DEFECT'], true)) {
                $addNotice([
                    'severity' => 'warning',
                    'module' => 'maintenance',
                    'type' => 'enrep_defect',
                    'title' => 'EnRep defect',
                    'message' => $assetName,
                    'meta' => $meta,
                    'detail' => $shortReportText($reportData['bdefect'] ?? 'Defect inspection result recorded.'),
                    'source' => 'enrep_item',
                    'source_id' => $itemnumber,
                ]);
            }

            if ($hasReportActionText($reportData['obs'] ?? '') || $lastReport === 'OBS') {
                $addNotice([
                    'severity' => 'info',
                    'module' => 'maintenance',
                    'type' => 'enrep_observation',
                    'title' => 'EnRep observation',
                    'message' => $assetName,
                    'meta' => $meta,
                    'detail' => $shortReportText($reportData['obs'] ?? 'Observation recorded on latest inspection.'),
                    'source' => 'enrep_item',
                    'source_id' => $itemnumber,
                ]);
            }

            if ($hasReportActionText($reportData['pnareason'] ?? '') || $lastReport === 'PNA') {
                $addNotice([
                    'severity' => 'warning',
                    'module' => 'maintenance',
                    'type' => 'enrep_pna',
                    'title' => 'Plant not available',
                    'message' => $assetName,
                    'meta' => $meta,
                    'detail' => $shortReportText($reportData['pnareason'] ?? 'Plant was not available for inspection.'),
                    'source' => 'enrep_item',
                    'source_id' => $itemnumber,
                ]);
            }
        }
        $stmt->close();
    }
}

if (!empty($modules['documents']) && assetmanager_table_exists($con, 'assetmanager_documents') && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT f.title AS file_title, f.document_type AS file_type, f.expires_at, a.asset_title, a.source_type, a.source_itemnumber, a.id AS asset_id
        FROM assetmanager_documents f
        INNER JOIN assetmanager_assets a ON a.id=f.asset_id AND a.tenant_key=f.tenant_key AND a.clientnumber=f.clientnumber
        WHERE f.tenant_key=? AND f.clientnumber=? AND f.expires_at IS NOT NULL AND f.expires_at < CURDATE(){$assetSourceSql}
        ORDER BY f.expires_at ASC
        LIMIT 5
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $addNotice([
                'severity' => 'critical',
                'module' => 'documents',
                'type' => 'document_expired',
                'title' => 'Document expired',
                'message' => (string)$row['file_title'],
                'meta' => trim((string)$row['asset_title'] . ' | Expired ' . assetmanager_format_date($row['expires_at'] ?? '')),
                'source' => (string)$row['source_type'],
                'source_id' => (string)$row['source_type'] === 'enrep_item' ? (int)$row['source_itemnumber'] : (int)$row['asset_id'],
            ]);
        }
        $stmt->close();
    }
}

if (!empty($modules['hire']) && assetmanager_table_exists($con, 'assetmanager_hire')) {
    $stmt = $con->prepare("
        SELECT id, reference AS contract_ref, payload_json, ends_at
        FROM assetmanager_hire
        WHERE tenant_key=? AND clientnumber=? AND record_type='contract' AND status_key IN ('active','on_hire','open') AND ends_at IS NOT NULL AND ends_at < NOW()
        ORDER BY ends_at ASC
        LIMIT 5
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $payload = assetmanager_decode_json($row['payload_json'] ?? '');
            $customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
            $addNotice([
                'severity' => 'critical',
                'module' => 'hire',
                'type' => 'hire_overdue',
                'title' => 'Hire overdue',
                'message' => (string)($row['contract_ref'] ?: ($customer['name'] ?? 'Hire contract')),
                'meta' => 'Ended ' . assetmanager_format_date($row['ends_at'] ?? ''),
            ]);
        }
        $stmt->close();
    }
}

if (!empty($modules['fleet']) && assetmanager_table_exists($con, 'assetmanager_activity') && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT f.activity_type AS record_type, JSON_UNQUOTE(JSON_EXTRACT(f.payload_json, '$.due_at')) AS due_at, a.asset_title, a.source_type, a.source_itemnumber, a.id AS asset_id
        FROM assetmanager_activity f
        INNER JOIN assetmanager_assets a ON a.id=f.asset_id AND a.tenant_key=f.tenant_key AND a.clientnumber=f.clientnumber
        WHERE f.tenant_key=? AND f.clientnumber=? AND f.module_key='fleet' AND JSON_UNQUOTE(JSON_EXTRACT(f.payload_json, '$.due_at')) IS NOT NULL AND JSON_UNQUOTE(JSON_EXTRACT(f.payload_json, '$.due_at')) < CURDATE(){$assetSourceSql}
        ORDER BY JSON_UNQUOTE(JSON_EXTRACT(f.payload_json, '$.due_at')) ASC
        LIMIT 5
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $addNotice([
                'severity' => 'critical',
                'module' => 'fleet',
                'type' => 'fleet_overdue',
                'title' => 'Fleet item overdue',
                'message' => ucwords(str_replace('_', ' ', (string)$row['record_type'])),
                'meta' => trim((string)$row['asset_title'] . ' | Due ' . assetmanager_format_date($row['due_at'] ?? '')),
                'source' => (string)$row['source_type'],
                'source_id' => (string)$row['source_type'] === 'enrep_item' ? (int)$row['source_itemnumber'] : (int)$row['asset_id'],
            ]);
        }
        $stmt->close();
    }
}

if (!empty($modules['finance']) && assetmanager_table_exists($con, 'assetmanager_activity')) {
    $stmt = $con->prepare("
        SELECT id, summary AS title, JSON_UNQUOTE(JSON_EXTRACT(payload_json, '$.body')) AS body, created_at
        FROM assetmanager_activity
        WHERE tenant_key=? AND clientnumber=? AND module_key='system' AND activity_type='finance_invoice_required' AND JSON_UNQUOTE(JSON_EXTRACT(payload_json, '$.read_at')) IS NULL
        ORDER BY created_at DESC
        LIMIT 5
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $addNotice([
                'severity' => 'info',
                'module' => 'finance',
                'type' => 'invoice_required',
                'title' => (string)$row['title'],
                'message' => (string)$row['body'],
                'meta' => 'Queued ' . assetmanager_format_date($row['created_at'] ?? ''),
            ]);
        }
        $stmt->close();
    }
}

usort($notices, static function (array $a, array $b): int {
    if (($a['weight'] ?? 2) === ($b['weight'] ?? 2)) {
        return strcmp((string)($a['title'] ?? ''), (string)($b['title'] ?? ''));
    }
    return ((int)($a['weight'] ?? 2)) <=> ((int)($b['weight'] ?? 2));
});

$counts = ['critical' => 0, 'warning' => 0, 'info' => 0];
foreach ($notices as $notice) {
    $severity = (string)($notice['severity'] ?? 'info');
    if (!isset($counts[$severity])) {
        $severity = 'info';
    }
    $counts[$severity]++;
}

$visibleNotices = array_slice($notices, 0, 8);
foreach ($visibleNotices as &$notice) {
    unset($notice['weight']);
}
unset($notice);

assetmanager_json_response([
    'success' => true,
    'counts' => $counts,
    'total' => count($notices),
    'notices' => $visibleNotices,
]);
