<?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);
$defectId = enrep_request_int('defect_id', 0);
$status = enrep_request_string('status_key', '', 80);

if ($clientnumber <= 0 || $defectId <= 0 || $status === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Defect and status are required.']);
}
assetmanager_json_require_client_access($con, $clientnumber);
assetmanager_json_require_module($con, $tenant, $clientnumber, 'maintenance', 'Maintenance');

$stmt = $con->prepare("SELECT id, asset_id, status_key, priority_key AS severity_key, summary FROM assetmanager_maintenance WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='defect' LIMIT 1");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Defect could not be loaded.']);
}
$stmt->bind_param('isi', $defectId, $tenant, $clientnumber);
$stmt->execute();
$before = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$before) {
    assetmanager_json_response(['success' => false, 'message' => 'Defect was not found.']);
}

$resolvedAt = in_array($status, ['resolved', 'closed'], true) ? date('Y-m-d H:i:s') : null;
$stmt = $con->prepare("UPDATE assetmanager_maintenance SET status_key=?, completed_at=?, updated_at=? WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='defect' LIMIT 1");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Defect status could not be prepared.']);
}
$now = date('Y-m-d H:i:s');
$stmt->bind_param('sssisi', $status, $resolvedAt, $now, $defectId, $tenant, $clientnumber);
$ok = $stmt->execute();
$stmt->close();

if ($ok) {
    assetmanager_audit($con, $tenant, $clientnumber, assetmanager_actor_user_id(), 'defect', $defectId, 'status', $before, [
        'status_key' => $status,
        'resolved_at' => $resolvedAt,
    ]);
}

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