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

enrep_require_admin();

$con = $GLOBALS['con'] ?? null;
if (!$con instanceof mysqli) {
    assetmanager_json_response(['success' => false, 'message' => 'Tenant database connection unavailable.']);
}
$con->set_charset('utf8mb4');

$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);

if (!assetmanager_schema_ready($con)) {
    assetmanager_json_response([
        'success' => false,
        'setup_required' => true,
        'message' => 'Asset Manager tables are not installed yet.',
    ]);
}

$enabled = enrep_request_int('enabled', 0) === 1 ? 1 : 0;
$modules = [];
foreach (array_keys(assetmanager_default_settings()['modules']) as $moduleKey) {
    $modules[$moduleKey] = enrep_request_int('module_' . $moduleKey, 0) === 1 ? 1 : 0;
}

$limits = [
    'users' => max(1, enrep_request_int('limit_users', 10)),
    'local_assets' => max(0, enrep_request_int('limit_local_assets', 250)),
    'storage_mb' => max(0, enrep_request_int('limit_storage_mb', 1024)),
];

$normaliseHex = static function (string $value, string $fallback): string {
    $value = strtolower(ltrim(trim($value), '#'));
    return preg_match('/^[0-9a-f]{6}$/', $value) ? $value : $fallback;
};

$branding = [
    'tenant_logo' => enrep_request_int('brand_tenant_logo', 0) === 1 ? 1 : 0,
    'client_logo' => enrep_request_int('brand_client_logo', 0) === 1 ? 1 : 0,
    'primary' => $normaliseHex(enrep_request_string('brand_primary', '245781', 12), '245781'),
    'accent' => $normaliseHex(enrep_request_string('brand_accent', '54b4d3', 12), '54b4d3'),
];

$currentSequences = assetmanager_get_client_sequences($con, $tenant, $clientnumber);

$permissions = [
    'include_enrep_assets' => enrep_request_int('perm_include_enrep_assets', 0) === 1 ? 1 : 0,
    'client_add_assets' => enrep_request_int('perm_client_add_assets', 0) === 1 ? 1 : 0,
    'client_archive_local_assets' => enrep_request_int('perm_client_archive_local_assets', 0) === 1 ? 1 : 0,
    'require_confirmations' => 1,
];

$sequences = [
    'hire_agreement' => [
        'prefix' => array_key_exists('hire_agreement_prefix', $_POST) ? enrep_request_string('hire_agreement_prefix', 'HA-', 40) : (string)($currentSequences['hire_agreement']['prefix'] ?? 'HA-'),
        'next_number' => array_key_exists('hire_agreement_next_number', $_POST) ? max(1, enrep_request_int('hire_agreement_next_number', 1)) : max(1, (int)($currentSequences['hire_agreement']['next_number'] ?? 1)),
        'padding' => array_key_exists('hire_agreement_padding', $_POST) ? max(0, min(12, enrep_request_int('hire_agreement_padding', 4))) : max(0, min(12, (int)($currentSequences['hire_agreement']['padding'] ?? 4))),
        'suffix' => array_key_exists('hire_agreement_suffix', $_POST) ? enrep_request_string('hire_agreement_suffix', '', 40) : (string)($currentSequences['hire_agreement']['suffix'] ?? ''),
    ],
    'hire_quote' => [
        'prefix' => array_key_exists('hire_quote_prefix', $_POST) ? enrep_request_string('hire_quote_prefix', 'HQ-', 40) : (string)($currentSequences['hire_quote']['prefix'] ?? 'HQ-'),
        'next_number' => array_key_exists('hire_quote_next_number', $_POST) ? max(1, enrep_request_int('hire_quote_next_number', 1)) : max(1, (int)($currentSequences['hire_quote']['next_number'] ?? 1)),
        'padding' => array_key_exists('hire_quote_padding', $_POST) ? max(0, min(12, enrep_request_int('hire_quote_padding', 4))) : max(0, min(12, (int)($currentSequences['hire_quote']['padding'] ?? 4))),
        'suffix' => array_key_exists('hire_quote_suffix', $_POST) ? enrep_request_string('hire_quote_suffix', '', 40) : (string)($currentSequences['hire_quote']['suffix'] ?? ''),
    ],
];

$allowedItemdetailsFields = [
    'plantnumber',
    'serialnumber',
    'manufacturer',
    'model',
    'dateofmanf',
    'customer_reference',
    'asset_tag',
];
$postedFields = $_POST['itemdetails_fields'] ?? [];
if (!is_array($postedFields)) {
    $postedFields = [];
}
$fields = array_values(array_intersect($allowedItemdetailsFields, array_map('strval', $postedFields)));

$itemdetailsEdit = [
    'enabled' => enrep_request_int('itemdetails_edit_enabled', 0) === 1 ? 1 : 0,
    'fields' => $fields,
];

$settings = assetmanager_merge_settings([
    'enabled' => $enabled,
    'modules' => $modules,
    'limits' => $limits,
    'branding' => $branding,
    'permissions' => $permissions,
    'itemdetails_edit' => $itemdetailsEdit,
]);

$ok = assetmanager_save_client_settings($con, $tenant, $clientnumber, $settings, assetmanager_actor_user_id());
if ($ok && !assetmanager_save_client_sequences($con, $tenant, $clientnumber, $sequences)) {
    $ok = false;
    $GLOBALS['assetmanager_last_error'] = 'Asset Manager settings saved, but numbering settings could not be saved.';
}

assetmanager_json_response([
    'success' => $ok,
    'message' => $ok ? 'Asset Manager settings saved.' : ((string)($GLOBALS['assetmanager_last_error'] ?? '') ?: 'Asset Manager settings could not be saved.'),
]);
