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

$clientnumber = enrep_request_int('clientnumber', 0);
if ($clientnumber <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Client number is required.']);
}
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'";
$dashboard = [
    'open_work_orders' => [],
    'open_defects' => [],
    'due_schedules' => [],
    'expiring_files' => [],
    'active_hires' => [],
    'active_quotes' => [],
    'pending_deliveries' => [],
    'completed_hires' => [],
    'fleet_due' => [],
    'recent_parts' => [],
    'recent_stock_events' => [],
    'notifications' => [],
    'recent_local_assets' => [],
    'inspection_due' => [],
];

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.priority_key, w.due_at, a.source_type, a.source_itemnumber, a.asset_title, 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'){$assetSourceSql}
        ORDER BY w.due_at IS NULL, w.due_at ASC, w.id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['open_work_orders'][] = [
                'id' => (int)$row['id'],
                'summary' => (string)$row['summary'],
                'status' => (string)$row['status_key'],
                'priority' => (string)$row['priority_key'],
                'due_at' => assetmanager_format_date($row['due_at'] ?? ''),
                'asset_title' => (string)$row['asset_title'],
                '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['maintenance']) && assetmanager_table_exists($con, 'assetmanager_maintenance') && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT d.id, d.summary, d.status_key, d.priority_key AS severity_key, d.created_at AS reported_at, a.source_type, a.source_itemnumber, a.asset_title, 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 d.created_at DESC, d.id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['open_defects'][] = [
                'id' => (int)$row['id'],
                'summary' => (string)$row['summary'],
                'status' => (string)$row['status_key'],
                'severity' => (string)$row['severity_key'],
                'reported_at' => assetmanager_format_date($row['reported_at'] ?? ''),
                'asset_title' => (string)$row['asset_title'],
                '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['maintenance']) && assetmanager_table_exists($con, 'assetmanager_maintenance') && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT s.id, s.summary AS schedule_type, s.due_at AS next_due_at, a.source_type, a.source_itemnumber, a.asset_title, 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 <= DATE_ADD(NOW(), INTERVAL 30 DAY){$assetSourceSql}
        ORDER BY s.due_at ASC, s.id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['due_schedules'][] = [
                'id' => (int)$row['id'],
                'type' => (string)$row['schedule_type'],
                'next_due_at' => assetmanager_format_date($row['next_due_at'] ?? ''),
                'asset_title' => (string)$row['asset_title'],
                '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['documents']) && assetmanager_table_exists($con, 'assetmanager_documents') && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT f.id, f.title AS file_title, f.document_type AS file_type, f.expires_at, a.source_type, a.source_itemnumber, a.asset_title, 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 <= DATE_ADD(CURDATE(), INTERVAL 30 DAY){$assetSourceSql}
        ORDER BY f.expires_at ASC, f.id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['expiring_files'][] = [
                'id' => (int)$row['id'],
                'title' => (string)$row['file_title'],
                'type' => (string)$row['file_type'],
                'expires_at' => assetmanager_format_date($row['expires_at'] ?? ''),
                'asset_title' => (string)$row['asset_title'],
                '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, status_key, starts_at, ends_at, payload_json AS contract_payload_json
        FROM assetmanager_hire
        WHERE tenant_key=? AND clientnumber=? AND record_type='contract' AND status_key IN ('pending_signature','active','on_hire','open')
        ORDER BY ends_at IS NULL, ends_at ASC, id DESC
        LIMIT 500
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $payload = assetmanager_decode_json($row['contract_payload_json'] ?? '');
            $customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
            $delivery = is_array($payload['delivery'] ?? null) ? $payload['delivery'] : [];
            $hireAssets = is_array($payload['hire_assets'] ?? null) ? $payload['hire_assets'] : [];
            if (in_array((string)$row['status_key'], ['active', 'on_hire', 'open'], true)) {
                $dashboard['active_hires'][] = [
                    'id' => (int)$row['id'],
                    'contract_ref' => (string)$row['contract_ref'],
                    'customer_name' => (string)($customer['name'] ?? ''),
                    'status' => (string)$row['status_key'],
                    'starts_at' => assetmanager_format_date($row['starts_at'] ?? ''),
                    'ends_at' => assetmanager_format_date($row['ends_at'] ?? ''),
                    'hire_asset' => is_array($payload['hire_asset'] ?? null) ? $payload['hire_asset'] : [],
                    'hire_assets' => $hireAssets,
                    'delivery' => $delivery,
                ];
            }
            if (!empty($delivery['required']) && in_array((string)($delivery['status'] ?? 'pending'), ['pending', 'postponed'], true)) {
                $dashboard['pending_deliveries'][] = [
                    'id' => (int)$row['id'],
                    'contract_ref' => (string)$row['contract_ref'],
                    'customer_name' => (string)($customer['name'] ?? ''),
                    'delivery_status' => (string)($delivery['status'] ?? 'pending'),
                    'delivery_date' => assetmanager_format_date($delivery['delivery_date'] ?? ''),
                    'delivery_time' => (string)($delivery['delivery_time'] ?? ''),
                    'delivery_address' => (string)($delivery['address'] ?? ''),
                    'asset_count' => count($hireAssets) ?: 1,
                ];
            }
        }
        $stmt->close();
    }
}

