<?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_assets')) {
    assetmanager_json_response(['success' => false, 'setup_required' => true, 'message' => 'Asset Manager asset table is not installed yet.']);
}

$mode = enrep_request_enum('mode', ['create_local', 'save_supplement'], '');
$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);

$now = date('Y-m-d H:i:s');
$userId = assetmanager_actor_user_id();

if ($mode === 'create_local') {
    assetmanager_json_require_permission($con, $tenant, $clientnumber, 'client_add_assets', 'Local asset creation');

    $title = enrep_request_string('asset_title', '', 255);
    if ($title === '') {
        assetmanager_json_response(['success' => false, 'message' => 'Asset title is required.']);
    }

    $plantnumber = enrep_request_string('plantnumber', '', 120);
    $serialnumber = enrep_request_string('serialnumber', '', 120);
    $assetClass = enrep_request_string('asset_class', 'general', 80);
    $hireEnabled = enrep_request_int('hire_enabled', 0) === 1 ? 1 : 0;
    if ($assetClass === 'hire_plant') {
        $assetClass = 'plant';
        $hireEnabled = 1;
    }
    $category = enrep_request_string('category_key', $assetClass !== '' ? $assetClass : 'general', 80);
    if ($category === 'general' && $assetClass !== '') {
        $category = $assetClass;
    }
    $status = enrep_request_string('status_key', 'active', 80);
    $coreFields = [
        'manufacturer' => enrep_request_string('manufacturer', '', 160),
        'model' => enrep_request_string('model', '', 160),
        'dateofmanf' => assetmanager_parse_datetime(enrep_request_string('dateofmanf', '', 40), true) ?: '',
        'asset_tag' => enrep_request_string('asset_tag', '', 120),
        'fleet_number' => enrep_request_string('fleet_number', '', 120),
        'registration_mark' => enrep_request_string('registration_mark', '', 80),
    ];
    $customFields = [
        'location_label' => enrep_request_string('location_label', '', 255),
        'subloc' => enrep_request_string('subloc', '', 255),
        'asset_class' => $assetClass,
        'hire_enabled' => $hireEnabled,
        'ownership_status' => enrep_request_string('ownership_status', '', 80),
        'department' => enrep_request_string('department', '', 160),
        'custodian' => enrep_request_string('custodian', '', 160),
        'supplier' => enrep_request_string('supplier', '', 160),
        'purchase_date' => assetmanager_parse_datetime(enrep_request_string('purchase_date', '', 40), true) ?: '',
        'warranty_expires' => assetmanager_parse_datetime(enrep_request_string('warranty_expires', '', 40), true) ?: '',
        'insurance_provider' => enrep_request_string('insurance_provider', '', 160),
        'insurance_policy' => enrep_request_string('insurance_policy', '', 160),
        'insurance_expires' => assetmanager_parse_datetime(enrep_request_string('insurance_expires', '', 40), true) ?: '',
        'mot_expires' => assetmanager_parse_datetime(enrep_request_string('mot_expires', '', 40), true) ?: '',
        'tax_expires' => assetmanager_parse_datetime(enrep_request_string('tax_expires', '', 40), true) ?: '',
        'pat_expires' => assetmanager_parse_datetime(enrep_request_string('pat_expires', '', 40), true) ?: '',
        'last_service_date' => assetmanager_parse_datetime(enrep_request_string('last_service_date', '', 40), true) ?: '',
        'service_interval' => enrep_request_string('service_interval', '', 80),
        'current_hours' => enrep_request_string('current_hours', '', 80),
        'current_mileage' => enrep_request_string('current_mileage', '', 80),
        'hire_state' => enrep_request_string('hire_state', '', 80),
        'notes' => enrep_request_string('notes', '', 5000),
    ];

    $coreJson = assetmanager_encode_json($coreFields);
    $customJson = assetmanager_encode_json($customFields);
    $moduleJson = assetmanager_encode_json([]);
    $sourceType = 'assetmanager_item';
    $sourceItemnumber = null;
    $locationId = null;
    $archived = 0;

    $stmt = $con->prepare("
        INSERT INTO assetmanager_assets
            (tenant_key, clientnumber, source_type, source_itemnumber, category_key, asset_title, plantnumber, serialnumber, location_id, status_key, core_fields_json, custom_fields_json, module_data_json, archived, created_by, created_at, updated_at)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    ");
    if (!$stmt) {
        assetmanager_json_response(['success' => false, 'message' => 'Asset could not be prepared.']);
    }
    $stmt->bind_param(
        'sisissssissssiiss',
        $tenant,
        $clientnumber,
        $sourceType,
        $sourceItemnumber,
        $category,
        $title,
        $plantnumber,
        $serialnumber,
        $locationId,
        $status,
        $coreJson,
        $customJson,
        $moduleJson,
        $archived,
        $userId,
        $now,
        $now
    );
    $ok = $stmt->execute();
    $assetId = $ok ? (int)$stmt->insert_id : 0;
    $stmt->close();

    if ($ok) {
        assetmanager_audit($con, $tenant, $clientnumber, $userId, 'asset', $assetId, 'create_local', [], [
            'asset_title' => $title,
            'plantnumber' => $plantnumber,
            'serialnumber' => $serialnumber,
        ]);
    }

    assetmanager_json_response([
        'success' => $ok,
        'asset_id' => $assetId,
        'message' => $ok ? 'Asset created.' : 'Asset could not be created.',
    ]);
}

if ($mode === 'save_supplement') {
    $source = enrep_request_enum('source', ['enrep_item', 'assetmanager_item'], '');
    $sourceId = enrep_request_int('source_id', 0);
    if ($source === '' || $sourceId <= 0) {
        assetmanager_json_response(['success' => false, 'message' => 'Asset source is required.']);
    }
    assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $source, $sourceId);

    $existingSupplement = [];
    if (assetmanager_table_exists($con, 'assetmanager_assets')) {
        if ($source === 'assetmanager_item') {
            $stmt = $con->prepare("
                SELECT custom_fields_json
                FROM assetmanager_assets
                WHERE id=? AND clientnumber=? AND tenant_key=?
                LIMIT 1
            ");
            if ($stmt) {
                $stmt->bind_param('iis', $sourceId, $clientnumber, $tenant);
                $stmt->execute();
                $row = $stmt->get_result()->fetch_assoc();
                $existingSupplement = assetmanager_decode_json($row['custom_fields_json'] ?? '');
                $stmt->close();
            }
        } else {
            $stmt = $con->prepare("
                SELECT custom_fields_json
                FROM assetmanager_assets
                WHERE tenant_key=? AND clientnumber=? AND source_type='enrep_item' AND source_itemnumber=?
                LIMIT 1
            ");
            if ($stmt) {
                $stmt->bind_param('sii', $tenant, $clientnumber, $sourceId);
                $stmt->execute();
                $row = $stmt->get_result()->fetch_assoc();
                $existingSupplement = assetmanager_decode_json($row['custom_fields_json'] ?? '');
                $stmt->close();
            }
        }
    }

    $supplement = array_merge($existingSupplement, [
        'nickname' => enrep_request_string('nickname', '', 255),
        'operational_status' => enrep_request_string('operational_status', 'active', 80),
        'live_subloc' => enrep_request_string('live_subloc', '', 255),
        'asset_class' => enrep_request_string('asset_class', '', 80),
        'hire_enabled' => enrep_request_int('hire_enabled', 0) === 1 ? 1 : 0,
        'ownership_status' => enrep_request_string('ownership_status', '', 80),
        'department' => enrep_request_string('department', '', 160),
        'custodian' => enrep_request_string('custodian', '', 160),
        'supplier' => enrep_request_string('supplier', '', 160),
        'asset_tag' => enrep_request_string('asset_tag', '', 120),
        'fleet_number' => enrep_request_string('fleet_number', '', 120),
        'registration_mark' => enrep_request_string('registration_mark', '', 80),
        'purchase_date' => assetmanager_parse_datetime(enrep_request_string('purchase_date', '', 40), true) ?: '',
        'warranty_expires' => assetmanager_parse_datetime(enrep_request_string('warranty_expires', '', 40), true) ?: '',
        'insurance_provider' => enrep_request_string('insurance_provider', '', 160),
        'insurance_policy' => enrep_request_string('insurance_policy', '', 160),
        'insurance_expires' => assetmanager_parse_datetime(enrep_request_string('insurance_expires', '', 40), true) ?: '',
        'mot_expires' => assetmanager_parse_datetime(enrep_request_string('mot_expires', '', 40), true) ?: '',
        'tax_expires' => assetmanager_parse_datetime(enrep_request_string('tax_expires', '', 40), true) ?: '',
        'pat_expires' => assetmanager_parse_datetime(enrep_request_string('pat_expires', '', 40), true) ?: '',
        'last_service_date' => assetmanager_parse_datetime(enrep_request_string('last_service_date', '', 40), true) ?: '',
        'service_interval' => enrep_request_string('service_interval', '', 80),
        'current_hours' => enrep_request_string('current_hours', '', 80),
        'current_mileage' => enrep_request_string('current_mileage', '', 80),
        'hire_state' => enrep_request_string('hire_state', '', 80),
        'notes' => enrep_request_string('notes', '', 5000),
        'updated_at' => $now,
        'updated_by' => $userId,
    ]);
    if ((string)$supplement['asset_class'] === 'hire_plant') {
        $supplement['asset_class'] = 'plant';
        $supplement['hire_enabled'] = 1;
    }

    if ($source === 'assetmanager_item') {
        $customJson = assetmanager_encode_json($supplement);
        $stmt = $con->prepare("
            UPDATE assetmanager_assets
            SET custom_fields_json=?, status_key=?, updated_at=?
            WHERE id=? AND clientnumber=? AND tenant_key=?
        ");
        if (!$stmt) {
            assetmanager_json_response(['success' => false, 'message' => 'Asset supplement could not be prepared.']);
        }
        $stmt->bind_param('sssiis', $customJson, $supplement['operational_status'], $now, $sourceId, $clientnumber, $tenant);
        $ok = $stmt->execute();
        $stmt->close();
    } else {
        $assetTitle = 'EnRep item ' . $sourceId;
        $sourceType = 'enrep_item';
        $category = 'enrep';
        $status = $supplement['operational_status'];
        $coreJson = assetmanager_encode_json([]);
        $customJson = assetmanager_encode_json($supplement);
        $moduleJson = assetmanager_encode_json([]);
        $archived = 0;

        $stmt = $con->prepare("
            INSERT INTO assetmanager_assets
                (tenant_key, clientnumber, source_type, source_itemnumber, category_key, asset_title, status_key, core_fields_json, custom_fields_json, module_data_json, archived, created_by, created_at, updated_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                status_key=VALUES(status_key),
                custom_fields_json=VALUES(custom_fields_json),
                updated_at=VALUES(updated_at)
        ");
        if (!$stmt) {
            assetmanager_json_response(['success' => false, 'message' => 'Asset supplement could not be prepared. A unique link index may be required.']);
        }
        $stmt->bind_param(
            'sisissssssisss',
            $tenant,
            $clientnumber,
            $sourceType,
            $sourceId,
            $category,
            $assetTitle,
            $status,
            $coreJson,
            $customJson,
            $moduleJson,
            $archived,
            $userId,
            $now,
            $now
        );
        $ok = $stmt->execute();
        $stmt->close();
    }

    if (!empty($ok)) {
        assetmanager_audit($con, $tenant, $clientnumber, $userId, 'asset_supplement', $sourceId, 'save', [], $supplement);
    }

    assetmanager_json_response([
        'success' => !empty($ok),
        'message' => !empty($ok) ? 'Asset supplement saved.' : 'Asset supplement could not be saved.',
    ]);
}

assetmanager_json_response(['success' => false, 'message' => 'Unknown asset save mode.']);
