<?php
require_once __DIR__ . '/../../functions/security.php';

$tenant = enrep_tenant_segment();
if ($tenant !== '' && file_exists('../../../' . $tenant . '/config.php')) {
    require_once('../../../' . $tenant . '/config.php');
}
if (file_exists('/config.php')) {
    require_once('/config.php');
}

if (!isset($GLOBALS['con']) || !($GLOBALS['con'] instanceof mysqli)) {
    enrep_fail(400, 'Tenant config not found');
}

enrep_require_admin();
require_once __DIR__ . '/../plant_changes/plant_change_helpers.php';

function plantChangesE($value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function plantChangesDateToTs(string $value, int $fallback = 0): int
{
    $value = trim($value);
    if ($value === '') {
        return $fallback;
    }

    $ts = strtotime($value);
    return $ts === false ? $fallback : $ts;
}

function plantChangesDateToEndTs(string $value, int $fallback = 0): int
{
    $ts = plantChangesDateToTs($value, $fallback);
    if ($ts <= 0) {
        return $ts;
    }

    return strtotime(date('Y-m-d 23:59:59', $ts)) ?: $ts;
}

function plantChangesClientOptions(int $selected): string
{
    $ret = '<option value="">Select client</option>';
    $stmt = $GLOBALS['con']->prepare("SELECT `clientnumber`,`clientname` FROM `clientdetails` WHERE `statuslive`='1' ORDER BY `clientname` ASC");
    if (!$stmt) {
        return $ret;
    }

    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    while ($row = $res->fetch_assoc()) {
        $clientnumber = (int)$row['clientnumber'];
        $ret .= '<option value="' . $clientnumber . '"' . ($clientnumber === $selected ? ' selected' : '') . '>' . plantChangesE($row['clientname']) . '</option>';
    }

    return $ret;
}

function plantChangesClientRenewal(int $clientnumber): int
{
    if ($clientnumber <= 0) {
        return 0;
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `renewal_date` FROM `clientdetails` WHERE `clientnumber`=? LIMIT 1");
    if (!$stmt) {
        return 0;
    }
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $row = $res ? $res->fetch_assoc() : null;
    return (int)($row['renewal_date'] ?? 0);
}

function plantChangesClientContractAmount(int $clientnumber): float
{
    if ($clientnumber <= 0) {
        return 0.0;
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `rate_per_hour` FROM `clientdetails` WHERE `clientnumber`=? LIMIT 1");
    if (!$stmt) {
        return 0.0;
    }

    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $row = $res ? $res->fetch_assoc() : null;
    return (float)($row['rate_per_hour'] ?? 0);
}

function plantChangesClientIuPricing(int $clientnumber): array
{
    if ($clientnumber <= 0) {
        return ['iu_base_rate' => 0.0, 'iu_admin_fee' => 0.0];
    }

    $stmt = $GLOBALS['con']->prepare("SELECT `iu_base_rate`, `iu_admin_fee` FROM `clientdetails` WHERE `clientnumber`=? LIMIT 1");
    if (!$stmt) {
        return ['iu_base_rate' => 0.0, 'iu_admin_fee' => 0.0];
    }

    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $row = $res ? $res->fetch_assoc() : null;
    return [
        'iu_base_rate' => (float)($row['iu_base_rate'] ?? 0),
        'iu_admin_fee' => (float)($row['iu_admin_fee'] ?? 0),
    ];
}

function plantChangesCurrentUiTotal(int $clientnumber): float
{
    if ($clientnumber <= 0) {
        return 0.0;
    }

    $stmt = $GLOBALS['con']->prepare("
        SELECT SUM(COALESCE(d.`units`, 0)) AS `total_ui`
        FROM `itemdetails` i
        LEFT JOIN `dd_plant` d ON d.`code` = i.`code`
        WHERE i.`clientnumber`=? AND i.`statuslive`='1'
    ");
    if (!$stmt) {
        return 0.0;
    }

    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $row = $res ? $res->fetch_assoc() : null;
    return round((float)($row['total_ui'] ?? 0), 2);
}

function plantChangesCurrentPlantSummary(int $clientnumber): array
{
    if ($clientnumber <= 0) {
        return ['total_items' => 0, 'total_ui' => 0.0];
    }

    $stmt = $GLOBALS['con']->prepare("
        SELECT COUNT(*) AS `total_items`, COALESCE(SUM(CAST(d.`units` AS DECIMAL(10,2))), 0) AS `total_ui`
        FROM `itemdetails` i
        LEFT JOIN `dd_plant` d ON d.`code` = i.`code`
        WHERE i.`clientnumber`=? AND i.`statuslive`='1'
    ");
    if (!$stmt) {
        return ['total_items' => 0, 'total_ui' => 0.0];
    }

    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();
    $row = $res ? $res->fetch_assoc() : [];
    return [
        'total_items' => (int)($row['total_items'] ?? 0),
        'total_ui' => (float)($row['total_ui'] ?? 0),
    ];
}

function plantChangesCurrentItemOptions(int $clientnumber): string
{
    if ($clientnumber <= 0) {
        return '<option value="">Select current plant</option>';
    }

    $stmt = $GLOBALS['con']->prepare("
        SELECT i.`itemnumber`, i.`desc`, i.`plantnumber`, i.`serialnumber`, i.`locnumber`,
               l.`locname`, COALESCE(d.`units`, 0) AS `units`
        FROM `itemdetails` i
        LEFT JOIN `locations` l ON l.`locnumber` = i.`locnumber`
        LEFT JOIN `dd_plant` d ON d.`code` = i.`code`
        WHERE i.`clientnumber`=? AND i.`statuslive`='1'
        ORDER BY i.`desc`, i.`serialnumber`, i.`plantnumber`
    ");
    if (!$stmt) {
        return '<option value="">Select current plant</option>';
    }

    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    $ret = '<option value="">Select current plant</option>';
    while ($res && ($row = $res->fetch_assoc())) {
        $data = [
            'type' => 'manual_add',
            'itemnumber' => (int)$row['itemnumber'],
            'desc' => (string)($row['desc'] ?? ''),
            'plantnumber' => (string)($row['plantnumber'] ?? ''),
            'serialnumber' => (string)($row['serialnumber'] ?? ''),
            'locnumber' => (int)($row['locnumber'] ?? 0),
            'locname' => (string)($row['locname'] ?? ''),
            'ui' => round((float)($row['units'] ?? 0), 2),
        ];
        $label = trim((string)$row['desc'] . ' / SN: ' . ($row['serialnumber'] ?: '-') . ' / PN: ' . ($row['plantnumber'] ?: '-'));
        $ret .= '<option value="' . (int)$row['itemnumber'] . '" data-entry="' . plantChangesE(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)) . '">' . plantChangesE($label) . '</option>';
    }

    return $ret;
}

function plantChangesReportHistory(int $clientnumber): array
{
    if ($clientnumber <= 0 || !plantChangeDbReady('plant_change_reports')) {
        return [];
    }

    $stmt = $GLOBALS['con']->prepare("SELECT * FROM `plant_change_reports` WHERE `clientnumber`=? ORDER BY `created_at` DESC LIMIT 20");
    if (!$stmt) {
        return [];
    }
    $stmt->bind_param('i', $clientnumber);
    $stmt->execute();
    $res = $stmt->get_result();
    $stmt->close();

    $rows = [];
    while ($res && ($row = $res->fetch_assoc())) {
        $rows[] = $row;
    }
    return $rows;
}

$clientnumber = enrep_request_int('clientnumber');
$action = enrep_request_string('action', '', 40);
$fromInput = enrep_request_string('from', '', 40);
$toInput = enrep_request_string('to', '', 40);
$renewalDate = plantChangesClientRenewal($clientnumber);
$toDefault = $renewalDate > 0 ? $renewalDate : time();
$toTs = plantChangesDateToEndTs($toInput, $toDefault);
if ($toTs <= 0) {
    $toTs = time();
}
$fromDefaultBase = strtotime(date('Y-m-d', $toTs)) ?: $toTs;
$fromDefault = strtotime('-1 year', $fromDefaultBase) ?: strtotime('-12 months');
$fromTs = plantChangesDateToTs($fromInput, $fromDefault);
if ($fromTs <= 0) {
    $fromTs = $fromDefault;
}
plantChangeDebugLog(
    'MODULE request action=' . $action .
    ' client=' . $clientnumber .
    ' from_input=' . $fromInput .
    ' to_input=' . $toInput .
    ' from_ts=' . $fromTs . ' (' . date('Y-m-d H:i:s', $fromTs) . ')' .
    ' to_ts=' . $toTs . ' (' . date('Y-m-d H:i:s', $toTs) . ')'
);

if (in_array($action, ['remove_confirm', 'accept_confirm', 'reject_confirm', 'remove_log_confirm'], true)) {
    $reportId = enrep_request_int('report_id');
    if ($action === 'remove_log_confirm') {
        $logGroup = enrep_request_string('log_group', '', 120);
?>
<div class="alert alert-warning mb-0">
    <strong>Remove this added plant log entry?</strong><br>
    This will remove the selected tracked change from the current assessment and recalculate the added IU.
</div>
<input type="hidden" id="plantChangeRemoveLogGroup" value="<?= plantChangesE($logGroup) ?>">
<?php
        exit;
    }
    if ($action === 'accept_confirm') {
        $report = plantChangeReportRow($reportId, $clientnumber);
        $endorsementType = is_array($report) && function_exists('plantChangeReportEndorsementType') ? plantChangeReportEndorsementType($report) : 'full_term';
        $newValue = is_array($report) ? (float)($report['new_contract_amount'] ?? 0) : 0.0;
        $adminFeeValue = is_array($report) ? (float)($report['admin_fee'] ?? 0) : 0.0;
        $netValue = is_array($report) ? (float)($report['net_amount'] ?? ($newValue + $adminFeeValue)) : 0.0;
        $vatValue = is_array($report) ? (float)($report['vat_amount'] ?? 0) : 0.0;
        $finalValue = is_array($report) ? (float)($report['final_amount'] ?? ($netValue + $vatValue)) : 0.0;
        $defaultRenewal = $renewalDate > 0 ? $renewalDate : time();
        if ($endorsementType === 'mid_term') {
?>
<div class="alert alert-success mb-0">
    <strong>Mark this mid term endorsement as accepted?</strong><br>
    This will move it into Historic without changing the client contract fee.
</div>
<input type="hidden" id="plantChangeAcceptReportId" value="<?= (int)$reportId ?>">
<?php
            exit;
        }
?>
<div class="alert alert-success">
    <strong>Mark this plant change renewal as accepted?</strong><br>
    This will update the client renewal date and contract fee, then open Direct Mailer with a New Cover Confirmed PDF.
</div>
<div class="plant-change-calc p-3 mb-3">
    <div class="plant-change-calc-row">
        <span class="plant-change-calc-label">Renewal price <span class="text-muted">(less admin fee)</span></span>
        <span class="plant-change-calc-value">&pound;<?= plantChangesE(number_format($newValue, 2)) ?></span>
    </div>
    <div class="plant-change-calc-row">
        <span class="plant-change-calc-label">Admin fee</span>
        <span class="plant-change-calc-value">&pound;<?= plantChangesE(number_format($adminFeeValue, 2)) ?></span>
    </div>
    <div class="plant-change-calc-row">
        <span class="plant-change-calc-label">Subtotal before VAT</span>
        <span class="plant-change-calc-value">&pound;<?= plantChangesE(number_format($netValue, 2)) ?></span>
    </div>
    <div class="plant-change-calc-row">
        <span class="plant-change-calc-label">VAT</span>
        <span class="plant-change-calc-value">&pound;<?= plantChangesE(number_format($vatValue, 2)) ?></span>
    </div>
    <div class="plant-change-calc-row plant-change-calc-final">
        <span class="plant-change-calc-label fw-semibold">Total charged to customer</span>
        <span class="plant-change-calc-value">&pound;<?= plantChangesE(number_format($finalValue, 2)) ?></span>
    </div>
</div>
<label for="plantChangeAcceptRenewalDate" class="form-label">Renewal date</label>
<input type="text" id="plantChangeAcceptRenewalDate" class="form-control date-picker"
    value="<?= plantChangesE(date('d-m-Y', $defaultRenewal)) ?>">
<input type="hidden" id="plantChangeAcceptReportId" value="<?= (int)$reportId ?>">
<script>
(function() {
    if (typeof mdb === 'undefined') return;
    var modalElement = document.getElementById('plantChangeConfirmBox');
    if (!modalElement) return;
    var datepickerElements = modalElement.querySelectorAll('.date-picker');
    datepickerElements.forEach(function(datepickerEl) {
        new mdb.Datepicker(datepickerEl, {
            confirmDateOnSelect: true,
            format: 'dd-mm-yyyy'
        });
    });
})();
</script>
<?php
        exit;
    }
    if ($action === 'reject_confirm') {
?>
<div class="alert alert-danger mb-0">
    <strong>Reject this full term endorsement?</strong><br>
    This will archive the client by setting their live status to inactive.
</div>
<input type="hidden" id="plantChangeRejectReportId" value="<?= (int)$reportId ?>">
<?php
        exit;
    }
    ?>
<div class="alert alert-warning mb-0">
    <strong>Remove saved plant change report?</strong><br>
    This will hide the saved run from the active list. Accepted reports cannot be removed.
</div>
<input type="hidden" id="plantChangeRemoveReportId" value="<?= (int)$reportId ?>">
<?php
    exit;
}

if (in_array($action, ['save_report', 'remove_report', 'remove_log', 'mark_sent', 'accept_report', 'reject_report'], true)) {
    ob_start();
    header('Content-Type: application/json; charset=utf-8');
    try {
        $ok = false;
        $message = 'Plant change report updated.';
        $responseExtra = [];
        if ($action === 'save_report') {
            $rows = plantChangeFetchLogs($clientnumber, $fromTs, $toTs);
            $manualEntriesJson = enrep_request_string('manual_entries', '[]', 100000);
            $manualEntries = json_decode($manualEntriesJson, true);
            $summary = plantChangeSummarise($rows, is_array($manualEntries) ? $manualEntries : []);
            $endorsementType = enrep_request_string('endorsement_type', 'full_term', 40) === 'mid_term' ? 'mid_term' : 'full_term';
            $unitRateInput = enrep_request_string('unit_rate', '', 80);
            $baseContractInput = enrep_request_string('base_contract_amount', '', 80);
            $newContractInput = enrep_request_string('new_contract_amount', '', 80);
            $unitRateValue = (float)preg_replace('/[^0-9.\-]/', '', $unitRateInput);
            $baseContractValue = (float)preg_replace('/[^0-9.\-]/', '', $baseContractInput);
            $newContractValue = (float)preg_replace('/[^0-9.\-]/', '', $newContractInput);
            if ($unitRateValue <= 0) {
                $message = 'Unable to create document because the client IU rate is missing.';
            } elseif ($endorsementType === 'full_term' && $baseContractValue <= 0 && $newContractValue <= 0) {
                $message = 'Unable to create renewal because the client contract fee is missing.';
            } else {
                $ok = plantChangeSaveReport(
                    $clientnumber,
                    $fromTs,
                    $toTs,
                    $summary,
                    enrep_request_string('manual_lines', '', 20000),
                    $unitRateInput,
                    $baseContractInput,
                    $newContractInput,
                    enrep_request_string('admin_fee', '', 80),
                    enrep_request_string('vat_rate', '', 80),
                    $manualEntriesJson,
                    $endorsementType,
                    enrep_request_string('mid_term_amount', '', 80),
                    enrep_request_string('mid_term_admin_fee', '', 80),
                    enrep_request_string('uplift_percent', '', 80)
                );
                $message = $ok ? 'Report history saved.' : 'Plant change report table is not available.';
            }
        } elseif ($action === 'remove_report') {
            $ok = plantChangeRemoveReport(enrep_request_int('report_id'), $clientnumber);
            $message = $ok ? 'Plant change report removed.' : 'Unable to remove plant change report.';
        } elseif ($action === 'remove_log') {
            $ok = plantChangeRemoveLogGroup($clientnumber, enrep_request_string('log_group', '', 120));
            $message = $ok ? 'Plant change log entry removed and assessment corrected.' : 'Unable to remove plant change log entry.';
        } elseif ($action === 'mark_sent') {
            $ok = plantChangeMarkReportSent(enrep_request_int('report_id'), $clientnumber, enrep_request_string('email_to', '', 500));
            $message = $ok ? 'Plant change email marked as sent.' : 'Unable to track plant change email.';
        } elseif ($action === 'accept_report') {
            $reportId = enrep_request_int('report_id');
            $report = plantChangeReportRow($reportId, $clientnumber);
            $endorsementType = is_array($report) && function_exists('plantChangeReportEndorsementType') ? plantChangeReportEndorsementType($report) : 'full_term';
            $acceptRenewalDate = plantChangesDateToTs(enrep_request_string('renewal_date', '', 40), time());
            $ok = plantChangeAcceptReport($reportId, $clientnumber, $acceptRenewalDate);
            $message = $ok ? 'Plant change document accepted.' : 'Unable to accept plant change report.';

            if ($ok && $endorsementType === 'full_term' && is_array($report)) {
                $acceptedReport = plantChangeReportRow($reportId, $clientnumber) ?: $report;
                $acceptancePdf = function_exists('plantChangeGenerateAcceptancePdf') ? plantChangeGenerateAcceptancePdf($reportId, $clientnumber, $acceptRenewalDate, $acceptedReport) : '';
                if ($acceptancePdf !== '') {
                    if (function_exists('plantChangeStoreAcceptancePdfPath')) {
                        plantChangeStoreAcceptancePdfPath($reportId, $clientnumber, $acceptancePdf);
                    }
                    $clientDetailsForMail = plantChangeClientDetails($clientnumber);
                    $adminDetailsForMail = plantChangeCurrentAdminDetails();
                    $pdfSource = trim(dirname(ltrim($acceptancePdf, '/')), '.');
                    $pdfName = basename($acceptancePdf);
                    $emailMessage = '<p>Please find attached confirmation of your Engineering Inspection cover.</p>';
                    $emailMessage .= '<p>The inspection fee is <strong>&pound;' . number_format((float)($acceptedReport['final_amount'] ?? 0), 2) . '</strong> including VAT.</p>';
                    $adminName = trim((string)($adminDetailsForMail['name'] ?? ''));
                    $adminTel = trim((string)($adminDetailsForMail['tel'] ?? ''));
                    $adminEmail = trim((string)($adminDetailsForMail['email'] ?? ''));
                    if ($adminName !== '' || $adminTel !== '' || $adminEmail !== '') {
                        $emailMessage .= '<p>Kind regards';
                        if ($adminName !== '') {
                            $emailMessage .= '<br>' . plantChangesE($adminName);
                        }
                        if ($adminTel !== '') {
                            $emailMessage .= '<br>Tel: ' . plantChangesE($adminTel);
                        }
                        if ($adminEmail !== '') {
                            $emailMessage .= '<br>Email: ' . plantChangesE($adminEmail);
                        }
                        $emailMessage .= '</p>';
                    }
                    $emailPayload = [
                        'mode' => 'renewal',
                        'addressMode' => 'renewal',
                        'clientNumber' => (string)$clientnumber,
                        'clientName' => (string)($clientDetailsForMail['clientname'] ?? ''),
                        'primaryEmail' => (string)($clientDetailsForMail['email'] ?? ''),
                        'secondaryEmail' => (string)($clientDetailsForMail['pri_contact_email'] ?? ''),
                        'subject' => 'New cover confirmed',
                        'message' => $emailMessage,
                        'filePath' => $pdfSource,
                        'fileName' => $pdfName,
                        'sentCallbackUrl' => $rootUrl . '/includes/master/plant_changes.php?tenant=' . rawurlencode($tenantUrl) . '&clientnumber=' . $clientnumber . '&report_id=' . $reportId . '&action=mark_sent',
                    ];
                    $responseExtra['mailer_payload64'] = base64_encode(json_encode($emailPayload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
                    $message = 'Renewal accepted and New Cover Confirmed email prepared.';
                } else {
                    $message = 'Renewal accepted, but the New Cover Confirmed PDF could not be generated' . (function_exists('plantChangeLastError') && plantChangeLastError() !== '' ? ': ' . plantChangeLastError() : '.');
                }
            } elseif ($ok) {
                $message = 'Mid term document accepted.';
            }
        } elseif ($action === 'reject_report') {
            $ok = plantChangeRejectReport(enrep_request_int('report_id'), $clientnumber);
            $message = $ok ? 'Plant change report rejected and client archived.' : 'Unable to reject plant change report.';
        }

        $strayOutput = trim((string)ob_get_clean());
        $message = $ok ? $message : (function_exists('plantChangeLastError') && plantChangeLastError() !== '' ? plantChangeLastError() : $message);
        if ($strayOutput !== '') {
            $message .= ' Output: ' . substr(preg_replace('/\s+/', ' ', $strayOutput), 0, 300);
        }
        echo json_encode(array_merge(['ok' => $ok, 'message' => $message], $responseExtra), JSON_UNESCAPED_SLASHES);
    } catch (Throwable $e) {
        $strayOutput = trim((string)ob_get_clean());
        http_response_code(500);
        echo json_encode([
            'ok' => false,
            'message' => 'Plant change save failed: ' . $e->getMessage() . ($strayOutput !== '' ? ' Output: ' . substr(preg_replace('/\s+/', ' ', $strayOutput), 0, 300) : ''),
        ], JSON_UNESCAPED_SLASHES);
    }
    exit;
}

$logs = $clientnumber > 0 ? plantChangeFetchLogs($clientnumber, $fromTs, $toTs) : [];
$rawLogCount = count($logs);
$summary = plantChangeSummarise($logs);
$history = plantChangesReportHistory($clientnumber);
$activeHistory = [];
$historicHistory = [];
foreach ($history as $historyReport) {
    if (!empty($historyReport['removed_at'])) {
        continue;
    }
    if (!empty($historyReport['accepted_at']) || !empty($historyReport['rejected_at'])) {
        $historicHistory[] = $historyReport;
    } else {
        $activeHistory[] = $historyReport;
    }
}
$defaultHistoryMode = 'active';
$clientDetails = $clientnumber > 0 ? plantChangeClientDetails($clientnumber) : [];
$contractAmount = plantChangesClientContractAmount($clientnumber);
$iuPricing = plantChangesClientIuPricing($clientnumber);
$iuBaseRate = (float)$iuPricing['iu_base_rate'];
$iuAdminFee = (float)$iuPricing['iu_admin_fee'];
$plantSummary = plantChangesCurrentPlantSummary($clientnumber);
$currentItemTotal = (int)$plantSummary['total_items'];
$currentUiTotal = (float)$plantSummary['total_ui'];
$currentScheduleValue = round($currentUiTotal * $iuBaseRate, 2);
$midTermDefaultAmount = round((((float)($summary['added_ui'] ?? 0.0)) - ((float)($summary['deleted_ui'] ?? 0.0))) * $iuBaseRate, 2);
$companyVatRate = function_exists('getCompanyDetails') ? (float)getCompanyDetails('vatrate') : 0.0;
$rootUrl = defined('ROOT_URL') ? ROOT_URL : '';
$tenantUrl = defined('TENANT_URL') ? TENANT_URL : ('/' . $tenant);
?>
<style>
.plant-change-summary-line {
    border-left: 4px solid #1266f1;
}

.plant-change-summary-line-add {
    border-left-color: #00b74a;
}

.plant-change-summary-line-delete {
    border-left-color: #f93154;
}

.plant-change-summary-line-duplicate {
    border-left-color: #ffa900;
}

.plant-change-advice-col-title {
    font-size: .85rem;
    font-weight: 700;
}

.plant-change-advice-group {
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    background: #fff;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.plant-change-advice-scroll {
    height: 185px;
    overflow-y: auto;
    padding-right: .25rem;
}

.plant-change-advice-form {
    border-top: 1px solid #e5e7eb;
    margin-top: .75rem;
    padding-top: .75rem;
}

.plant-change-advice-action {
    min-width: 120px;
}

.plant-change-calc {
    background: #f8f9fa;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
}

.plant-change-calc-row {
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    padding: .45rem 0;
    border-bottom: 1px solid #e5e7eb;
}

.plant-change-calc-row:last-child {
    border-bottom: 0;
}

.plant-change-calc-label {
    color: #5f6368;
}

.plant-change-calc-value {
    font-weight: 600;
    text-align: right;
    white-space: nowrap;
}

.plant-change-calc-final {
    font-size: 1.1rem;
}

.plant-change-compact {
    font-size: .875rem;
}

.plant-change-compact .form-label {
    margin-bottom: .25rem;
    font-size: .8rem;
}

.plant-change-compact .form-control,
.plant-change-compact .select-input {
    font-size: .875rem;
}

.plant-change-stat {
    background: #f8f9fa;
    border: 1px solid #e5e7eb;
    border-radius: 6px;
    padding: .65rem .8rem;
}

.plant-change-stat-label {
    color: #6c757d;
    font-size: .78rem;
}

.plant-change-stat-value {
    font-weight: 700;
    font-size: 1rem;
}

.plant-change-history-toggle {
    display: inline-flex;
    background: rgba(255, 255, 255, .12);
    border: 1px solid rgba(255, 255, 255, .25);
    border-radius: 4px;
    overflow: hidden;
}

.plant-change-history-toggle button {
    border: 0;
    background: transparent;
    color: rgba(255, 255, 255, .78);
    font-size: .72rem;
    font-weight: 700;
    line-height: 1;
    padding: .35rem .55rem;
    text-transform: uppercase;
}

.plant-change-history-toggle button.active {
    background: #fff;
    color: #28435c;
}

.plant-change-mode-toggle .active {
    pointer-events: none;
}

.plant-change-endorsement-help {
    align-items: center;
    display: flex !important;
    gap: .75rem;
    justify-content: space-between;
    width: 100%;
}

.plant-change-endorsement-help > .help-icon {
    background: #54b4d3 !important;
    border-color: #54b4d3 !important;
    color: #fff !important;
    flex: 0 0 auto;
    margin: 0 0 0 auto !important;
}

.plant-change-endorsement-help > .help-icon:hover,
.plant-change-endorsement-help > .help-icon:focus {
    background: #3b9bbd !important;
    border-color: #3b9bbd !important;
    color: #fff !important;
}
</style>

<div class="plant-change-module" data-clientnumber="<?= (int)$clientnumber ?>">
    <?php if (!plantChangeDbReady('plant_change_log')) { ?>
    <div class="note note-warning mb-3">
        Plant change tracking is ready in code, but the database tables have not been applied yet. Use the draft SQL in
        the W-drive backup folder before relying on live tracking.
    </div>
    <?php } ?>

    <div class="row g-3 mb-4 align-items-start">
        <div class="col-12 col-xl-4">
            <label class="form-label" for="plantChangeClient">Client</label>
            <select id="plantChangeClient" class="form-select" data-mdb-select-init data-mdb-filter="true"
                data-mdb-container="#plantChangeBox" data-placeholder="Search client">
                <?= plantChangesClientOptions($clientnumber) ?>
            </select>
        </div>
        <div class="col-6 col-xl-3">
            <label class="form-label" for="plantChangeFrom">From</label>
            <div class="date-picker datepicker" data-date-type="open" data-mdb-toggle-button="false"
                data-mdb-format="dd-mm-yyyy">
                <input id="plantChangeFrom" class="form-control" data-mdb-confirmDateOnSelect
                    data-mdb-toggle="datepicker" type="text" value="<?= date('d-m-Y', $fromTs) ?>">
            </div>
        </div>
        <div class="col-6 col-xl-3">
            <label class="form-label" for="plantChangeTo">To</label>
            <div class="date-picker datepicker" data-date-type="open" data-mdb-toggle-button="false"
                data-mdb-format="dd-mm-yyyy">
                <input id="plantChangeTo" class="form-control" data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                    type="text" value="<?= date('d-m-Y', $toTs) ?>">
            </div>
            <?php if ($renewalDate > 0) { ?>
            <small class="text-muted">Defaulted from renewal date <?= date('d-m-Y', $renewalDate) ?></small>
            <?php } ?>
        </div>
        <div class="col-12 col-xl-2">
            <label class="form-label d-none d-xl-block">&nbsp;</label>
            <button type="button" class="btn btn-info w-100" onclick="plantChangeReload()"><i
                    class="fad fa-filter me-2"></i>Load</button>
        </div>
    </div>

    <?php if ($clientnumber > 0) { ?>
    <div class="row g-3 mb-4">
        <div class="col-12 col-xl-8">
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center" data-help-topic="plant_change_advice_lines">
                    <span>Change Advice Lines</span>
                    <span class="badge bg-secondary"><?= (int)$summary['group_count'] ?> changes</span>
                </div>
                <div class="card-body">
                    <?php
                        $addEntries = [];
                        $deleteEntries = [];
                        $summaryEntries = is_array($summary['entries'] ?? null) ? $summary['entries'] : [];
                        if (empty($summaryEntries)) {
                            foreach ($summary['lines'] as $line) {
                                $summaryEntries[] = [
                                    'line' => $line,
                                    'type' => (stripos($line, 'Add -') === 0 || stripos($line, 'Reinstate -') === 0) ? 'add' : 'delete',
                                ];
                            }
                        }
                        foreach ($summaryEntries as $entry) {
                            if (($entry['type'] ?? '') === 'add') {
                                $addEntries[] = $entry;
                            } else {
                                $deleteEntries[] = $entry;
                            }
                        }
                        $duplicateAdded = is_array($summary['duplicate_added'] ?? null) ? $summary['duplicate_added'] : [];
                        ?>
                    <?php if (!empty($duplicateAdded)) { ?>
                    <div class="alert alert-warning mb-3">
                        <strong>Possible duplicate added plant found.</strong><br>
                        These entries share the same description/code and matching serial or plant number. Remove any
                        incorrect log entry below before saving the assessment.
                    </div>
                    <?php } ?>
                    <div id="plantChangeNoAdviceNote"
                        class="note note-info mb-0 <?= empty($summary['lines']) ? '' : 'd-none' ?>">No tracked plant
                        changes were found in this date range.</div>
                    <div class="row g-3 plant-change-compact" id="plantChangeAdviceLineList">
                        <div class="col-12 col-lg-6">
                            <div class="plant-change-advice-group p-3">
                                <div class="plant-change-advice-col-title text-success mb-2">Added / reinstated</div>
                                <div id="plantChangeAdviceAddList" class="plant-change-advice-scroll">
                                    <?php foreach ($addEntries as $entry) {
                                        $line = (string)($entry['line'] ?? '');
                                        $isDuplicate = !empty($entry['duplicate']);
                                        $reasons = !empty($entry['duplicate_reasons']) && is_array($entry['duplicate_reasons']) ? implode(', ', $entry['duplicate_reasons']) : 'matching identifiers';
                                    ?>
                                    <div
                                        class="plant-change-summary-line <?= $isDuplicate ? 'plant-change-summary-line-duplicate' : 'plant-change-summary-line-add' ?> bg-light rounded p-2 mb-2 d-flex justify-content-between gap-2">
                                        <div>
                                            <div><?= plantChangesE($line) ?></div>
                                            <?php if ($isDuplicate) { ?>
                                            <div class="small text-warning fw-semibold">Possible duplicate:
                                                <?= plantChangesE($reasons) ?></div>
                                            <?php } ?>
                                        </div>
                                        <?php if ($isDuplicate && !empty($entry['group'])) { ?>
                                        <button type="button" class="btn btn-outline-danger btn-sm flex-shrink-0"
                                            onclick="plantChangeConfirmRemoveLog(<?= plantChangesE(json_encode((string)$entry['group'])) ?>)">
                                            <i class="fad fa-trash me-1"></i>Remove
                                        </button>
                                        <?php } ?>
                                    </div>
                                    <?php } ?>
                                </div>
                                <div class="plant-change-advice-form">
                                    <div class="fw-semibold mb-2">Manual additions from current plant</div>
                                    <div class="row g-2 align-items-end">
                                        <div class="col-12">
                                            <label class="form-label" for="plantChangeManualAddSelect">Current
                                                plant</label>
                                            <select id="plantChangeManualAddSelect" class="form-select"
                                                data-mdb-select-init data-mdb-filter="true"
                                                data-mdb-container="#plantChangeBox"
                                                data-placeholder="Search current plant">
                                                <?= plantChangesCurrentItemOptions($clientnumber) ?>
                                            </select>
                                        </div>
                                        <div class="col-7">
                                            <label class="form-label" for="plantChangeManualAddDate">Date of
                                                change</label>
                                            <div class="date-picker datepicker" data-date-type="open"
                                                data-mdb-toggle-button="false" data-mdb-format="dd-mm-yyyy">
                                                <input id="plantChangeManualAddDate" class="form-control"
                                                    data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                                    type="text" value="<?= date('d-m-Y') ?>">
                                            </div>
                                        </div>
                                        <div class="col-5 d-flex align-items-end justify-content-end">
                                            <button type="button" class="btn btn-success plant-change-advice-action"
                                                onclick="plantChangeAddCurrentItem()"><i
                                                    class="fad fa-plus me-2"></i>Add</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-12 col-lg-6">
                            <div class="plant-change-advice-group p-3">
                                <div class="plant-change-advice-col-title text-danger mb-2">Deleted / archived / changed
                                </div>
                                <div id="plantChangeAdviceDeleteList" class="plant-change-advice-scroll">
                                    <?php foreach ($deleteEntries as $entry) { ?>
                                    <div
                                        class="plant-change-summary-line plant-change-summary-line-delete bg-light rounded p-2 mb-2">
                                        <?= plantChangesE($entry['line'] ?? '') ?></div>
                                    <?php } ?>
                                </div>
                                <div class="plant-change-advice-form">
                                    <div class="fw-semibold mb-2">Manual removals not in EnRep</div>
                                    <div class="row g-2 align-items-end">
                                        <div class="col-12 col-xl-6">
                                            <label class="form-label" for="plantChangeRemoveDesc">Description</label>
                                            <input id="plantChangeRemoveDesc" class="form-control" type="text">
                                        </div>
                                        <div class="col-6 col-xl-3">
                                            <label class="form-label" for="plantChangeRemovePlant">Plant no.</label>
                                            <input id="plantChangeRemovePlant" class="form-control" type="text">
                                        </div>
                                        <div class="col-6 col-xl-3">
                                            <label class="form-label" for="plantChangeRemoveSerial">Serial no.</label>
                                            <input id="plantChangeRemoveSerial" class="form-control" type="text">
                                        </div>
                                        <div class="col-4 col-xl-2">
                                            <label class="form-label" for="plantChangeRemoveUi">UI</label>
                                            <input id="plantChangeRemoveUi" class="form-control" type="number"
                                                step="0.01">
                                        </div>
                                        <div class="col-6 col-xl-5">
                                            <label class="form-label" for="plantChangeRemoveDate">Date removed</label>
                                            <div class="date-picker datepicker" data-date-type="open"
                                                data-mdb-toggle-button="false" data-mdb-format="dd-mm-yyyy">
                                                <input id="plantChangeRemoveDate" class="form-control"
                                                    data-mdb-confirmDateOnSelect data-mdb-toggle="datepicker"
                                                    type="text" value="<?= date('d-m-Y') ?>">
                                            </div>
                                        </div>
                                        <div class="col-12 col-xl-5 d-flex align-items-end justify-content-end">
                                            <button type="button" class="btn btn-danger plant-change-advice-action"
                                                onclick="plantChangeAddManualRemoval()"><i
                                                    class="fad fa-minus me-2"></i>Remove</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <input id="plantChangeManualEntries" type="hidden" value="[]">

                    <div class="mt-3">
                        <label class="form-label" for="plantChangeManualLines">Additional text-only advice</label>
                        <textarea id="plantChangeManualLines" class="form-control" rows="4"
                            placeholder="Add any extra client advice here"></textarea>
                    </div>
                    <div class="row g-2 mt-3">
                        <div class="col-6 col-lg-4">
                            <div class="plant-change-stat">
                                <div class="plant-change-stat-label" id="plantChangeStatPlantLabel">Plant</div>
                                <div class="plant-change-stat-value" id="plantChangeStatPlantValue">
                                    <?= plantChangesE($clientnumber > 0 ? 'Live schedule' : '-') ?></div>
                            </div>
                        </div>
                        <div class="col-6 col-lg-4">
                            <div class="plant-change-stat">
                                <div class="plant-change-stat-label">Total items</div>
                                <div class="plant-change-stat-value" id="plantChangeStatItemValue">
                                    <?= plantChangesE(number_format($currentItemTotal)) ?></div>
                            </div>
                        </div>
                        <div class="col-6 col-lg-4">
                            <div class="plant-change-stat">
                                <div class="plant-change-stat-label">Total IU</div>
                                <div class="plant-change-stat-value" id="plantChangeStatUiValue">
                                    <?= plantChangesE(number_format($currentUiTotal, 2)) ?></div>
                            </div>
                        </div>
                    </div>
                    <div class="row g-3 mt-1 align-items-stretch">
                        <div class="col-12 col-lg-8">
                            <div class="plant-change-calc p-3">
                                <?php if ($iuBaseRate <= 0 || ($contractAmount <= 0 && $currentScheduleValue <= 0)) { ?>
                                <div class="alert alert-warning mb-3">
                                    <strong>Pricing setup required.</strong><br>
                                    <?php if ($iuBaseRate <= 0) { ?>
                                    Add an IU rate to this client before creating a Renewal or Mid Term document.
                                    <?php } elseif ($contractAmount <= 0 && $currentScheduleValue <= 0) { ?>
                                    Add a client contract fee before creating a Renewal document.
                                    <?php } ?>
                                </div>
                                <?php } ?>
                                <div class="mb-3">
                                    <label class="form-label d-block plant-change-endorsement-help" data-help-topic="plant_change_endorsement_type">Endorsement type</label>
                                    <div class="btn-group plant-change-mode-toggle" role="group">
                                        <button type="button" id="plantChangeModeFull" class="btn btn-sm btn-primary active"
                                            onclick="plantChangeSetMode('full_term')">Renewal</button>
                                        <button type="button" id="plantChangeModeMid" class="btn btn-sm btn-outline-primary"
                                            onclick="plantChangeSetMode('mid_term')">Mid Term</button>
                                    </div>
                                </div>
                                <div class="plant-change-calc-row plant-change-full-term-row">
                                    <span class="plant-change-calc-label">Current contract value</span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeContractDisplay"><?= plantChangesE(number_format($contractAmount, 2, '.', '')) ?></span></span>
                                </div>
                                <div class="plant-change-calc-row plant-change-full-term-row">
                                    <span class="plant-change-calc-label">New schedule value <span
                                            class="text-muted">(current UI x
                                            &pound;<?= plantChangesE(number_format($iuBaseRate, 2)) ?>)</span></span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeNewContractDisplay"><?= plantChangesE(number_format($currentScheduleValue, 2, '.', '')) ?></span></span>
                                </div>
                                <div class="plant-change-calc-row">
                                    <span class="plant-change-calc-label">Added plant value <span
                                            class="text-muted">(advice only)</span></span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeAddedValueDisplay">0.00</span></span>
                                </div>
                                <div class="plant-change-calc-row">
                                    <span class="plant-change-calc-label">Deleted plant value <span
                                            class="text-muted">(advice only)</span></span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeDeletedValueDisplay">0.00</span></span>
                                </div>
                                <div class="plant-change-calc-row plant-change-mid-term-row d-none">
                                    <span class="plant-change-calc-label">Mid term net adjustment</span>
                                    <span class="plant-change-calc-value">
                                        &pound;<input id="plantChangeMidTermAmount" class="form-control form-control-sm plant-change-money d-inline-block text-end"
                                            style="width: 120px;" type="number" step="0.01"
                                            value="<?= plantChangesE(number_format($midTermDefaultAmount, 2, '.', '')) ?>" data-auto="1">
                                    </span>
                                </div>
                                <div class="plant-change-calc-row plant-change-mid-term-row d-none">
                                    <span class="plant-change-calc-label">Mid term admin fee</span>
                                    <span class="plant-change-calc-value">
                                        &pound;<input id="plantChangeMidTermAdminFee" class="form-control form-control-sm plant-change-money d-inline-block text-end"
                                            style="width: 120px;" type="number" step="0.01" value="0.00">
                                    </span>
                                </div>
                                <div class="plant-change-calc-row plant-change-full-term-row">
                                    <span class="plant-change-calc-label">Admin fee</span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeAdminFeeDisplay"><?= plantChangesE(number_format($iuAdminFee, 2, '.', '')) ?></span></span>
                                </div>
                                <div class="plant-change-calc-row">
                                    <span class="plant-change-calc-label">Percentage multiplier</span>
                                    <span class="plant-change-calc-value">
                                        <input id="plantChangeUpliftPercent" class="form-control form-control-sm plant-change-money d-inline-block text-end"
                                            style="width: 90px;" type="number" step="0.01" value="0.00">%
                                    </span>
                                </div>
                                <div class="plant-change-calc-row">
                                    <span class="plant-change-calc-label">Multiplier value</span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeUpliftAmountDisplay">0.00</span></span>
                                </div>
                                <div class="plant-change-calc-row">
                                    <span class="plant-change-calc-label">Subtotal before VAT</span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeNetAmountDisplay">0.00</span></span>
                                </div>
                                <div class="plant-change-calc-row">
                                    <span class="plant-change-calc-label">VAT at
                                        <?= plantChangesE(number_format($companyVatRate, 2)) ?>%</span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeVatAmountDisplay">0.00</span></span>
                                </div>
                                <div class="plant-change-calc-row plant-change-calc-final">
                                    <span class="plant-change-calc-label fw-semibold">Final price inc VAT</span>
                                    <span class="plant-change-calc-value">&pound;<span
                                            id="plantChangeFinalAmountDisplay">0.00</span></span>
                                </div>
                            </div>
                        </div>
                        <div class="col-12 col-lg-4 d-flex align-items-end">
                            <button type="button" id="plantChangeSaveButton" class="btn btn-secondary w-100" onclick="plantChangeSaveReport()"><i
                                    class="fad fa-save me-2"></i><span id="plantChangeSaveLabel">Save Renewal</span></button>
                        </div>
                    </div>
                    <input id="plantChangeContractAmount" type="hidden"
                        value="<?= plantChangesE(number_format($contractAmount, 2, '.', '')) ?>">
                    <input id="plantChangeNewContractAmount" type="hidden"
                        value="<?= plantChangesE(number_format($currentScheduleValue, 2, '.', '')) ?>">
                    <input id="plantChangeAddedValue" type="hidden" value="0.00">
                    <input id="plantChangeDeletedValue" type="hidden" value="0.00">
                    <input id="plantChangeUnitRate" type="hidden"
                        value="<?= plantChangesE(number_format($iuBaseRate, 2, '.', '')) ?>">
                    <input id="plantChangeAdminFee" type="hidden"
                        value="<?= plantChangesE(number_format($iuAdminFee, 2, '.', '')) ?>">
                    <input id="plantChangeVatRate" type="hidden"
                        value="<?= plantChangesE(number_format($companyVatRate, 2, '.', '')) ?>">
                    <input id="plantChangeFinalAmount" type="hidden" value="0.00">
                    <input id="plantChangeUpliftAmount" type="hidden" value="0.00">
                    <input id="plantChangeEndorsementType" type="hidden" value="full_term">
                </div>
            </div>
        </div>

        <div class="col-12 col-xl-4">
            <div class="card" id="plantChangeSavedDocumentsCard">
                <div class="card-header d-flex justify-content-between align-items-center gap-2" data-help-topic="plant_change_saved_endorsements">
                    <span>Saved Documents</span>
                    <div class="plant-change-history-toggle" role="group" aria-label="Plant change history view">
                        <button type="button" id="plantChangeActiveToggle" class="active"
                            onclick="plantChangeToggleHistory('active')">Active <?= count($activeHistory) ?></button>
                        <button type="button" id="plantChangeHistoricToggle"
                            onclick="plantChangeToggleHistory('historic')">Historic <?= count($historicHistory) ?></button>
                    </div>
                </div>
                <div class="card-body">
                    <?php if (empty($activeHistory) && empty($historicHistory)) { ?>
                    <div class="text-muted">No saved documents yet.</div>
                    <?php } else { ?>
                    <?php foreach (['active' => $activeHistory, 'historic' => $historicHistory] as $historyMode => $historyRows) { ?>
                    <div id="plantChangeHistory<?= ucfirst($historyMode) ?>"
                        class="list-group list-group-light plant-change-history-list<?= $historyMode !== $defaultHistoryMode ? ' d-none' : '' ?>">
                        <?php if (empty($historyRows)) { ?>
                        <div class="text-muted small">No <?= $historyMode ?> documents.</div>
                        <?php } ?>
                        <?php foreach ($historyRows as $report) {
                                    $reportId = (int)($report['id'] ?? 0);
                                    $isAccepted = !empty($report['accepted_at']);
                                    $isRejected = !empty($report['rejected_at']);
                                    $endorsementType = function_exists('plantChangeReportEndorsementType') ? plantChangeReportEndorsementType($report) : 'full_term';
                                    $endorsementLabel = $endorsementType === 'mid_term' ? 'Mid Term' : 'Renewal';
                                    $reportPdf = (string)($report['pdf_path'] ?? '');
                                    $pdfSource = trim(dirname(ltrim($reportPdf, '/')), '.');
                                    $pdfName = basename($reportPdf);
                                    $finalPrice = (float)($report['final_amount'] ?? 0);
                                    $emailMessage = '<p>Please find attached your Engineering Inspections Schedule amendment advice.</p>';
                                    $emailMessage .= '<p>The renewal fee is <strong>&pound;' . number_format($finalPrice, 2) . '</strong>.</p>';
                                    $emailPayload = [
                                        'clientNumber' => (string)$clientnumber,
                                        'clientName' => (string)($clientDetails['clientname'] ?? ''),
                                        'primaryEmail' => (string)($clientDetails['email'] ?? ''),
                                        'secondaryEmail' => (string)($clientDetails['pri_contact_email'] ?? ''),
                                        'subject' => 'Engineering Inspections Schedule amendment',
                                        'message' => $emailMessage,
                                        'filePath' => $pdfSource,
                                        'fileName' => $pdfName,
                                        'sentCallbackUrl' => $rootUrl . '/includes/master/plant_changes.php?tenant=' . rawurlencode($tenantUrl) . '&clientnumber=' . $clientnumber . '&report_id=' . $reportId . '&action=mark_sent',
                                    ];
                                    $email64 = base64_encode(json_encode($emailPayload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
                                ?>
                        <div class="list-group-item px-0">
                            <div class="fw-semibold d-flex justify-content-between gap-2 align-items-start">
                                <span><?= date('d-m-Y', (int)$report['range_start']) ?> to
                                    <?= date('d-m-Y', (int)$report['range_end']) ?></span>
                                <span class="text-end">&pound;<?= plantChangesE(number_format($finalPrice, 2)) ?></span>
                            </div>
                            <div class="mt-1">
                                <span class="badge badge-secondary"><?= plantChangesE($endorsementLabel) ?></span>
                            <?php if ($isAccepted) { ?>
                                <span class="badge badge-success">Historic accepted</span>
                            <?php } elseif ($isRejected) { ?>
                                <span class="badge badge-danger">Rejected</span>
                            <?php } elseif (!empty($report['email_sent_at'])) { ?>
                                <span class="badge badge-info">Emailed</span>
                            <?php } ?>
                            </div>
                            <?php if (!empty($report['email_sent_at'])) { ?>
                            <div class="small text-muted">Sent
                                <?= date('d-m-Y H:i', (int)$report['email_sent_at']) ?><?= !empty($report['email_to']) ? ' to ' . plantChangesE($report['email_to']) : '' ?>
                            </div>
                            <?php } ?>
                            <?php if ($isAccepted) { ?>
                            <div class="small text-muted">Accepted <?= date('d-m-Y H:i', (int)$report['accepted_at']) ?>
                                at
                                &pound;<?= plantChangesE(number_format((float)($report['accepted_rate_per_hour'] ?? $report['new_contract_amount'] ?? 0), 2)) ?>
                            </div>
                            <?php } elseif ($isRejected) { ?>
                            <div class="small text-muted">Rejected <?= date('d-m-Y H:i', (int)$report['rejected_at']) ?></div>
                            <?php } ?>
                            <div class="mt-2 d-flex flex-wrap gap-1">
                                <?php if (!empty($report['pdf_path'])) { ?>
                                <a class="btn btn-sm btn-outline-primary"
                                    href="<?= plantChangesE($report['pdf_path']) ?>" target="_blank">
                                    <i class="fad fa-file-pdf me-1"></i>Open PDF
                                </a>
                                <button type="button" class="btn btn-sm btn-outline-info"
                                    onclick="plantChangeEmailReport(this)" data-values="<?= plantChangesE($email64) ?>"
                                    data-report-id="<?= $reportId ?>"
                                    data-href="<?= plantChangesE($rootUrl) ?>/includes/master/mailer.php">
                                    <i class="fad fa-envelope me-1"></i>Email Client
                                </button>
                                <?php } ?>
                                <?php if (!$isAccepted && !$isRejected) { ?>
                                <button type="button" class="btn btn-sm btn-outline-success"
                                    onclick="plantChangeConfirmAccept(<?= $reportId ?>)">
                                    <i class="fad fa-check me-1"></i>Accepted
                                </button>
                                <?php } ?>
                                <?php if (!$isAccepted && !$isRejected && $endorsementType === 'full_term') { ?>
                                <button type="button" class="btn btn-sm btn-outline-warning"
                                    onclick="plantChangeConfirmReject(<?= $reportId ?>)">
                                    <i class="fad fa-ban me-1"></i>Rejected
                                </button>
                                <?php } ?>
                                <?php if (!$isAccepted && !$isRejected) { ?>
                                <button type="button" class="btn btn-sm btn-outline-danger"
                                    onclick="plantChangeConfirmRemove(<?= $reportId ?>)">
                                    <i class="fad fa-trash me-1"></i>Remove
                                </button>
                                <?php } ?>
                            </div>
                        </div>
                        <?php } ?>
                    </div>
                    <?php } ?>
                    <?php } ?>
                </div>
            </div>
        </div>
    </div>
    <?php } ?>
</div>

<script>
window.plantChangeBaseUiDelta = <?= json_encode((float)$summary['ui_delta']) ?>;
window.plantChangeBaseAddedUi = <?= json_encode((float)($summary['added_ui'] ?? 0)) ?>;
window.plantChangeBaseDeletedUi = <?= json_encode((float)($summary['deleted_ui'] ?? 0)) ?>;
window.plantChangeBaseGroupCount = <?= json_encode((int)$summary['group_count']) ?>;
window.plantChangeCurrentItemTotal = <?= json_encode((int)$currentItemTotal) ?>;
window.plantChangeCurrentUiTotal = <?= json_encode((float)$currentUiTotal) ?>;
window.plantChangeManualEntries = [];
window.plantChangeLoadedClient = <?= json_encode((string)(int)$clientnumber) ?>;

function plantChangeCurrentClient() {
    const scopedModule = document.querySelector('#plantChangeBox .plant-change-module') ||
        document.querySelector('.modal.show .plant-change-module');
    if (scopedModule && scopedModule.dataset.clientnumber) {
        return scopedModule.dataset.clientnumber;
    }

    const modules = document.querySelectorAll('.plant-change-module');
    const module = modules.length ? modules[modules.length - 1] : null;
    return module && module.dataset.clientnumber ? module.dataset.clientnumber : (window.plantChangeLoadedClient || '');
}

function plantChangeUrl(action, clientOverride) {
    const client = clientOverride !== undefined ? clientOverride : plantChangeCurrentClient();
    const from = document.getElementById('plantChangeFrom') ? document.getElementById('plantChangeFrom').value : '';
    const to = document.getElementById('plantChangeTo') ? document.getElementById('plantChangeTo').value : '';
    let url = '<?= $rootUrl ?>/includes/master/plant_changes.php?tenant=' + encodeURIComponent(
            '<?= plantChangesE($tenantUrl) ?>') +
        '&clientnumber=' + encodeURIComponent(client) +
        '&from=' + encodeURIComponent(from) +
        '&to=' + encodeURIComponent(to);
    if (action) {
        url += '&action=' + encodeURIComponent(action);
    }
    return url;
}

function plantChangeReload(clientOverride) {
    const url = plantChangeUrl('', clientOverride);
    const modalModule = document.querySelector('.modal.show .plant-change-module');
    if (modalModule && typeof loadContentAndExecuteScripts === 'function') {
        const target = modalModule.parentElement;
        if (target && !target.id) {
            target.id = 'plantChangeModalBody';
        }
        if (target && target.id) {
            loadContentAndExecuteScripts(url, target.id);
            return;
        }
    }
    if (modalModule) {
        fetch(url)
            .then(response => response.text())
            .then(html => {
                modalModule.parentElement.innerHTML = html;
            });
        return;
    }
    window.location.href = 'index.php?t=includes/master&p=plant_changes.php&clientnumber=' +
        encodeURIComponent(clientOverride !== undefined ? clientOverride : plantChangeCurrentClient()) +
        '&from=' + encodeURIComponent(document.getElementById('plantChangeFrom').value) +
        '&to=' + encodeURIComponent(document.getElementById('plantChangeTo').value);
}

function plantChangeScrollToDocuments() {
    const target = document.getElementById('plantChangeSavedDocumentsCard');
    if (target) {
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
}

function plantChangeSetSaveBusy(isBusy) {
    const button = document.getElementById('plantChangeSaveButton');
    const label = document.getElementById('plantChangeSaveLabel');
    if (!button || !label) return;

    button.disabled = isBusy;
    button.dataset.busy = isBusy ? '1' : '0';
    if (isBusy) {
        label.textContent = 'Creating PDF...';
    } else {
        label.textContent = plantChangeEndorsementType() === 'mid_term' ? 'Save Endorsement' : 'Save Renewal';
    }
}

function plantChangePricingGuardMessage() {
    const unitRate = plantChangeNumber('plantChangeUnitRate');
    const baseContract = plantChangeNumber('plantChangeContractAmount');
    const newContract = plantChangeNumber('plantChangeNewContractAmount');
    if (unitRate <= 0) {
        return 'Add an IU rate to the client before creating this document.';
    }
    if (plantChangeEndorsementType() !== 'mid_term' && baseContract <= 0 && newContract <= 0) {
        return 'Add a client contract fee before creating a renewal document.';
    }
    return '';
}

function plantChangeSaveReport() {
    const saveButton = document.getElementById('plantChangeSaveButton');
    if (saveButton && saveButton.dataset.busy === '1') {
        return;
    }

    const pricingMessage = plantChangePricingGuardMessage();
    if (pricingMessage !== '') {
        showResponse('warning', pricingMessage);
        return;
    }

    plantChangeSetSaveBusy(true);
    showResponse('info', 'Creating the document PDF. This can take a few seconds.');
    plantChangeScrollToDocuments();

    const body = new URLSearchParams();
    body.append('tenant', '<?= $tenantUrl ?>');
    body.append('clientnumber', plantChangeCurrentClient());
    body.append('from', document.getElementById('plantChangeFrom').value);
    body.append('to', document.getElementById('plantChangeTo').value);
    body.append('manual_lines', document.getElementById('plantChangeManualLines').value);
    body.append('manual_entries', document.getElementById('plantChangeManualEntries').value);
    body.append('unit_rate', document.getElementById('plantChangeUnitRate').value);
    body.append('base_contract_amount', document.getElementById('plantChangeContractAmount').value);
    body.append('new_contract_amount', document.getElementById('plantChangeNewContractAmount').value);
    body.append('admin_fee', document.getElementById('plantChangeAdminFee').value);
    body.append('vat_rate', document.getElementById('plantChangeVatRate').value);
    body.append('endorsement_type', plantChangeEndorsementType());
    body.append('mid_term_amount', document.getElementById('plantChangeMidTermAmount') ? document.getElementById('plantChangeMidTermAmount').value : '');
    body.append('mid_term_admin_fee', document.getElementById('plantChangeMidTermAdminFee') ? document.getElementById('plantChangeMidTermAdminFee').value : '');
    body.append('uplift_percent', document.getElementById('plantChangeUpliftPercent') ? document.getElementById('plantChangeUpliftPercent').value : '');
    body.append('action', 'save_report');

    fetch('<?= $rootUrl ?>/includes/master/plant_changes.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: body.toString()
        })
        .then(response => response.text().then(text => ({
            ok: response.ok,
            status: response.status,
            statusText: response.statusText,
            url: response.url,
            text
        })))
        .then(payload => {
            const text = payload.text;
            if (!payload.ok && text.trim() === '') {
                throw new Error('HTTP ' + payload.status + ' ' + payload.statusText + ' from ' + payload.url);
            }
            return payload;
        })
        .then(text => {
            let result;
            try {
                result = JSON.parse(text.text);
            } catch (e) {
                const detail = text.text.trim().replace(/\s+/g, ' ').substring(0, 220);
                throw new Error(detail || ('The save endpoint did not return JSON. HTTP ' + text.status + ' ' + text
                    .statusText + ' from ' + text.url));
            }
            return result;
        })
        .then(result => {
            showResponse(result.ok ? 'success' : 'warning', result.message || 'Plant change report updated.');
            if (result.ok) {
                sessionStorage.setItem('plantChangeScrollTarget', 'documents');
                plantChangeReload();
            } else {
                plantChangeSetSaveBusy(false);
            }
        })
        .catch((error) => {
            plantChangeSetSaveBusy(false);
            showResponse('danger', 'Unable to save plant change report history. ' + (error.message || ''));
        });
}

function plantChangeToggleHistory(mode) {
    const activeList = document.getElementById('plantChangeHistoryActive');
    const historicList = document.getElementById('plantChangeHistoryHistoric');
    const activeToggle = document.getElementById('plantChangeActiveToggle');
    const historicToggle = document.getElementById('plantChangeHistoricToggle');
    const showHistoric = mode === 'historic';

    if (activeList) activeList.classList.toggle('d-none', showHistoric);
    if (historicList) historicList.classList.toggle('d-none', !showHistoric);

    if (activeToggle) {
        activeToggle.classList.toggle('active', !showHistoric);
    }
    if (historicToggle) {
        historicToggle.classList.toggle('active', showHistoric);
    }
}

function plantChangeEndorsementType() {
    const input = document.getElementById('plantChangeEndorsementType');
    return input && input.value === 'mid_term' ? 'mid_term' : 'full_term';
}

function plantChangeSetMode(mode) {
    const type = mode === 'mid_term' ? 'mid_term' : 'full_term';
    const hidden = document.getElementById('plantChangeEndorsementType');
    const fullButton = document.getElementById('plantChangeModeFull');
    const midButton = document.getElementById('plantChangeModeMid');
    const saveLabel = document.getElementById('plantChangeSaveLabel');

    if (hidden) hidden.value = type;
    if (fullButton) {
        fullButton.classList.toggle('active', type === 'full_term');
        fullButton.classList.toggle('btn-primary', type === 'full_term');
        fullButton.classList.toggle('btn-outline-primary', type !== 'full_term');
    }
    if (midButton) {
        midButton.classList.toggle('active', type === 'mid_term');
        midButton.classList.toggle('btn-primary', type === 'mid_term');
        midButton.classList.toggle('btn-outline-primary', type !== 'mid_term');
    }

    document.querySelectorAll('.plant-change-full-term-row').forEach((row) => row.classList.toggle('d-none', type === 'mid_term'));
    document.querySelectorAll('.plant-change-mid-term-row').forEach((row) => row.classList.toggle('d-none', type !== 'mid_term'));
    if (saveLabel) saveLabel.textContent = type === 'mid_term' ? 'Save Endorsement' : 'Save Renewal';
    plantChangeRecalculateMoney();
}

function plantChangeActionUrl(action, reportId) {
    return '<?= $rootUrl ?>/includes/master/plant_changes.php?tenant=' + encodeURIComponent(
            '<?= plantChangesE($tenantUrl) ?>') +
        '&clientnumber=' + encodeURIComponent(plantChangeCurrentClient()) +
        '&report_id=' + encodeURIComponent(reportId) +
        '&action=' + encodeURIComponent(action);
}

function plantChangePostAction(action, reportId, extra, onSuccess) {
    showResponse('info', 'Updating saved document. This can take a few seconds.');
    plantChangeScrollToDocuments();

    const body = new URLSearchParams();
    body.append('tenant', '<?= $tenantUrl ?>');
    body.append('clientnumber', plantChangeCurrentClient());
    body.append('report_id', reportId);
    body.append('action', action);
    if (extra) {
        Object.keys(extra).forEach((key) => body.append(key, extra[key]));
    }

    return fetch('<?= $rootUrl ?>/includes/master/plant_changes.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: body.toString()
        })
        .then(response => response.json())
        .then(result => {
            showResponse(result.ok ? 'success' : 'warning', result.message || 'Plant change report updated.');
            if (result.ok && typeof onSuccess === 'function') {
                onSuccess(result);
            }
            if (result.ok) {
                sessionStorage.setItem('plantChangeScrollTarget', 'documents');
                plantChangeReload();
            }
            return result;
        })
        .catch((error) => showResponse('danger', 'Unable to update plant change report. ' + (error.message || '')));
}

function plantChangeOpenMailerPayload(payload64) {
    if (!payload64) {
        return;
    }

    const dest = '<?= plantChangesE($rootUrl) ?>/includes/master/mailer.php?data=' +
        encodeURIComponent(encodeURIComponent(payload64)) + '&mode=popup&tenant=' +
        encodeURIComponent('<?= plantChangesE($tenantUrl) ?>');
    loadModalContent(dest, 'popupBox', 'modal-xl', 1060, 'false', 'Direct Mailer');
}

function plantChangeConfirmRemove(reportId) {
    const dest = plantChangeActionUrl('remove_confirm', reportId);
    loadModalContent(dest, 'plantChangeConfirmBox', 'modal-md', 1080, 'false', 'Remove Plant Change Report',
        'cancelConfirm',
        function() {
            plantChangePostAction('remove_report', reportId, null, function() {
                killModal('plantChangeConfirmBox');
            });
        });
}

function plantChangeConfirmRemoveLog(logGroup) {
    if (!logGroup) {
        showResponse('warning', 'The selected plant change log entry could not be identified.');
        return;
    }

    const dest = plantChangeUrl('remove_log_confirm') + '&log_group=' + encodeURIComponent(logGroup);
    loadModalContent(dest, 'plantChangeConfirmBox', 'modal-md', 1080, 'false', 'Remove Added Plant Log Entry',
        'cancelConfirm',
        function() {
            const body = new URLSearchParams();
            body.append('tenant', '<?= $tenantUrl ?>');
            body.append('clientnumber', plantChangeCurrentClient());
            body.append('from', document.getElementById('plantChangeFrom') ? document.getElementById('plantChangeFrom').value : '');
            body.append('to', document.getElementById('plantChangeTo') ? document.getElementById('plantChangeTo').value : '');
            body.append('log_group', logGroup);
            body.append('action', 'remove_log');

            showResponse('info', 'Removing the selected plant change log entry.');
            fetch('<?= $rootUrl ?>/includes/master/plant_changes.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: body.toString()
                })
                .then(response => response.json())
                .then(result => {
                    showResponse(result.ok ? 'success' : 'warning', result.message || 'Plant change log entry updated.');
                    if (result.ok) {
                        killModal('plantChangeConfirmBox');
                        plantChangeReload();
                    }
                })
                .catch((error) => showResponse('danger', 'Unable to remove plant change log entry. ' + (error.message || '')));
        });
}

function plantChangeConfirmAccept(reportId) {
    const dest = plantChangeActionUrl('accept_confirm', reportId);
    loadModalContent(dest, 'plantChangeConfirmBox', 'modal-md', 1080, 'false', 'Accepted Plant Change Report',
        'cancelConfirm',
        function() {
            const renewalDate = document.getElementById('plantChangeAcceptRenewalDate') ? document.getElementById('plantChangeAcceptRenewalDate').value : '';
            plantChangePostAction('accept_report', reportId, {
                renewal_date: renewalDate
            }, function(result) {
                killModal('plantChangeConfirmBox');
                if (result.mailer_payload64) {
                    setTimeout(function() {
                        plantChangeOpenMailerPayload(result.mailer_payload64);
                    }, 250);
                }
            });
        });
}

function plantChangeConfirmReject(reportId) {
    const dest = plantChangeActionUrl('reject_confirm', reportId);
    loadModalContent(dest, 'plantChangeConfirmBox', 'modal-md', 1080, 'false', 'Reject Plant Change Report',
        'cancelConfirm',
        function() {
            plantChangePostAction('reject_report', reportId, null, function() {
                killModal('plantChangeConfirmBox');
            });
        });
}

function plantChangeEmailReport(button) {
    const string = button.dataset.values;
    if (!string) {
        showResponse('danger', 'Email payload is missing.');
        return;
    }
    plantChangeOpenMailerPayload(string);
}

function plantChangeNumber(id) {
    const el = document.getElementById(id);
    const value = el ? parseFloat(el.value) : 0;
    return Number.isFinite(value) ? value : 0;
}

function plantChangeMoney(id) {
    const value = plantChangeNumber(id);
    return Number.isFinite(value) ? value : 0;
}

function plantChangeEscape(value) {
    return String(value || '').replace(/[&<>"']/g, function(chr) {
        return ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        } [chr]);
    });
}

function plantChangeManualUiDelta() {
    return window.plantChangeManualEntries.reduce((total, entry) => {
        const ui = parseFloat(entry.ui || 0) || 0;
        return total + (entry.type === 'manual_remove' ? -ui : ui);
    }, 0);
}

function plantChangeManualAddedUi() {
    return window.plantChangeManualEntries.reduce((total, entry) => {
        const ui = parseFloat(entry.ui || 0) || 0;
        return total + (entry.type === 'manual_add' ? ui : 0);
    }, 0);
}

function plantChangeManualDeletedUi() {
    return window.plantChangeManualEntries.reduce((total, entry) => {
        const ui = parseFloat(entry.ui || 0) || 0;
        return total + (entry.type === 'manual_remove' ? ui : 0);
    }, 0);
}

function plantChangeAddedUi() {
    return window.plantChangeBaseAddedUi + plantChangeManualAddedUi();
}

function plantChangeDeletedUi() {
    return window.plantChangeBaseDeletedUi + plantChangeManualDeletedUi();
}

function plantChangeFormatCount(value) {
    return Math.round(Number(value) || 0).toLocaleString('en-GB');
}

function plantChangeFormatUi(value) {
    return (Number(value) || 0).toLocaleString('en-GB', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
}

function plantChangeUpdateStats() {
    const plantValue = document.getElementById('plantChangeStatPlantValue');
    const itemValue = document.getElementById('plantChangeStatItemValue');
    const uiValue = document.getElementById('plantChangeStatUiValue');
    const midTerm = plantChangeEndorsementType() === 'mid_term';

    if (plantValue) plantValue.textContent = midTerm ? 'Mid Term changes' : 'Live schedule';
    if (itemValue) itemValue.textContent = midTerm ? plantChangeFormatCount(window.plantChangeBaseGroupCount + window.plantChangeManualEntries.length) : plantChangeFormatCount(window.plantChangeCurrentItemTotal);
    if (uiValue) uiValue.textContent = midTerm ? plantChangeFormatUi(plantChangeAddedUi() - plantChangeDeletedUi()) : plantChangeFormatUi(window.plantChangeCurrentUiTotal);
}

function plantChangeSyncManualEntries() {
    const hidden = document.getElementById('plantChangeManualEntries');
    if (hidden) hidden.value = JSON.stringify(window.plantChangeManualEntries);
}

function plantChangeRenderManualEntries() {
    const addList = document.getElementById('plantChangeAdviceAddList');
    const deleteList = document.getElementById('plantChangeAdviceDeleteList');
    const wrap = document.getElementById('plantChangeAdviceLineList');
    if (!addList || !deleteList || !wrap) return;

    wrap.querySelectorAll('[data-manual-entry="1"]').forEach((entry) => entry.remove());
    const note = document.getElementById('plantChangeNoAdviceNote');

    if (!window.plantChangeManualEntries.length) {
        if (note) note.classList.toggle('d-none', wrap.querySelectorAll('.plant-change-summary-line').length > 0);
        plantChangeSyncManualEntries();
        plantChangeRecalculateMoney();
        return;
    }

    window.plantChangeManualEntries.forEach((entry, index) => {
        const typeLabel = entry.type === 'manual_remove' ? 'Delete' : 'Add';
        const serial = entry.serialnumber ? ` s/n ${entry.serialnumber}` : '';
        const location = entry.locname ? ` (${entry.locname})` : '';
        const details = [
            entry.plantnumber ? `Plant no: ${entry.plantnumber}` : '',
            entry.date ? `Date: ${entry.date}` : '',
            `UI: ${parseFloat(entry.ui || 0).toFixed(2)}`
        ].filter(Boolean).join(' / ');
        const lineClass = entry.type === 'manual_remove' ? 'plant-change-summary-line-delete' :
            'plant-change-summary-line-add';
        const target = entry.type === 'manual_remove' ? deleteList : addList;

        target.insertAdjacentHTML('beforeend', `
            <div class="plant-change-summary-line ${lineClass} bg-light rounded p-2 mb-2 d-flex justify-content-between gap-2" data-manual-entry="1">
                <div>
                    <div>${typeLabel} - ${plantChangeEscape(entry.desc)}${plantChangeEscape(serial)}${plantChangeEscape(location)}</div>
                    <div class="small text-muted">${plantChangeEscape(details)}</div>
                </div>
                <button type="button" class="btn btn-danger btn-sm" onclick="plantChangeRemoveManualEntry(${index})"><i class="fad fa-times"></i></button>
            </div>`);
        target.scrollTop = target.scrollHeight;
    });

    if (note) note.classList.add('d-none');

    plantChangeSyncManualEntries();
    plantChangeRecalculateMoney();
}

function plantChangeRemoveManualEntry(index) {
    window.plantChangeManualEntries.splice(index, 1);
    plantChangeRenderManualEntries();
}

function plantChangeAddCurrentItem() {
    const select = document.getElementById('plantChangeManualAddSelect');
    if (!select || !select.value || !select.options[select.selectedIndex]) {
        showResponse('warning', 'Select a current plant item first.');
        return;
    }

    const option = select.options[select.selectedIndex];
    let entry = {};
    try {
        entry = JSON.parse(option.dataset.entry || '{}');
    } catch (e) {
        entry = {};
    }

    if (!entry.desc) {
        showResponse('warning', 'The selected plant item could not be read.');
        return;
    }

    entry.type = 'manual_add';
    entry.date = document.getElementById('plantChangeManualAddDate').value;
    window.plantChangeManualEntries.push(entry);
    plantChangeRenderManualEntries();
}

function plantChangeAddManualRemoval() {
    const desc = document.getElementById('plantChangeRemoveDesc').value.trim();
    const ui = plantChangeNumber('plantChangeRemoveUi');
    if (!desc || ui <= 0) {
        showResponse('warning', 'Add a removal description and UI value first.');
        return;
    }

    window.plantChangeManualEntries.push({
        type: 'manual_remove',
        desc,
        plantnumber: document.getElementById('plantChangeRemovePlant').value.trim(),
        serialnumber: document.getElementById('plantChangeRemoveSerial').value.trim(),
        ui,
        date: document.getElementById('plantChangeRemoveDate').value
    });

    ['plantChangeRemoveDesc', 'plantChangeRemovePlant', 'plantChangeRemoveSerial', 'plantChangeRemoveUi'].forEach((
        id) => {
        const el = document.getElementById(id);
        if (el) el.value = '';
    });
    plantChangeRenderManualEntries();
}

function plantChangeRecalculateMoney() {
    const unitRate = plantChangeNumber('plantChangeUnitRate');
    const newContractAmount = plantChangeNumber('plantChangeNewContractAmount');
    const addedValue = Math.max(0, plantChangeAddedUi()) * unitRate;
    const deletedValue = Math.max(0, plantChangeDeletedUi()) * unitRate;
    const adminFee = plantChangeNumber('plantChangeAdminFee');
    const vatRate = plantChangeNumber('plantChangeVatRate');
    const midTermInput = document.getElementById('plantChangeMidTermAmount');
    const midTermDefault = ((plantChangeAddedUi() - plantChangeDeletedUi()) * unitRate);
    if (midTermInput && midTermInput.dataset.auto === '1') {
        midTermInput.value = midTermDefault.toFixed(2);
    }
    const midTermAdminFee = plantChangeNumber('plantChangeMidTermAdminFee');
    const baseNet = plantChangeEndorsementType() === 'mid_term' ? plantChangeNumber('plantChangeMidTermAmount') + midTermAdminFee : newContractAmount + adminFee;
    const upliftPercent = Math.max(0, plantChangeNumber('plantChangeUpliftPercent'));
    const upliftAmount = baseNet * (upliftPercent / 100);
    const net = baseNet + upliftAmount;
    const vat = net * (vatRate / 100);
    const final = net + vat;

    if (document.getElementById('plantChangeAddedValue')) document.getElementById('plantChangeAddedValue').value =
        addedValue.toFixed(2);
    if (document.getElementById('plantChangeDeletedValue')) document.getElementById('plantChangeDeletedValue')
        .value = deletedValue.toFixed(2);
    if (document.getElementById('plantChangeFinalAmount')) document.getElementById('plantChangeFinalAmount').value =
        final.toFixed(2);
    if (document.getElementById('plantChangeUpliftAmount')) document.getElementById('plantChangeUpliftAmount').value =
        upliftAmount.toFixed(2);
    if (document.getElementById('plantChangeAddedValueDisplay')) document.getElementById(
        'plantChangeAddedValueDisplay').textContent = addedValue.toFixed(2);
    if (document.getElementById('plantChangeDeletedValueDisplay')) document.getElementById(
        'plantChangeDeletedValueDisplay').textContent = deletedValue.toFixed(2);
    if (document.getElementById('plantChangeUpliftAmountDisplay')) document.getElementById(
        'plantChangeUpliftAmountDisplay').textContent = upliftAmount.toFixed(2);
    if (document.getElementById('plantChangeNetAmountDisplay')) document.getElementById(
        'plantChangeNetAmountDisplay').textContent = net.toFixed(2);
    if (document.getElementById('plantChangeVatAmountDisplay')) document.getElementById(
        'plantChangeVatAmountDisplay').textContent = vat.toFixed(2);
    if (document.getElementById('plantChangeFinalAmountDisplay')) document.getElementById(
        'plantChangeFinalAmountDisplay').textContent = final.toFixed(2);

    plantChangeUpdateStats();
}

document.querySelectorAll('.plant-change-money').forEach((input) => {
    input.addEventListener('input', function() {
        if (this.id === 'plantChangeMidTermAmount') {
            this.dataset.auto = '0';
        }
        plantChangeRecalculateMoney();
    });
});

function plantChangeInitMdbControls() {
    if (typeof mdb === 'undefined') return;

    var modalElement = document.getElementById('plantChangeBox');
    if (!modalElement) {
        modalElement = document;
    }

    var datepickerElements = modalElement.querySelectorAll('.date-picker');
    datepickerElements.forEach((datepickerEl) => {
        const options = {
            confirmDateOnSelect: true,
            format: 'dd-mm-yyyy',
        };
        new mdb.Datepicker(datepickerEl, options);
    });

    if (document.getElementById('plantChangeClient')) {
        const clientSelect = document.getElementById('plantChangeClient');
        new mdb.Select(clientSelect, {
            filter: true,
            container: '#plantChangeBox'
        });
        if (!clientSelect.dataset.plantChangeBound) {
            clientSelect.dataset.plantChangeBound = '1';
            clientSelect.addEventListener('change', function() {
                if (this.value && this.value !== plantChangeCurrentClient()) {
                    plantChangeReload(this.value);
                }
            });
        }
    }

    if (document.getElementById('plantChangeManualAddSelect')) {
        new mdb.Select(document.getElementById('plantChangeManualAddSelect'), {
            filter: true,
            container: '#plantChangeBox'
        });
    }
}

plantChangeInitMdbControls();
plantChangeRecalculateMoney();
if (sessionStorage.getItem('plantChangeScrollTarget') === 'documents') {
    sessionStorage.removeItem('plantChangeScrollTarget');
    setTimeout(plantChangeScrollToDocuments, 150);
}
</script>