if (!empty($modules['hire']) && assetmanager_table_exists($con, 'assetmanager_hire')) {
    try {
        $stmt = $con->prepare("
            SELECT id, reference AS contract_ref, status_key, starts_at, ends_at, payload_json AS contract_payload_json
            FROM assetmanager_hire
            WHERE tenant_key=? AND clientnumber=? AND record_type='contract' AND status_key IN ('returned','completed','closed')
            ORDER BY ends_at DESC, id DESC
            LIMIT 100
        ");
        if ($stmt) {
            $stmt->bind_param('si', $tenant, $clientnumber);
            $stmt->execute();
            $res = $stmt->get_result();
            while ($row = $res->fetch_assoc()) {
                $payload = assetmanager_decode_json($row['contract_payload_json'] ?? '');
                $customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
                $hireAssets = is_array($payload['hire_assets'] ?? null) ? $payload['hire_assets'] : (is_array($payload['hire_asset'] ?? null) ? [$payload['hire_asset']] : []);
                $dashboard['completed_hires'][] = [
                    'id' => (int)$row['id'],
                    'contract_ref' => (string)$row['contract_ref'],
                    'customer_name' => (string)($customer['name'] ?? ''),
                    'customer' => $customer,
                    'status' => (string)$row['status_key'],
                    'starts_at' => assetmanager_format_date($row['starts_at'] ?? ''),
                    'ends_at' => assetmanager_format_date($row['ends_at'] ?? ''),
                    'hire_asset' => is_array($payload['hire_asset'] ?? null) ? $payload['hire_asset'] : [],
                    'hire_assets' => $hireAssets,
                    'asset_count' => count($hireAssets),
                ];
            }
            $stmt->close();
        }
    } catch (Throwable $e) {
        $dashboard['completed_hires'] = [];
    }
}

if (!empty($modules['hire']) && assetmanager_table_exists($con, 'assetmanager_hire')) {
    $stmt = $con->prepare("
        SELECT id, reference AS quote_ref, status_key, starts_at, ends_at, payload_json AS quote_payload_json
        FROM assetmanager_hire
        WHERE tenant_key=? AND clientnumber=? AND record_type='quote' AND status_key='quote'
        ORDER BY updated_at DESC, id DESC
        LIMIT 10
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $payload = assetmanager_decode_json($row['quote_payload_json'] ?? '');
            $customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
            $pricing = is_array($payload['pricing'] ?? null) ? $payload['pricing'] : [];
            $dashboard['active_quotes'][] = [
                'id' => (int)$row['id'],
                'quote_ref' => (string)$row['quote_ref'],
                'customer_name' => (string)($customer['name'] ?? ''),
                'status' => (string)$row['status_key'],
                'starts_at' => assetmanager_format_date($row['starts_at'] ?? ''),
                'ends_at' => assetmanager_format_date($row['ends_at'] ?? ''),
                'pricing' => $pricing,
                'hire_asset' => is_array($payload['hire_asset'] ?? null) ? $payload['hire_asset'] : [],
                'hire_assets' => is_array($payload['hire_assets'] ?? null) ? $payload['hire_assets'] : [],
            ];
        }
        $stmt->close();
    }
}

if (!empty($modules['fleet']) && assetmanager_table_exists($con, 'assetmanager_activity') && assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT f.id, f.activity_type AS record_type, JSON_UNQUOTE(JSON_EXTRACT(f.payload_json, '$.status_key')) AS status_key, JSON_UNQUOTE(JSON_EXTRACT(f.payload_json, '$.due_at')) AS due_at, a.source_type, a.source_itemnumber, a.asset_title, 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')) <= DATE_ADD(CURDATE(), INTERVAL 30 DAY){$assetSourceSql}
        ORDER BY JSON_UNQUOTE(JSON_EXTRACT(f.payload_json, '$.due_at')) ASC, f.id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['fleet_due'][] = [
                'id' => (int)$row['id'],
                'record_type' => (string)$row['record_type'],
                'status' => (string)$row['status_key'],
                'due_at' => assetmanager_format_date($row['due_at'] ?? ''),
                'asset_title' => (string)$row['asset_title'],
                '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['parts']) && assetmanager_table_exists($con, 'assetmanager_parts')) {
    $stmt = $con->prepare("
        SELECT id, part_ref, part_name, status_key, created_at
        FROM assetmanager_parts
        WHERE tenant_key=? AND clientnumber=? AND record_type='part'
        ORDER BY created_at DESC, id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['recent_parts'][] = [
                'id' => (int)$row['id'],
                'part_ref' => (string)$row['part_ref'],
                'part_name' => (string)$row['part_name'],
                'status' => (string)$row['status_key'],
                'created_at' => assetmanager_format_date($row['created_at'] ?? ''),
            ];
        }
        $stmt->close();
    }
}

