<?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) {
    echo '<div class="note note-danger">Tenant database connection unavailable.</div>';
    exit;
}
$con->set_charset('utf8mb4');

$clientnumber = enrep_request_int('clientnumber', 0);
$contractId = enrep_request_int('contract_id', 0);
if ($clientnumber <= 0 || $contractId <= 0) {
    echo '<div class="note note-danger">Hire agreement could not be loaded.</div>';
    exit;
}
if (!assetmanager_user_can_access_client($con, $clientnumber)) {
    echo '<div class="note note-danger">You do not have access to this client.</div>';
    exit;
}
if (!assetmanager_module_enabled($con, $tenant, $clientnumber, 'hire')) {
    echo '<div class="note note-warning">Hire is not enabled for this client.</div>';
    exit;
}
if (!assetmanager_table_exists($con, 'assetmanager_hire')) {
    echo '<div class="note note-warning">Hire agreement table is not installed yet.</div>';
    exit;
}

$stmt = $con->prepare("
    SELECT id, reference AS contract_ref, status_key, starts_at, ends_at, payload_json AS contract_payload_json, created_at, updated_at
    FROM assetmanager_hire
    WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='contract'
    LIMIT 1
");
if (!$stmt) {
    echo '<div class="note note-danger">Hire agreement could not be prepared.</div>';
    exit;
}
$stmt->bind_param('isi', $contractId, $tenant, $clientnumber);
$stmt->execute();
$contract = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$contract) {
    echo '<div class="note note-danger">Hire agreement could not be found.</div>';
    exit;
}

$payload = assetmanager_decode_json($contract['contract_payload_json'] ?? '');
$customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
$hireAsset = is_array($payload['hire_asset'] ?? null) ? $payload['hire_asset'] : [];
$hireAssets = is_array($payload['hire_assets'] ?? null) ? $payload['hire_assets'] : ($hireAsset ? [$hireAsset] : []);
$delivery = is_array($payload['delivery'] ?? null) ? $payload['delivery'] : [];
$pricing = is_array($payload['pricing'] ?? null) ? $payload['pricing'] : [];
$agreementPdf = is_array($payload['agreement_pdf'] ?? null) ? $payload['agreement_pdf'] : [];
$assetSource = (string)($hireAsset['source'] ?? '');
$assetSourceId = (int)($hireAsset['source_id'] ?? 0);
$assetTitle = (string)($hireAsset['title'] ?? 'Asset');

$customerAddressLines = array_values(array_filter(array_map('trim', [
    (string)($customer['site'] ?? ''),
    (string)($customer['address'] ?? ''),
    (string)($customer['town'] ?? ''),
    (string)($customer['county'] ?? ''),
    (string)($customer['postcode'] ?? ''),
])));

if (!function_exists('assetmanager_hire_profile_item_identifier')) {
    function assetmanager_hire_profile_item_identifier(array $asset): string
    {
        $parts = array_values(array_filter(array_map('trim', [
            (string)($asset['registration'] ?? ''),
            (string)($asset['plantnumber'] ?? ''),
            (string)($asset['serialnumber'] ?? ''),
        ])));
        return implode(' | ', array_unique($parts)) ?: '-';
    }
}

if (!function_exists('assetmanager_hire_profile_event_asset')) {
    function assetmanager_hire_profile_event_asset(array $event): string
    {
        $payload = is_array($event['payload'] ?? null) ? $event['payload'] : [];
        $title = trim((string)($payload['asset_title'] ?? ''));
        if ($title !== '') {
            return $title;
        }
        $source = trim((string)($payload['source'] ?? ''));
        $sourceId = (int)($payload['source_id'] ?? 0);
        return ($source !== '' && $sourceId > 0) ? $source . ' #' . $sourceId : '-';
    }
}

