<?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_hire') || !assetmanager_table_exists($con, 'assetmanager_activity')) {
    assetmanager_json_response(['success' => false, 'setup_required' => true, 'message' => 'Asset Manager hire 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, 'hire', 'Hire');

$status = enrep_request_string('status_key', 'draft', 80);
$startsAt = assetmanager_parse_datetime(enrep_request_string('starts_at', '', 40));
$endsAt = assetmanager_parse_datetime(enrep_request_string('ends_at', '', 40));
$source = enrep_request_enum('source', ['enrep_item', 'assetmanager_item'], '');
$sourceId = enrep_request_int('source_id', 0);
$requestedAssets = assetmanager_request_json_array('hire_assets_json');
if (empty($requestedAssets) && $source !== '' && $sourceId > 0) {
    $requestedAssets[] = [
        'source' => $source,
        'source_id' => $sourceId,
        'title' => enrep_request_string('asset_title', 'Asset', 255),
    ];
}
if (empty($requestedAssets)) {
    assetmanager_json_response(['success' => false, 'message' => 'Choose a hire asset first.']);
}
$hireAssets = [];
foreach ($requestedAssets as $asset) {
    if (!is_array($asset)) {
        continue;
    }
    $assetSource = (string)($asset['source'] ?? '');
    $assetSourceId = (int)($asset['source_id'] ?? 0);
    $assetTitle = trim((string)($asset['title'] ?? 'Asset'));
    if (!in_array($assetSource, ['enrep_item', 'assetmanager_item'], true) || $assetSourceId <= 0) {
        continue;
    }
    assetmanager_json_require_asset_access($con, $tenant, $clientnumber, $assetSource, $assetSourceId);
    $assetId = assetmanager_resolve_asset_id($con, $tenant, $clientnumber, $assetSource, $assetSourceId, $assetTitle, true);
    if ($assetId <= 0) {
        assetmanager_json_response(['success' => false, 'message' => 'Hire asset could not be linked.']);
    }
    $asset['source'] = $assetSource;
    $asset['source_id'] = $assetSourceId;
    $asset['asset_id'] = $assetId;
    $asset['title'] = $assetTitle !== '' ? $assetTitle : 'Asset';
    $hireAssets[] = $asset;
}
if (empty($hireAssets)) {
    assetmanager_json_response(['success' => false, 'message' => 'Choose a valid hire asset first.']);
}
$primaryAsset = $hireAssets[0];
$source = (string)$primaryAsset['source'];
$sourceId = (int)$primaryAsset['source_id'];
$assetTitle = (string)$primaryAsset['title'];
$assetId = (int)$primaryAsset['asset_id'];

if (assetmanager_table_exists($con, 'assetmanager_hire')) {
    $stmt = $con->prepare("
        SELECT id, reference AS contract_ref, payload_json
        FROM assetmanager_hire
        WHERE tenant_key=? AND clientnumber=? AND record_type='contract' AND status_key IN ('pending_signature','active','on_hire','open')
        ORDER BY id DESC
        LIMIT 200
    ");
    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'] ?? '');
            $existingAssets = is_array($payload['hire_assets'] ?? null) ? $payload['hire_assets'] : (is_array($payload['hire_asset'] ?? null) ? [$payload['hire_asset']] : []);
            foreach ($existingAssets as $hireAsset) {
                if (!is_array($hireAsset)) {
                    continue;
                }
                foreach ($hireAssets as $selectedAsset) {
                    if ((string)($hireAsset['source'] ?? '') !== (string)$selectedAsset['source'] || (int)($hireAsset['source_id'] ?? 0) !== (int)$selectedAsset['source_id']) {
                        continue;
                    }
                $customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
                $label = trim((string)($row['contract_ref'] ?? ''));
                if ($label === '') {
                    $label = trim((string)($customer['name'] ?? 'active hire agreement'));
                }
                $stmt->close();
                    assetmanager_json_response(['success' => false, 'message' => $selectedAsset['title'] . ' is already on an active hire agreement: ' . $label]);
                }
            }
        }
        $stmt->close();
    }
}

$customer = assetmanager_request_json_array('customer_json');
$customer['name'] = enrep_request_string('customer_name', $customer['name'] ?? '', 255);
$payload = assetmanager_request_json_array('payload_json');
$payload['hire_asset'] = [
    'source' => $source,
    'source_id' => $sourceId,
    'asset_id' => $assetId,
    'title' => $assetTitle,
];
$payload['hire_assets'] = $hireAssets;
$payload['notes'] = enrep_request_string('notes', $payload['notes'] ?? '', 5000);
$customerJson = assetmanager_encode_json($customer);
$payloadJson = assetmanager_encode_json($payload);
$userId = assetmanager_actor_user_id();
$now = date('Y-m-d H:i:s');
$contractRef = '';
for ($attempt = 0; $attempt < 5; $attempt++) {
    $candidateRef = assetmanager_next_client_sequence_ref($con, $tenant, $clientnumber, 'hire_agreement');
    if ($candidateRef === '') {
        break;
    }
    $refStmt = $con->prepare("SELECT id FROM assetmanager_hire WHERE tenant_key=? AND clientnumber=? AND record_type='contract' AND reference=? LIMIT 1");
    if (!$refStmt) {
        $contractRef = $candidateRef;
        break;
    }
    $refStmt->bind_param('sis', $tenant, $clientnumber, $candidateRef);
    $refStmt->execute();
    $existingRef = $refStmt->get_result()->fetch_assoc();
    $refStmt->close();
    if (!$existingRef) {
        $contractRef = $candidateRef;
        break;
    }
}
if ($contractRef === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Hire agreement number could not be generated. Check the client hire numbering setup.']);
}

$stmt = $con->prepare("
    INSERT INTO assetmanager_hire
        (tenant_key, clientnumber, record_type, reference, status_key, customer_name, customer_reference, asset_id, starts_at, ends_at, payload_json, created_by, created_at, updated_at)
    VALUES (?, ?, 'contract', ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire contract could not be prepared.']);
}
$customerName = (string)($customer['name'] ?? '');
$customerReference = (string)($customer['reference'] ?? $customer['customer_reference'] ?? '');
$stmt->bind_param('sissssisssiss', $tenant, $clientnumber, $contractRef, $status, $customerName, $customerReference, $assetId, $startsAt, $endsAt, $payloadJson, $userId, $now, $now);
$ok = $stmt->execute();
$contractId = $ok ? (int)$stmt->insert_id : 0;
$stmt->close();

if ($ok) {
    $eventType = 'on_hire';
    $eventAt = $startsAt ?: $now;
    $eventStmt = $con->prepare("
        INSERT INTO assetmanager_activity
            (tenant_key, clientnumber, asset_id, module_key, parent_type, parent_id, activity_type, activity_at, summary, payload_json, created_by, created_at)
        VALUES (?, ?, ?, 'hire', 'contract', ?, ?, ?, ?, ?, ?, ?)
    ");
    if ($eventStmt) {
        foreach ($hireAssets as $eventAsset) {
            $eventAssetId = (int)($eventAsset['asset_id'] ?? 0);
            $eventSummary = 'Created with hire agreement';
            $eventPayloadJson = assetmanager_encode_json([
                'source' => $eventAsset['source'] ?? '',
                'source_id' => (int)($eventAsset['source_id'] ?? 0),
                'asset_title' => $eventAsset['title'] ?? 'Asset',
            ]);
            $eventStmt->bind_param('siiissssis', $tenant, $clientnumber, $eventAssetId, $contractId, $eventType, $eventAt, $eventSummary, $eventPayloadJson, $userId, $now);
            $eventStmt->execute();
        }
        $eventStmt->close();
    }

    assetmanager_audit($con, $tenant, $clientnumber, $userId, 'hire_contract', $contractId, 'create', [], [
        'contract_ref' => $contractRef,
        'status_key' => $status,
        'starts_at' => $startsAt,
        'ends_at' => $endsAt,
        'hire_asset' => $payload['hire_asset'],
    ]);
}

assetmanager_json_response([
    'success' => $ok,
    'contract_id' => $contractId,
    'message' => $ok ? 'Hire contract saved.' : 'Hire contract could not be saved.',
]);