if (!empty($modules['parts']) && assetmanager_table_exists($con, 'assetmanager_parts')) {
    $stmt = $con->prepare("
        SELECT s.id, JSON_UNQUOTE(JSON_EXTRACT(s.payload_json, '$.event_type')) AS event_type, s.quantity, s.created_at, p.part_ref, p.part_name
        FROM assetmanager_parts s
        INNER JOIN assetmanager_parts p ON p.id=s.parent_id AND p.tenant_key=s.tenant_key AND p.clientnumber=s.clientnumber AND p.record_type='part'
        WHERE s.tenant_key=? AND s.clientnumber=? AND s.record_type='stock_event'
        ORDER BY s.created_at DESC, s.id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['recent_stock_events'][] = [
                'id' => (int)$row['id'],
                'event_type' => (string)$row['event_type'],
                'quantity' => (string)$row['quantity'],
                'part_ref' => (string)$row['part_ref'],
                'part_name' => (string)$row['part_name'],
                'created_at' => assetmanager_format_date($row['created_at'] ?? ''),
            ];
        }
        $stmt->close();
    }
}

if (assetmanager_table_exists($con, 'assetmanager_activity')) {
    $userId = assetmanager_actor_user_id();
    $stmt = $con->prepare("
        SELECT id, activity_type AS notification_type, 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='notification' AND JSON_UNQUOTE(JSON_EXTRACT(payload_json, '$.read_at')) IS NULL AND (created_by IS NULL OR created_by=?)
        ORDER BY created_at DESC, id DESC
        LIMIT 6
    ");
    if ($stmt) {
        $stmt->bind_param('sii', $tenant, $clientnumber, $userId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['notifications'][] = [
                'id' => (int)$row['id'],
                'type' => (string)$row['notification_type'],
                'title' => (string)$row['title'],
                'body' => (string)$row['body'],
                'created_at' => assetmanager_format_date($row['created_at'] ?? ''),
            ];
        }
        $stmt->close();
    }
}

if (assetmanager_table_exists($con, 'assetmanager_assets')) {
    $stmt = $con->prepare("
        SELECT id, asset_title, plantnumber, serialnumber, created_at
        FROM assetmanager_assets
        WHERE tenant_key=? AND clientnumber=? AND source_type='assetmanager_item' AND archived='0'
        ORDER BY created_at DESC, id DESC
        LIMIT 5
    ");
    if ($stmt) {
        $stmt->bind_param('si', $tenant, $clientnumber);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $dashboard['recent_local_assets'][] = [
                'id' => (int)$row['id'],
                'asset_title' => (string)$row['asset_title'],
                'plantnumber' => (string)$row['plantnumber'],
                'serialnumber' => (string)$row['serialnumber'],
                'created_at' => assetmanager_format_date($row['created_at'] ?? ''),
                'source' => 'assetmanager_item',
                'source_id' => (int)$row['id'],
            ];
        }
        $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.duedate, l.locname
        FROM itemdetails a
        LEFT JOIN locations l ON l.locnumber=a.locnumber
        WHERE a.clientnumber=? AND a.statuslive='1' AND a.duedate IS NOT NULL AND a.duedate <= DATE_ADD(CURDATE(), INTERVAL 30 DAY)
        {$siteSql}
        ORDER BY a.duedate ASC, a.desc ASC
        LIMIT 6
    ");
    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()) {
            $dashboard['inspection_due'][] = [
                'itemnumber' => (int)$row['itemnumber'],
                'asset_title' => (string)$row['desc'],
                'plantnumber' => (string)$row['plantnumber'],
                'location' => (string)$row['locname'],
                'duedate' => assetmanager_format_date($row['duedate'] ?? ''),
                'source' => 'enrep_item',
                'source_id' => (int)$row['itemnumber'],
            ];
        }
        $stmt->close();
    }
}

assetmanager_json_response([
    'success' => true,
    'dashboard' => $dashboard,
]);
