<?php
require_once __DIR__ . '/functions.php';

$tenant = enrep_tenant_segment($_REQUEST['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');

$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, 'hire', 'Hire');

if (!assetmanager_table_exists($con, 'assetmanager_hire_pricing')) {
    assetmanager_json_response([
        'success' => true,
        'setup_required' => true,
        'groups' => [],
        'rules' => [],
        'matched_rule' => null,
        'message' => 'Hire pricing table is not installed yet.',
    ]);
}

$groups = [];
$rules = [];
$stmt = $con->prepare("
    SELECT p.id, p.record_type, p.group_key, p.group_name, p.asset_id, p.status_key,
           p.daily_rate, p.weekly_rate, p.monthly_rate, p.vat_mode, p.vat_rate,
           p.deposit_amount, p.insurance_daily_rate, p.min_duration, p.max_duration,
           p.duration_unit, p.payload_json,
           a.asset_title, a.source_type, a.source_itemnumber, a.plantnumber, a.serialnumber,
           a.registration, a.core_fields_json, a.custom_fields_json
    FROM assetmanager_hire_pricing p
    LEFT JOIN assetmanager_assets a ON a.id=p.asset_id AND a.tenant_key=p.tenant_key AND a.clientnumber=p.clientnumber
    WHERE p.tenant_key=? AND p.clientnumber=? AND p.status_key='active'
    ORDER BY p.record_type ASC, p.group_name ASC, p.asset_id IS NULL ASC, p.id DESC
    LIMIT 500
");
if ($stmt) {
    $stmt->bind_param('si', $tenant, $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    while ($row = $res->fetch_assoc()) {
        $payload = assetmanager_decode_json($row['payload_json'] ?? '');
        $recordType = (string)($row['record_type'] ?? 'item');
        $groupName = trim((string)($row['group_name'] ?? ''));
        $groupKey = trim((string)($row['group_key'] ?? ''));
        $assetId = (int)($row['asset_id'] ?? 0);
        $assetTitle = trim((string)($row['asset_title'] ?? ''));
        $core = assetmanager_decode_json($row['core_fields_json'] ?? '');
        $custom = assetmanager_decode_json($row['custom_fields_json'] ?? '');
        $assetClass = trim((string)($custom['asset_class'] ?? ''));
        $identifier = $assetClass === 'vehicle'
            ? trim((string)($row['registration'] ?? $core['registration_mark'] ?? $custom['registration_mark'] ?? $row['plantnumber'] ?? $row['serialnumber'] ?? ''))
            : trim((string)($row['plantnumber'] ?? $row['serialnumber'] ?? $row['registration'] ?? ''));
        $assetLabel = $assetTitle !== '' && $identifier !== '' ? $assetTitle . ' - ' . $identifier : $assetTitle;
        $assetSource = (string)($row['source_type'] ?? '');
        $assetSourceId = $assetSource === 'enrep_item' ? (int)($row['source_itemnumber'] ?? 0) : $assetId;
        $assetRef = $assetSource !== '' && $assetSourceId > 0 ? $assetSource . '|' . $assetSourceId . '|' . $assetTitle : '';
        $groupId = ctype_digit($groupKey) ? (int)$groupKey : 0;

        if ($recordType === 'group') {
            $groups[(int)$row['id']] = [
                'id' => (int)$row['id'],
                'group_name' => $groupName,
                'status_key' => (string)$row['status_key'],
                'payload' => $payload,
            ];
        }

        $rules[] = [
            'id' => (int)$row['id'],
            'price_group_id' => $groupId,
            'group_name' => $groupName,
            'asset_id' => $assetId,
            'asset_title' => $assetTitle,
            'asset_label' => $assetLabel,
            'asset_ref' => $assetRef,
            'asset_source' => $assetSource,
            'asset_source_id' => $assetSourceId,
            'rule_label' => $recordType === 'group' ? ($groupName !== '' ? $groupName : 'Group pricing') : ($assetLabel !== '' ? $assetLabel : 'Item-specific pricing'),
            'record_type' => $recordType,
            'status_key' => (string)$row['status_key'],
            'daily_rate' => $row['daily_rate'],
            'weekly_rate' => $row['weekly_rate'],
            'monthly_rate' => $row['monthly_rate'],
            'vat_mode' => (string)$row['vat_mode'],
            'vat_rate' => $row['vat_rate'],
            'deposit_amount' => $row['deposit_amount'],
            'insurance_required' => !empty($payload['insurance_available']) ? 1 : 0,
            'insurance_daily_rate' => $row['insurance_daily_rate'],
            'min_duration' => $row['min_duration'],
            'max_duration' => $row['max_duration'],
            'duration_unit' => (string)$row['duration_unit'],
            'payload' => $payload,
        ];
    }
    $stmt->close();
}

$source = enrep_request_enum('source', ['enrep_item', 'assetmanager_item'], '');
$sourceId = enrep_request_int('source_id', 0);
$assetTitle = enrep_request_string('asset_title', 'Asset', 255);
$assetClass = enrep_request_string('asset_class', '', 120);
$matchedRule = null;
$assetId = 0;
if ($source !== '' && $sourceId > 0) {
    assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $source, $sourceId);
    $assetId = assetmanager_resolve_asset_id($con, $tenant, $clientnumber, $source, $sourceId, $assetTitle, true);
    foreach ($rules as $rule) {
        if ((int)$rule['asset_id'] > 0 && (int)$rule['asset_id'] === $assetId) {
            $matchedRule = $rule;
            break;
        }
    }
    if (!$matchedRule && $assetClass !== '') {
        foreach ($rules as $rule) {
            $payloadClass = trim((string)($rule['payload']['asset_class'] ?? ''));
            if ($payloadClass !== '' && strcasecmp($payloadClass, $assetClass) === 0) {
                $matchedRule = $rule;
                break;
            }
        }
    }
}

assetmanager_json_response([
    'success' => true,
    'asset_id' => $assetId,
    'groups' => array_values($groups),
    'rules' => $rules,
    'matched_rule' => $matchedRule,
    'message' => $matchedRule ? 'Hire pricing loaded.' : 'No configured hire pricing found for this asset.',
]);
