<?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);
$signatureMode = enrep_request_enum('signature_mode', ['print', 'digital'], 'print');
if ($clientnumber <= 0 || $contractId <= 0) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire agreement is required.']);
}
assetmanager_json_require_client_access($con, $clientnumber);
assetmanager_json_require_module($con, $tenant, $clientnumber, 'hire', 'Hire');

$stmt = $con->prepare("
    SELECT id, reference AS contract_ref, status_key, starts_at, ends_at, payload_json AS contract_payload_json, created_at
    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 prepared.']);
}
$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 could not be found.']);
}

$autoload = __DIR__ . '/../packages/mpd/vendor/autoload.php';
if (!is_file($autoload)) {
    assetmanager_json_response(['success' => false, 'message' => 'Agreement PDF engine is not available.']);
}
require_once $autoload;

$tenantRoot = realpath(dirname(__DIR__) . '/../' . $tenant);
if ($tenantRoot === false) {
    assetmanager_json_response(['success' => false, 'message' => 'Tenant storage path could not be resolved.']);
}

$relativeDir = 'assetmanager/agreements/client_' . $clientnumber . '/contract_' . $contractId;
$targetDir = $tenantRoot . '/' . $relativeDir;
if (!is_dir($targetDir) && !mkdir($targetDir, 0755, true)) {
    assetmanager_json_response(['success' => false, 'message' => 'Agreement folder could not be created.']);
}

$mpdfTempDir = $tenantRoot . '/assetmanager/tmp/mpdf';
if (!is_dir($mpdfTempDir) && !mkdir($mpdfTempDir, 0755, true)) {
    assetmanager_json_response(['success' => false, 'message' => 'Agreement PDF cache folder could not be created.']);
}

$payload = assetmanager_decode_json($contract['contract_payload_json'] ?? '');
$customer = is_array($payload['customer'] ?? null) ? $payload['customer'] : [];
$hireAssets = is_array($payload['hire_assets'] ?? null) ? $payload['hire_assets'] : (is_array($payload['hire_asset'] ?? null) ? [$payload['hire_asset']] : []);
$delivery = is_array($payload['delivery'] ?? null) ? $payload['delivery'] : [];
$pricing = is_array($payload['pricing'] ?? null) ? $payload['pricing'] : [];
$now = date('Y-m-d H:i:s');

$signaturePath = '';
$signatureRelativePath = '';
if ($signatureMode === 'digital') {
    $signatureData = trim((string)($_POST['signature_data'] ?? ''));
    if (!preg_match('#^data:image/png;base64,#', $signatureData)) {
        assetmanager_json_response(['success' => false, 'message' => 'Customer signature is required.']);
    }
    $binary = base64_decode(substr($signatureData, strpos($signatureData, ',') + 1), true);
    if ($binary === false || strlen($binary) < 100) {
        assetmanager_json_response(['success' => false, 'message' => 'Customer signature could not be read.']);
    }
    $signatureDir = $targetDir . '/signatures';
    if (!is_dir($signatureDir) && !mkdir($signatureDir, 0755, true)) {
        assetmanager_json_response(['success' => false, 'message' => 'Signature folder could not be created.']);
    }
    $signatureName = 'signature-' . date('YmdHis') . '.png';
    $signaturePath = $signatureDir . '/' . $signatureName;
    if (file_put_contents($signaturePath, $binary) === false) {
        assetmanager_json_response(['success' => false, 'message' => 'Customer signature could not be saved.']);
    }
    $signatureRelativePath = $relativeDir . '/signatures/' . $signatureName;
}

$logoPath = realpath(__DIR__ . '/../images/logoSm.png') ?: '';
$customerAddress = array_values(array_filter(array_map('trim', [
    (string)($customer['site'] ?? ''),
    (string)($customer['address'] ?? ''),
    (string)($customer['town'] ?? ''),
    (string)($customer['county'] ?? ''),
    (string)($customer['postcode'] ?? ''),
])));
$contractRef = trim((string)($contract['contract_ref'] ?? ''));
$pdfName = 'hire-agreement-' . ($contractRef !== '' ? preg_replace('/[^A-Za-z0-9._-]/', '_', $contractRef) : $contractId) . '-' . $signatureMode . '.pdf';
$pdfPath = $targetDir . '/' . $pdfName;
$pdfRelativePath = $relativeDir . '/' . $pdfName;

