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

$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_module($con, $tenant, $clientnumber, 'parts', 'Parts');

$partName = enrep_request_string('part_name', '', 255);
if ($partName === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Part name is required.']);
}

$partRef = enrep_request_string('part_ref', '', 120);
$status = enrep_request_string('status_key', 'active', 80);
$payload = assetmanager_request_json_array('payload_json');
$payload['notes'] = enrep_request_string('notes', $payload['notes'] ?? '', 5000);
$payloadJson = assetmanager_encode_json($payload);
$now = date('Y-m-d H:i:s');

$stmt = $con->prepare("
    INSERT INTO assetmanager_parts
        (tenant_key, clientnumber, record_type, part_ref, part_name, status_key, payload_json, created_by, created_at, updated_at)
    VALUES (?, ?, 'part', ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Part could not be prepared.']);
}
$userId = assetmanager_actor_user_id();
$stmt->bind_param('sissssiss', $tenant, $clientnumber, $partRef, $partName, $status, $payloadJson, $userId, $now, $now);
$ok = $stmt->execute();
$partId = $ok ? (int)$stmt->insert_id : 0;
$stmt->close();

if ($ok) {
    assetmanager_audit($con, $tenant, $clientnumber, $userId, 'part', $partId, 'create', [], [
        'part_ref' => $partRef,
        'part_name' => $partName,
        'status_key' => $status,
    ]);
}

assetmanager_json_response([
    'success' => $ok,
    'part_id' => $partId,
    'message' => $ok ? 'Part saved.' : 'Part could not be saved.',
]);
