<?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');

if (!assetmanager_table_exists($con, 'assetmanager_maintenance')) {
    assetmanager_json_response(['success' => false, 'setup_required' => true, 'message' => 'Asset Manager maintenance table is not installed yet.']);
}

$clientnumber = enrep_request_int('clientnumber', 0);
$workOrderId = enrep_request_int('work_order_id', 0);
$status = enrep_request_enum('status_key', ['open', 'in_progress', 'complete', 'cancelled'], '');

if ($clientnumber <= 0 || $workOrderId <= 0 || $status === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Work-order status request is invalid.']);
}
assetmanager_json_require_client_access($con, $clientnumber);
assetmanager_json_require_module($con, $tenant, $clientnumber, 'maintenance', 'Maintenance');

$before = [];
$stmt = $con->prepare("
    SELECT w.id, w.asset_id, w.status_key, w.summary, a.source_type, a.source_itemnumber
    FROM assetmanager_maintenance w
    LEFT 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.id=? AND w.record_type='work_order'
    LIMIT 1
");
if ($stmt) {
    $stmt->bind_param('sii', $tenant, $clientnumber, $workOrderId);
    $stmt->execute();
    $before = $stmt->get_result()->fetch_assoc() ?: [];
    $stmt->close();
}

if (empty($before)) {
    assetmanager_json_response(['success' => false, 'message' => 'Work order could not be found.']);
}
$source = (string)($before['source_type'] ?? 'assetmanager_item');
$sourceId = $source === 'enrep_item' ? (int)($before['source_itemnumber'] ?? 0) : (int)($before['asset_id'] ?? 0);
assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $source, $sourceId);

$now = date('Y-m-d H:i:s');
$completedAt = $status === 'complete' ? $now : null;
$stmt = $con->prepare("
    UPDATE assetmanager_maintenance
    SET status_key=?, completed_at=?, updated_at=?
    WHERE tenant_key=? AND clientnumber=? AND id=?
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Work-order status could not be prepared.']);
}
$stmt->bind_param('ssssii', $status, $completedAt, $now, $tenant, $clientnumber, $workOrderId);
$ok = $stmt->execute();
$stmt->close();

if ($ok) {
    if ($status === 'complete' && assetmanager_module_enabled($con, $tenant, $clientnumber, 'finance')) {
        assetmanager_audit($con, $tenant, $clientnumber, assetmanager_actor_user_id(), 'work_order', $workOrderId, 'finance_invoice_required', [], [
            'title' => 'Invoice required: ' . (string)($before['summary'] ?? 'Work order'),
            'asset_id' => (int)($before['asset_id'] ?? 0),
            'source' => $source,
            'source_id' => $sourceId,
        ]);
    }
    assetmanager_audit($con, $tenant, $clientnumber, assetmanager_actor_user_id(), 'work_order', $workOrderId, 'status', $before, [
        'status_key' => $status,
        'updated_at' => $now,
    ]);
}

assetmanager_json_response([
    'success' => $ok,
    'message' => $ok ? 'Work-order status updated.' : 'Work-order status could not be updated.',
]);