$events = [];
if (assetmanager_table_exists($con, 'assetmanager_activity')) {
    $stmt = $con->prepare("
        SELECT id, activity_type AS event_type, activity_at AS event_at, payload_json AS event_payload_json, created_at
        FROM assetmanager_activity
        WHERE tenant_key=? AND clientnumber=? AND module_key='hire' AND parent_type='contract' AND parent_id=?
        ORDER BY activity_at DESC, id DESC
        LIMIT 50
    ");
    if ($stmt) {
        $stmt->bind_param('sii', $tenant, $clientnumber, $contractId);
        $stmt->execute();
        $res = $stmt->get_result();
        while ($row = $res->fetch_assoc()) {
            $row['payload'] = assetmanager_decode_json($row['event_payload_json'] ?? '');
            $events[] = $row;
        }
        $stmt->close();
    }
}
?>
<style>
.assetmanager-hire-profile .assetmanager-form-section {
    border: 1px solid rgba(0,0,0,.12);
    border-radius: 8px;
    margin-bottom: .85rem;
    background: #fff;
    overflow: hidden;
}
.assetmanager-hire-profile .assetmanager-form-section-title {
    background: #263746;
    color: #fff;
    font-weight: 700;
    padding: .55rem .75rem;
}
.assetmanager-hire-profile .assetmanager-form-section-body {
    padding: .85rem;
}
.assetmanager-hire-profile .assetmanager-multiline {
    white-space: pre-line;
}
@media print {
    .assetmanager-print-hide {
        display: none !important;
    }
    .assetmanager-hire-profile .assetmanager-form-section {
        break-inside: avoid;
    }
}
</style>
<div class="assetmanager-hire-profile" id="assetManagerHireAgreementPrint">
    <div class="assetmanager-form-section">
        <div class="card-header assetmanager-form-section-title d-flex align-items-center justify-content-between gap-2">
            <span><i class="fad fa-handshake"></i> Hire Agreement</span>
            <span class="d-flex align-items-center gap-2">
                <?php if (!empty($agreementPdf['file_url'])) { ?>
                <button type="button" class="btn btn-sm btn-light assetmanager-print-hide assetmanager-view-hire-pdf" data-pdf-url="<?= assetmanager_e($agreementPdf['file_url']) ?>">
                    <i class="fad fa-file-pdf"></i> View PDF
                </button>
                <?php } ?>
                <button type="button" class="btn btn-sm btn-light assetmanager-print-hide" onclick="assetManagerOpenHireDigitalSignature(<?= (int)$contractId ?>)">
                    <i class="fad fa-signature"></i> Digital Sign
                </button>
                <button type="button" class="btn btn-sm btn-light assetmanager-print-hide" onclick="assetManagerGenerateHireAgreementPdf(<?= (int)$contractId ?>, 'print')">
                    <i class="fad fa-file-pdf"></i> Print / Sign PDF
                </button>
                <span class="badge bg-light text-dark"><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)$contract['status_key']))) ?></span>
            </span>
        </div>
        <div class="assetmanager-form-section-body">
            <div class="row g-2">
                <div class="col-12 col-md-3">
                    <label class="form-label">Agreement ref</label>
                    <input type="text" class="form-control" value="<?= assetmanager_e($contract['contract_ref'] ?? '') ?>" readonly>
                </div>
                <div class="col-12 col-md-3">
                    <label class="form-label">Start date</label>
                    <input type="text" class="form-control" value="<?= assetmanager_e(assetmanager_format_date($contract['starts_at'] ?? '')) ?>" readonly>
                </div>
                <div class="col-12 col-md-3">
                    <label class="form-label">End date</label>
                    <input type="text" class="form-control" value="<?= assetmanager_e(assetmanager_format_date($contract['ends_at'] ?? '')) ?>" readonly>
                </div>
                <div class="col-12 col-md-3">
                    <label class="form-label">Customer site</label>
                    <input type="text" class="form-control" value="<?= assetmanager_e($payload['site'] ?? $customer['site'] ?? '') ?>" readonly>
                </div>
            </div>
        </div>
    </div>
    <div class="assetmanager-form-section">
        <div class="card-header assetmanager-form-section-title"><i class="fad fa-user-helmet-safety"></i> Hire Customer</div>
        <div class="assetmanager-form-section-body">
            <dl class="row small mb-0">
                <dt class="col-12 col-md-3">Hire customer</dt><dd class="col-12 col-md-9"><?= assetmanager_e($customer['name'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Contact</dt><dd class="col-12 col-md-9"><?= assetmanager_e($customer['contact'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Phone</dt><dd class="col-12 col-md-9"><?= assetmanager_e($customer['phone'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Email</dt><dd class="col-12 col-md-9"><?= assetmanager_e($customer['email'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Address</dt><dd class="col-12 col-md-9 assetmanager-multiline"><?= assetmanager_e($customerAddressLines ? implode("\n", $customerAddressLines) : '-') ?></dd>
            </dl>
        </div>
    </div>
    <div class="assetmanager-form-section">
        <div class="card-header assetmanager-form-section-title d-flex align-items-center justify-content-between gap-2">
            <span><i class="fad fa-truck-ramp-box"></i> Delivery</span>
            <?php if (!empty($delivery['required'])) { ?>
            <span class="badge bg-light text-dark"><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)($delivery['status'] ?? 'pending')))) ?></span>
            <?php } ?>
        </div>
        <div class="assetmanager-form-section-body">
            <?php if (empty($delivery['required'])) { ?>
            <div class="text-muted small">Customer delivery is not required for this hire.</div>
            <?php } else { ?>
            <dl class="row small mb-0">
                <dt class="col-12 col-md-3">Delivery due</dt><dd class="col-12 col-md-9"><?= assetmanager_e(trim(assetmanager_format_date($delivery['delivery_date'] ?? '') . ' ' . ($delivery['delivery_time'] ?? '')) ?: '-') ?></dd>
                <dt class="col-12 col-md-3">Address</dt><dd class="col-12 col-md-9 assetmanager-multiline"><?= assetmanager_e($delivery['address'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Notes</dt><dd class="col-12 col-md-9 assetmanager-multiline"><?= assetmanager_e($delivery['notes'] ?? '-') ?></dd>
                <?php if (!empty($delivery['postpone_reason'])) { ?>
                <dt class="col-12 col-md-3">Postpone reason</dt><dd class="col-12 col-md-9"><?= assetmanager_e($delivery['postpone_reason']) ?></dd>
                <?php } ?>
            </dl>
            <?php if (in_array((string)($delivery['status'] ?? 'pending'), ['pending', 'postponed'], true)) { ?>
            <div class="d-flex flex-wrap gap-2 mt-3 assetmanager-print-hide">
                <button type="button" class="btn btn-sm btn-success assetmanager-complete-hire-delivery" data-contract-id="<?= (int)$contractId ?>"><i class="fad fa-check"></i> Complete Delivery</button>
                <button type="button" class="btn btn-sm btn-secondary assetmanager-postpone-hire-delivery" data-contract-id="<?= (int)$contractId ?>"><i class="fad fa-calendar-clock"></i> Postpone</button>
            </div>
            <?php } ?>
            <?php } ?>
        </div>
    </div>
    <div class="assetmanager-form-section">
        <div class="card-header assetmanager-form-section-title"><i class="fad fa-box"></i> Hire Assets</div>
        <div class="assetmanager-form-section-body">
            <div class="table-responsive">
                <table class="table table-sm align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Item</th>
                            <th>Identifier</th>
                            <th class="text-end assetmanager-print-hide">Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($hireAssets as $asset) { ?>
                        <tr>
                            <td><?= assetmanager_e($asset['title'] ?? 'Asset') ?></td>
                            <td><?= assetmanager_e(assetmanager_hire_profile_item_identifier($asset)) ?></td>
                            <td class="text-end assetmanager-print-hide">
                                <?php if ((string)($asset['source'] ?? '') !== '' && (int)($asset['source_id'] ?? 0) > 0) { ?>
                                <button type="button" class="btn btn-sm btn-light assetmanager-open-full-asset" data-source="<?= assetmanager_e($asset['source']) ?>" data-source-id="<?= (int)$asset['source_id'] ?>">
                                    <i class="fad fa-folder-open"></i> Open Asset
                                </button>
                                <?php } ?>
                            </td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <div class="assetmanager-form-section">
        <div class="card-header assetmanager-form-section-title"><i class="fad fa-pound-sign"></i> Hire Pricing</div>
        <div class="assetmanager-form-section-body">
            <dl class="row small mb-0">
                <dt class="col-12 col-md-3">Rate basis</dt><dd class="col-12 col-md-9"><?= assetmanager_e(ucwords((string)($pricing['rate_basis'] ?? '-'))) ?></dd>
                <dt class="col-12 col-md-3">Hire subtotal</dt><dd class="col-12 col-md-9"><?= assetmanager_e($pricing['hire_subtotal'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">VAT</dt><dd class="col-12 col-md-9"><?= assetmanager_e(($pricing['vat_amount'] ?? '-') . ' @ ' . ($pricing['vat_rate'] ?? '-') . '%') ?></dd>
                <dt class="col-12 col-md-3">Deposit</dt><dd class="col-12 col-md-9"><?= assetmanager_e($pricing['deposit_amount'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Insurance</dt><dd class="col-12 col-md-9"><?= assetmanager_e($pricing['insurance_total'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Total due</dt><dd class="col-12 col-md-9 fw-bold"><?= assetmanager_e($pricing['total_due'] ?? '-') ?></dd>
                <dt class="col-12 col-md-3">Agreement document</dt><dd class="col-12 col-md-9"><?= assetmanager_e(!empty($agreementPdf['signature_status']) ? ucwords(str_replace('_', ' ', (string)$agreementPdf['signature_status'])) : 'Not generated') ?></dd>
            </dl>
        </div>
    </div>
    <div class="assetmanager-form-section">
        <div class="card-header assetmanager-form-section-title d-flex align-items-center justify-content-between gap-2">
            <span><i class="fad fa-timeline"></i> Hire Events</span>
            <button type="button" class="btn btn-sm btn-light assetmanager-print-hide" onclick="assetManagerOpenHireEvent(<?= (int)$contractId ?>)">
                <i class="fad fa-plus"></i> Log Event
            </button>
        </div>
        <div class="assetmanager-form-section-body">
            <?php if (empty($events)) { ?>
            <div class="text-muted small">No hire events have been logged yet.</div>
            <?php } else { ?>
            <div class="table-responsive">
                <table class="table table-sm align-middle mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>Event</th>
                            <th>Date</th>
                            <th>Asset</th>
                            <th>Reference</th>
                            <th>Condition</th>
                            <th>Notes</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($events as $event) { ?>
                        <tr>
                            <td><?= assetmanager_e(ucwords(str_replace('_', ' ', (string)$event['event_type']))) ?></td>
                            <td><?= assetmanager_e(assetmanager_format_date($event['event_at'] ?? '')) ?></td>
                            <td><?= assetmanager_e(assetmanager_hire_profile_event_asset($event)) ?></td>
                            <td><?= assetmanager_e($event['payload']['event_ref'] ?? '-') ?></td>
                            <td><?= assetmanager_e($event['payload']['condition'] ?? '-') ?></td>
                            <td class="assetmanager-multiline"><?= assetmanager_e($event['payload']['notes'] ?? '-') ?></td>
                        </tr>
                        <?php } ?>
                    </tbody>
                </table>
            </div>
            <?php } ?>
        </div>
    </div>
</div>
