<?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 tables are not installed yet.']);
}

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

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

$payload = assetmanager_decode_json($contract['contract_payload_json'] ?? '');
$delivery = is_array($payload['delivery'] ?? null) ? $payload['delivery'] : [];
if (empty($delivery['required'])) {
    assetmanager_json_response(['success' => false, 'message' => 'This hire agreement does not require delivery.']);
}

$userId = assetmanager_actor_user_id();
$now = date('Y-m-d H:i:s');
if ($action === 'complete') {
    $delivery['status'] = 'completed';
    $delivery['completed_at'] = $now;
    $delivery['completed_by'] = $userId;
} else {
    $deliveryDate = assetmanager_parse_datetime(enrep_request_string('delivery_date', '', 40));
    $deliveryTime = enrep_request_string('delivery_time', '', 20);
    if (!$deliveryDate || $deliveryTime === '') {
        assetmanager_json_response(['success' => false, 'message' => 'New delivery date and time are required.']);
    }
    $delivery['status'] = 'postponed';
    $delivery['delivery_date'] = substr($deliveryDate, 0, 10);
    $delivery['delivery_time'] = $deliveryTime;
    $delivery['postponed_at'] = $now;
    $delivery['postponed_by'] = $userId;
    $delivery['postpone_reason'] = enrep_request_string('reason', '', 1000);
}
$payload['delivery'] = $delivery;
$payloadJson = assetmanager_encode_json($payload);

$stmt = $con->prepare("UPDATE assetmanager_hire SET payload_json=?, updated_at=? WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='contract'");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Delivery could not be updated.']);
}
$stmt->bind_param('ssisi', $payloadJson, $now, $contractId, $tenant, $clientnumber);
$ok = $stmt->execute();
$stmt->close();

if ($ok) {
    assetmanager_audit($con, $tenant, $clientnumber, $userId, 'hire_delivery', $contractId, $action, [], $delivery);
}

assetmanager_json_response([
    'success' => $ok,
    'message' => $ok ? ($action === 'complete' ? 'Delivery completed.' : 'Delivery postponed.') : 'Delivery could not be updated.',
]);