$assetRows = '';
foreach ($hireAssets as $asset) {
    if (!is_array($asset)) {
        continue;
    }
    $identifierParts = array_values(array_filter(array_map('trim', [
        (string)($asset['registration'] ?? ''),
        (string)($asset['plantnumber'] ?? ''),
        (string)($asset['serialnumber'] ?? ''),
    ])));
    $assetRows .= '<tr><td>' . assetmanager_e($asset['title'] ?? 'Asset') . '</td><td>' . assetmanager_e(implode(' | ', array_unique($identifierParts)) ?: '-') . '</td></tr>';
}
if ($assetRows === '') {
    $assetRows = '<tr><td colspan="2">No hire assets recorded.</td></tr>';
}

$signatureHtml = '<div class="signature-box"><div class="signature-line"></div><div>Customer signature</div><div class="small">Name: __________________________ Date: __________________</div></div>';
if ($signatureMode === 'digital' && $signaturePath !== '') {
    $signatureHtml = '<div class="signature-box"><img src="' . assetmanager_e($signaturePath) . '" style="height:45px;max-width:220px;"><div>Digitally signed by customer</div><div class="small">' . assetmanager_e(assetmanager_format_date($now)) . '</div></div>';
}

$deliveryHtml = empty($delivery['required'])
    ? '<p>Customer delivery is not required for this hire.</p>'
    : '<table class="meta"><tr><td><strong>Delivery due</strong></td><td>' . assetmanager_e(trim(assetmanager_format_date($delivery['delivery_date'] ?? '') . ' ' . ($delivery['delivery_time'] ?? '')) ?: '-') . '</td><td><strong>Delivery notes</strong></td><td>' . nl2br(assetmanager_e($delivery['notes'] ?? '-')) . '</td></tr><tr><td><strong>Delivery address</strong></td><td colspan="3">' . nl2br(assetmanager_e($delivery['address'] ?? '-')) . '</td></tr></table>';

