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

$clientnumber = enrep_request_int('clientnumber', 0);
$quoteId = enrep_request_int('quote_id', 0);
$action = enrep_request_enum('action', ['complete', 'delete'], '');
if ($clientnumber <= 0 || $quoteId <= 0 || $action === '') {
    assetmanager_json_response(['success' => false, 'message' => 'Hire quote action is invalid.']);
}
assetmanager_json_require_client_access($con, $clientnumber);
assetmanager_json_require_module($con, $tenant, $clientnumber, 'hire', 'Hire');

$stmt = $con->prepare("
    SELECT id, reference AS quote_ref, asset_id, status_key, starts_at, ends_at, expires_at, payload_json
    FROM assetmanager_hire
    WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='quote' AND status_key='quote'
    LIMIT 1
");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire quote could not be loaded.']);
}
$stmt->bind_param('isi', $quoteId, $tenant, $clientnumber);
$stmt->execute();
$quote = $stmt->get_result()->fetch_assoc();
$stmt->close();
if (!$quote) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire quote was not found.']);
}

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

if ($action === 'delete') {
    $stmt = $con->prepare("UPDATE assetmanager_hire SET status_key='deleted', updated_at=? WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='quote'");
    if (!$stmt) {
        assetmanager_json_response(['success' => false, 'message' => 'Hire quote could not be deleted.']);
    }
    $stmt->bind_param('sisi', $now, $quoteId, $tenant, $clientnumber);
    $ok = $stmt->execute();
    $stmt->close();
    if ($ok) {
        assetmanager_audit($con, $tenant, $clientnumber, $userId, 'hire_quote', $quoteId, 'delete', $quote, []);
    }
    assetmanager_json_response(['success' => $ok, 'message' => $ok ? 'Hire quote deleted.' : 'Hire quote could not be deleted.']);
}

$payload = assetmanager_decode_json($quote['payload_json'] ?? '');
$customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
$pricing = is_array($payload['pricing'] ?? null) ? $payload['pricing'] : [];
$hireAsset = is_array($payload['hire_asset'] ?? null) ? $payload['hire_asset'] : [];
$hireAssets = is_array($payload['hire_assets'] ?? null) ? $payload['hire_assets'] : ($hireAsset ? [$hireAsset] : []);
if (empty($hireAssets)) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire quote does not have valid linked plant.']);
}

$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 ('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()) {
        $contractPayload = assetmanager_decode_json($row['payload_json'] ?? '');
        $contractAssets = is_array($contractPayload['hire_assets'] ?? null) ? $contractPayload['hire_assets'] : (is_array($contractPayload['hire_asset'] ?? null) ? [$contractPayload['hire_asset']] : []);
        foreach ($contractAssets as $contractAsset) {
            if (!is_array($contractAsset)) {
                continue;
            }
            foreach ($hireAssets as $selectedAsset) {
                if ((string)($contractAsset['source'] ?? '') === (string)($selectedAsset['source'] ?? '') && (int)($contractAsset['source_id'] ?? 0) === (int)($selectedAsset['source_id'] ?? 0)) {
                    $stmt->close();
                    assetmanager_json_response(['success' => false, 'message' => ($selectedAsset['title'] ?? 'This asset') . ' is already on an active hire agreement.']);
                }
            }
        }
    }
    $stmt->close();
}

$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.']);
}

$payload['pricing'] = $pricing;
$payload['hire_assets'] = $hireAssets;
$payload['quote_id'] = $quoteId;
$payload['quote_ref'] = (string)($quote['quote_ref'] ?? '');
$payloadJson = assetmanager_encode_json($payload);
$status = 'active';
$startsAt = $quote['starts_at'] ?? null;
$endsAt = $quote['ends_at'] ?? null;
$assetId = (int)($quote['asset_id'] ?? 0);
$customerName = (string)($customer['name'] ?? '');
$customerReference = (string)($customer['reference'] ?? $customer['customer_reference'] ?? '');

$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 agreement could not be created from quote.']);
}
$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) {
    $stmt = $con->prepare("UPDATE assetmanager_hire SET status_key='completed', updated_at=? WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='quote'");
    if ($stmt) {
        $stmt->bind_param('sisi', $now, $quoteId, $tenant, $clientnumber);
        $stmt->execute();
        $stmt->close();
    }
    if (assetmanager_table_exists($con, 'assetmanager_activity')) {
        $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'] ?? $assetId);
                $eventSummary = 'Created from hire quote';
                $eventPayloadJson = assetmanager_encode_json([
                    'source' => $eventAsset['source'] ?? '',
                    'source_id' => (int)($eventAsset['source_id'] ?? 0),
                    'asset_title' => $eventAsset['title'] ?? 'Asset',
                    'quote_id' => $quoteId,
                ]);
                $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_quote', $quoteId, 'complete', $quote, ['contract_id' => $contractId]);
}

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