<?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_table_exists($con, 'assetmanager_assets')) {
    assetmanager_json_response(['success' => false, 'setup_required' => true, 'message' => 'Asset Manager maintenance tables are not installed yet.']);
}

$clientnumber = enrep_request_int('clientnumber', 0);
$source = enrep_request_enum('source', ['enrep_item', 'assetmanager_item'], '');
$sourceId = enrep_request_int('source_id', 0);
$assetTitle = enrep_request_string('asset_title', '', 255);

if ($clientnumber <= 0 || $source === '' || $sourceId <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset reference is required.']);
}
assetmanager_json_require_client_access($con, $clientnumber);
assetmanager_json_require_module($con, $tenant, $clientnumber, 'maintenance', 'Maintenance');
assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $source, $sourceId);

$assetId = assetmanager_resolve_asset_id($con, $tenant, $clientnumber, $source, $sourceId, $assetTitle, true);
if ($assetId <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Asset could not be linked for work orders.']);
}

$summary = enrep_request_string('summary', '', 255);
if ($summary === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Work order summary is required.']);
}

$workType = enrep_request_string('work_type', 'maintenance', 80);
$priority = enrep_request_string('priority_key', 'normal', 40);
$dueDateRaw = enrep_request_string('due_date', '', 40);
$dueAt = null;
if ($dueDateRaw !== '') {
    $dueTs = strtotime(str_replace('/', '-', $dueDateRaw));
    if ($dueTs) {
        $dueAt = date('Y-m-d 00:00:00', $dueTs);
    }
}

$details = [
    'work_type' => $workType,
    'notes' => enrep_request_string('notes', '', 5000),
    'source' => $source,
    'source_id' => $sourceId,
];
$detailsJson = assetmanager_encode_json($details);
$status = 'open';
$userId = assetmanager_actor_user_id();
$now = date('Y-m-d H:i:s');
$assignedTo = null;
$completedAt = null;
$recordType = 'work_order';

$stmt = $con->prepare("
    INSERT INTO assetmanager_maintenance
        (tenant_key, clientnumber, asset_id, record_type, status_key, priority_key, summary, due_at, completed_at, assigned_to, payload_json, created_by, created_at, updated_at)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Work order could not be prepared.']);
}
$stmt->bind_param(
    'siissssssississ',
    $tenant,
    $clientnumber,
    $assetId,
    $recordType,
    $status,
    $priority,
    $summary,
    $dueAt,
    $completedAt,
    $assignedTo,
    $detailsJson,
    $userId,
    $now,
    $now
);
$ok = $stmt->execute();
$workOrderId = $ok ? (int)$stmt->insert_id : 0;
$stmt->close();

if ($ok) {
    assetmanager_audit($con, $tenant, $clientnumber, $userId, 'work_order', $workOrderId, 'create', [], [
        'asset_id' => $assetId,
        'summary' => $summary,
        'work_type' => $workType,
        'priority_key' => $priority,
        'due_at' => $dueAt,
    ]);
}

assetmanager_json_response([
    'success' => $ok,
    'work_order_id' => $workOrderId,
    'message' => $ok ? 'Work order created.' : 'Work order could not be created.',
]);