$html = '<html><head><style>
body { font-family: sans-serif; font-size: 9pt; color: #1f2933; line-height: 1.22; }
.header { border-bottom: 2px solid #263746; padding-bottom: 5px; margin-bottom: 9px; }
.logo { height: 30px; }
h1 { font-size: 17pt; margin: 0; color: #263746; }
h2 { font-size: 10.5pt; margin: 9px 0 4px; color: #263746; border-bottom: 1px solid #d0d7de; padding-bottom: 2px; }
p { margin: 3px 0 5px; }
table { width: 100%; border-collapse: collapse; }
td, th { border-bottom: 1px solid #e1e4e8; padding: 4px 5px; vertical-align: top; }
th { background: #f1f4f7; text-align: left; }
.meta td { border-bottom: none; padding: 2px 5px; }
.totals td { border-bottom: none; }
.signature-box { border: 1px solid #263746; padding: 8px 10px; margin-top: 8px; min-height: 58px; }
.signature-line { border-bottom: 1px solid #263746; height: 28px; margin-bottom: 5px; }
.small { font-size: 7.5pt; color: #5d6b78; }
</style></head><body>
<htmlpagefooter name="agreementFooter"><div class="small" style="text-align:center;border-top:1px solid #d0d7de;padding-top:3px;">Hire Agreement ' . assetmanager_e($contractRef ?: (string)$contractId) . ' | Generated ' . assetmanager_e(date('d-m-Y H:i')) . ' | Page {PAGENO} of {nbpg}</div></htmlpagefooter>
<sethtmlpagefooter name="agreementFooter" value="on" />
<div class="header"><table class="meta"><tr><td style="width:60%">' . ($logoPath !== '' ? '<img class="logo" src="' . assetmanager_e($logoPath) . '">' : '<strong>EnRep Asset Manager</strong>') . '</td><td style="text-align:right"><h1>Hire Agreement</h1><div>' . assetmanager_e($contractRef ?: ('Agreement #' . $contractId)) . '</div></td></tr></table></div>
<h2>Agreement Details</h2>
<table class="meta">
<tr><td><strong>Start date</strong></td><td>' . assetmanager_e(assetmanager_format_date($contract['starts_at'] ?? '')) . '</td><td><strong>End date</strong></td><td>' . assetmanager_e(assetmanager_format_date($contract['ends_at'] ?? '')) . '</td></tr>
<tr><td><strong>Status</strong></td><td>' . assetmanager_e(ucwords(str_replace('_', ' ', (string)$contract['status_key']))) . '</td><td><strong>Generated for</strong></td><td>' . assetmanager_e($customer['name'] ?? '-') . '</td></tr>
</table>
<h2>Hire Customer</h2>
<table class="meta">
<tr><td><strong>Customer</strong></td><td>' . assetmanager_e($customer['name'] ?? '-') . '</td><td><strong>Contact</strong></td><td>' . assetmanager_e($customer['contact'] ?? '-') . '</td></tr>
<tr><td><strong>Phone</strong></td><td>' . assetmanager_e($customer['phone'] ?? '-') . '</td><td><strong>Email</strong></td><td>' . assetmanager_e($customer['email'] ?? '-') . '</td></tr>
<tr><td><strong>Address</strong></td><td colspan="3">' . nl2br(assetmanager_e($customerAddress ? implode("\n", $customerAddress) : '-')) . '</td></tr>
</table>
<h2>Hire Items</h2>
<table><thead><tr><th>Item</th><th>Identifier</th></tr></thead><tbody>' . $assetRows . '</tbody></table>
<h2>Pricing</h2>
<table class="totals">
<tr><td>Rate basis</td><td>' . assetmanager_e(ucwords((string)($pricing['rate_basis'] ?? '-'))) . '</td><td>Hire subtotal</td><td>' . assetmanager_e($pricing['hire_subtotal'] ?? '-') . '</td></tr>
<tr><td>VAT</td><td>' . assetmanager_e(($pricing['vat_amount'] ?? '-') . ' @ ' . ($pricing['vat_rate'] ?? '-') . '%') . '</td><td>Deposit</td><td>' . assetmanager_e($pricing['deposit_amount'] ?? '-') . '</td></tr>
<tr><td>Insurance</td><td>' . assetmanager_e($pricing['insurance_total'] ?? '-') . '</td><td><strong>Total due</strong></td><td><strong>' . assetmanager_e($pricing['total_due'] ?? '-') . '</strong></td></tr>
</table>
<h2>Delivery</h2>' . $deliveryHtml . '
<h2>Customer Agreement</h2>
<p>The customer confirms receipt of the hire item(s) listed above for the stated hire period and accepts responsibility for care, return condition, agreed charges, deposit use, damage, loss, and recorded additional services.</p>
' . $signatureHtml . '
</body></html>';

try {
    $mpdf = new \Mpdf\Mpdf([
        'tempDir' => $mpdfTempDir,
        'margin_top' => 8,
        'margin_bottom' => 10,
        'margin_left' => 9,
        'margin_right' => 9,
    ]);
    $mpdf->WriteHTML($html);
    $mpdf->Output($pdfPath, \Mpdf\Output\Destination::FILE);
} catch (Throwable $e) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire agreement PDF could not be generated.']);
}

$payload['agreement_pdf'] = [
    'file_path' => $pdfRelativePath,
    'file_url' => str_replace('\\', '/', substr($pdfRelativePath, strlen('assetmanager/'))),
    'signature_mode' => $signatureMode,
    'signature_path' => $signatureRelativePath,
    'signature_status' => $signatureMode === 'digital' ? 'signed' : 'print_signature_required',
    'generated_at' => $now,
];
$payloadJson = assetmanager_encode_json($payload);
$currentStatus = (string)($contract['status_key'] ?? '');
$newStatus = $signatureMode === 'digital' ? 'active' : ($currentStatus === 'active' ? 'active' : 'pending_signature');
$stmt = $con->prepare("UPDATE assetmanager_hire SET status_key=?, payload_json=?, updated_at=? WHERE id=? AND tenant_key=? AND clientnumber=? AND record_type='contract'");
if (!$stmt) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire agreement PDF was created but could not be linked.']);
}
$stmt->bind_param('sssisi', $newStatus, $payloadJson, $now, $contractId, $tenant, $clientnumber);
$ok = $stmt->execute();
$stmt->close();
if (!$ok) {
    assetmanager_json_response(['success' => false, 'message' => 'Hire agreement PDF was created but could not be linked.']);
}

assetmanager_audit($con, $tenant, $clientnumber, assetmanager_actor_user_id(), 'hire_contract', $contractId, 'agreement_pdf', [], $payload['agreement_pdf']);

assetmanager_json_response([
    'success' => true,
    'message' => $signatureMode === 'digital' ? 'Hire agreement signed and saved.' : 'Hire agreement PDF created for print/sign.',
    'file_url' => $payload['agreement_pdf']['file_url'],
    'signature_status' => $payload['agreement_pdf']['signature_status'],
    'status_key' => $newStatus,
]);
