<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/functions.php';
requireAdmin();

$message = '';
$error = '';

$jobId = (int)($_GET['id'] ?? $_POST['job_id'] ?? 0);

if ($jobId <= 0) {
    die('Invalid job ID.');
}

/*
|--------------------------------------------------------------------------
| Payment types that use Qty x Fee
|--------------------------------------------------------------------------
*/
$qtyPaymentTypes = ['meter_toner'];

/*
|--------------------------------------------------------------------------
| Load payment types
|--------------------------------------------------------------------------
*/
$paymentTypeRows = $pdo->query("
    SELECT code, label, fee, is_manual_fee
    FROM payment_types
    WHERE status = 'active'
    ORDER BY sort_order ASC, label ASC
")->fetchAll();

$paymentOptions = [];
foreach ($paymentTypeRows as $row) {
    $paymentOptions[$row['code']] = [
        'label' => $row['label'],
        'fee' => (float)$row['fee'],
        'is_manual_fee' => (int)$row['is_manual_fee']
    ];
}

/*
|--------------------------------------------------------------------------
| Load Machines
|--------------------------------------------------------------------------
*/
$machines = $pdo->query("
    SELECT
        id,
        customer_id,
        unique_machine_no,
        machine_model,
        customer_name,
        location_text,
        telephone,
        main_email
    FROM machines
    WHERE status = 'active'
    ORDER BY unique_machine_no
")->fetchAll();

/*
|--------------------------------------------------------------------------
| Load Staff
|--------------------------------------------------------------------------
*/
$staffList = $pdo->query("
    SELECT id, full_name
    FROM staff
    WHERE status = 'active'
    ORDER BY full_name
")->fetchAll();

/*
|--------------------------------------------------------------------------
| Load Job
|--------------------------------------------------------------------------
*/
$jobStmt = $pdo->prepare("
    SELECT *
    FROM jobs
    WHERE id = ?
    LIMIT 1
");
$jobStmt->execute([$jobId]);
$job = $jobStmt->fetch();

if (!$job) {
    die('Job not found.');
}

/*
|--------------------------------------------------------------------------
| Load assigned staff for this job
|--------------------------------------------------------------------------
*/
$assignedStmt = $pdo->prepare("
    SELECT staff_id
    FROM job_staff_assignments
    WHERE job_id = ?
");
$assignedStmt->execute([$jobId]);
$assignedStaffIds = array_map('intval', array_column($assignedStmt->fetchAll(), 'staff_id'));

/*
|--------------------------------------------------------------------------
| Try to calculate starting qty/manual fee from existing job
|--------------------------------------------------------------------------
*/
$existingQty = 1;
$existingManualFee = '';

if (isset($job['payment_type'], $paymentOptions[$job['payment_type']])) {
    $selectedPayment = $paymentOptions[$job['payment_type']];
    $isManualFeeType = !empty($selectedPayment['is_manual_fee']);
    $isQtyType = in_array($job['payment_type'], $qtyPaymentTypes, true);

    if ($isManualFeeType) {
        $existingManualFee = (string)($job['staff_fee'] ?? '');
    } elseif ($isQtyType) {
        $baseFee = (float)($selectedPayment['fee'] ?? 0);
        $staffFee = (float)($job['staff_fee'] ?? 0);

        if ($baseFee > 0) {
            $existingQty = max(1, (int)round($staffFee / $baseFee));
        }
    }
}

/*
|--------------------------------------------------------------------------
| Handle update
|--------------------------------------------------------------------------
*/
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $machine_id = (int)($_POST['machine_id'] ?? 0);
    $issue_title = trim($_POST['issue_title'] ?? '');
    $issue_description = trim($_POST['issue_description'] ?? '');
    $priority = trim($_POST['priority'] ?? 'medium');
    $payment_type = trim($_POST['payment_type'] ?? '');
    $status = trim($_POST['status'] ?? 'open');

    $qty = (int)($_POST['qty'] ?? 1);
    if ($qty < 1) {
        $qty = 1;
    }

    $manual_fee = isset($_POST['manual_fee']) ? str_replace(',', '', trim($_POST['manual_fee'])) : '';
    $manual_fee = ($manual_fee !== '' && is_numeric($manual_fee)) ? (float)$manual_fee : 0;

    $assigned_staff_ids = $_POST['assigned_staff_ids'] ?? [];
    $assigned_staff_ids = array_map('intval', $assigned_staff_ids);
    $assigned_staff_ids = array_filter($assigned_staff_ids, fn($id) => $id > 0);

    if ($machine_id <= 0) {
        $error = 'Please select a machine.';
    } elseif ($issue_title === '') {
        $error = 'Issue title is required.';
    } elseif (!in_array($priority, ['low', 'medium', 'high', 'urgent'], true)) {
        $error = 'Invalid priority.';
    } elseif (!in_array($status, ['open', 'assigned', 'in_progress', 'closed'], true)) {
        $error = 'Invalid status.';
    } elseif (!array_key_exists($payment_type, $paymentOptions)) {
        $error = 'Invalid payment type.';
    } else {
        $machineStmt = $pdo->prepare("
            SELECT id
            FROM machines
            WHERE id = ? AND status = 'active'
            LIMIT 1
        ");
        $machineStmt->execute([$machine_id]);
        $machineRow = $machineStmt->fetch();

        if (!$machineRow) {
            $error = 'Machine not found.';
        }
    }

    if ($error === '') {
        $selectedPayment = $paymentOptions[$payment_type] ?? null;

        if (!$selectedPayment) {
            $error = 'Invalid payment type.';
        } else {
            $requiresManualFee = !empty($selectedPayment['is_manual_fee']);
            $usesQty = in_array($payment_type, $qtyPaymentTypes, true);

            if ($requiresManualFee) {
                if ($manual_fee <= 0) {
                    $error = 'Please enter a manual fee.';
                } else {
                    $staff_fee = $manual_fee;
                }
            } elseif ($usesQty) {
                if ($qty <= 0) {
                    $error = 'Please enter quantity.';
                } else {
                    $staff_fee = (float)$selectedPayment['fee'] * $qty;
                }
            } else {
                $staff_fee = (float)$selectedPayment['fee'];
            }
        }
    }

    if ($error === '') {
        if (count($assigned_staff_ids) > 0 && $status === 'open') {
            $status = 'assigned';
        }

        try {
            $pdo->beginTransaction();

            $updateStmt = $pdo->prepare("
                UPDATE jobs
                SET machine_id = ?,
                    issue_title = ?,
                    issue_description = ?,
                    priority = ?,
                    payment_type = ?,
                    staff_fee = ?,
                    status = ?
                WHERE id = ?
            ");

            $updateStmt->execute([
                $machine_id,
                $issue_title,
                $issue_description,
                $priority,
                $payment_type,
                $staff_fee,
                $status,
                $jobId
            ]);

            $deleteAssignStmt = $pdo->prepare("
                DELETE FROM job_staff_assignments
                WHERE job_id = ?
            ");
            $deleteAssignStmt->execute([$jobId]);

            if (!empty($assigned_staff_ids)) {
                $assignStmt = $pdo->prepare("
                    INSERT INTO job_staff_assignments (job_id, staff_id)
                    VALUES (?, ?)
                ");

                foreach ($assigned_staff_ids as $staff_id) {
                    $assignStmt->execute([$jobId, $staff_id]);
                }
            }

            if ($status === 'closed') {
                $closeStmt = $pdo->prepare("
                    UPDATE jobs
                    SET closed_at = COALESCE(closed_at, NOW())
                    WHERE id = ?
                ");
                $closeStmt->execute([$jobId]);
            } else {
                $reopenStmt = $pdo->prepare("
                    UPDATE jobs
                    SET closed_at = NULL
                    WHERE id = ?
                ");
                $reopenStmt->execute([$jobId]);
            }

            $pdo->commit();

            $_SESSION['success_message'] = 'Job updated successfully.';
            header('Location: admin-dashboard.php');
            exit;
        } catch (Throwable $e) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $error = 'Error updating job: ' . $e->getMessage();
        }
    }

    $job['machine_id'] = $machine_id;
    $job['issue_title'] = $issue_title;
    $job['issue_description'] = $issue_description;
    $job['priority'] = $priority;
    $job['payment_type'] = $payment_type;
    $job['status'] = $status;
    $job['staff_fee'] = $staff_fee ?? ($job['staff_fee'] ?? 0);

    $assignedStaffIds = $assigned_staff_ids;

    if (isset($payment_type, $paymentOptions[$payment_type])) {
        $selectedPayment = $paymentOptions[$payment_type];
        $isManualFeeType = !empty($selectedPayment['is_manual_fee']);
        $isQtyType = in_array($payment_type, $qtyPaymentTypes, true);

        if ($isManualFeeType) {
            $existingManualFee = (string)$manual_fee;
            $existingQty = 1;
        } elseif ($isQtyType) {
            $existingQty = $qty;
            $existingManualFee = '';
        } else {
            $existingQty = 1;
            $existingManualFee = '';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Job</title>
    <link rel="stylesheet" href="css/style.css?v=1">

    <style>
        * {
            box-sizing: border-box;
        }

        body {
            font-family: Arial, sans-serif;
            background: #f3f6fb;
            margin: 0;
            color: #111827;
        }

        .job-topbar {
            margin: 20px 0;
            padding: 0 16px;
        }

        .job-back-btn {
            display: inline-block;
            background: #2563eb;
            color: #fff;
            padding: 8px 14px;
            border-radius: 8px;
            text-decoration: none;
            font-weight: bold;
        }

        .job-back-btn:hover {
            background: #1d4ed8;
        }

        .job-container {
            max-width: 950px;
            margin: 24px auto;
            padding: 0 16px;
        }

        .job-box {
            background: #fff;
            padding: 24px;
            border-radius: 16px;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.05);
        }

        .job-title {
            margin-top: 0;
            margin-bottom: 16px;
            font-size: 24px;
            font-weight: 700;
        }

        .message {
            background: #dcfce7;
            color: #166534;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .error {
            background: #fee2e2;
            color: #991b1b;
            padding: 12px;
            border-radius: 10px;
            margin-bottom: 14px;
        }

        .job-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 16px;
        }

        .job-full {
            grid-column: 1 / -1;
        }

        .job-form-group label {
            font-weight: bold;
            display: block;
            margin-bottom: 6px;
        }

        .job-form-group input,
        .job-form-group select,
        .job-form-group textarea {
            width: 100%;
            padding: 10px 12px;
            border: 1px solid #d1d5db;
            border-radius: 10px;
            margin-top: 4px;
            font-size: 14px;
            background: #fff;
            color: #111827;
        }

        .job-form-group textarea {
            min-height: 120px;
            resize: vertical;
        }

        .job-form-group input[readonly] {
            background: #f3f4f6;
            cursor: not-allowed;
        }

        .job-submit-btn {
            margin-top: 8px;
            padding: 12px 20px;
            background: #2563eb;
            color: white;
            border: none;
            border-radius: 10px;
            cursor: pointer;
            font-weight: bold;
        }

        .job-submit-btn:hover {
            background: #1d4ed8;
        }

        .machine-info {
            background: #f8fafc;
            padding: 12px;
            border-radius: 10px;
            border: 1px solid #e5e7eb;
            line-height: 1.7;
        }

        .machine-search-wrap {
            position: relative;
        }

        .machine-suggestions {
            border: 1px solid #d1d5db;
            border-radius: 10px;
            background: #fff;
            margin-top: 8px;
            max-height: 260px;
            overflow-y: auto;
            box-shadow: 0 10px 25px rgba(15, 23, 42, 0.08);
        }

        .machine-suggestions.hidden {
            display: none;
        }

        .machine-item {
            padding: 10px 12px;
            border-bottom: 1px solid #f1f5f9;
            cursor: pointer;
        }

        .machine-item:last-child {
            border-bottom: none;
        }

        .machine-item:hover {
            background: #eff6ff;
        }

        .machine-item .machine-no {
            font-weight: bold;
            color: #111827;
        }

        .machine-item .machine-sub {
            font-size: 13px;
            color: #6b7280;
            margin-top: 4px;
        }

        .staff-list label {
            font-weight: normal;
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
        }

        .staff-list input[type="checkbox"] {
            width: auto;
            margin: 0;
        }

        .no-spinner::-webkit-outer-spin-button,
        .no-spinner::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }

        .no-spinner {
            -moz-appearance: textfield;
            appearance: textfield;
        }

        @media (max-width: 768px) {
            .job-grid {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>

    <div class="job-topbar">
        <a href="admin-dashboard.php" class="job-back-btn">← Dashboard</a>
    </div>

    <div class="job-container">
        <div class="job-box">

            <h2 class="job-title">Edit Job: <?= esc(formatJobNo($job['job_no'] ?? '')) ?></h2>

            <?php if ($message): ?>
                <div class="message"><?= esc($message) ?></div>
            <?php endif; ?>

            <?php if ($error): ?>
                <div class="error"><?= esc($error) ?></div>
            <?php endif; ?>

            <form method="POST">
                <input type="hidden" name="job_id" value="<?= (int)$jobId ?>">

                <div class="job-grid">

                    <div class="job-form-group job-full machine-search-wrap">
                        <label>Search Machine *</label>

                        <input
                            type="text"
                            id="machine_search"
                            placeholder="Type machine no or model"
                            autocomplete="off"
                            oninput="filterMachineSuggestions()"
                            onfocus="showMachineSuggestions()"
                            value=""
                        >

                        <input
                            type="hidden"
                            name="machine_id"
                            id="machine_id"
                            value="<?= esc($job['machine_id'] ?? '') ?>"
                            required
                        >

                        <div id="machine_suggestions" class="machine-suggestions hidden"></div>

                        <div class="machine-info" style="margin-top:12px;">
                            Customer: <span id="m_customer">-</span><br>
                            Customer Code: <span id="m_customer_code">-</span><br>
                            Location: <span id="m_location">-</span><br>
                            Phone: <span id="m_phone">-</span><br>
                            Email: <span id="m_email">-</span>
                        </div>
                    </div>

                    <div class="job-form-group">
                        <label>Payment Type *</label>
                        <select name="payment_type" id="payment_type" onchange="toggleFee()" required>
                            <option value="">Select</option>
                            <?php foreach ($paymentOptions as $code => $item): ?>
                                <option value="<?= esc($code) ?>" <?= (($job['payment_type'] ?? '') === $code) ? 'selected' : '' ?>>
                                    <?= esc($item['label']) ?>
                                    <?= !empty($item['is_manual_fee']) ? '' : ' (' . esc(number_format($item['fee'], 0)) . ')' ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="job-form-group">
                        <label>Priority *</label>
                        <select name="priority" required>
                            <option value="medium" <?= (($job['priority'] ?? 'medium') === 'medium') ? 'selected' : '' ?>>Medium</option>
                            <option value="low" <?= (($job['priority'] ?? '') === 'low') ? 'selected' : '' ?>>Low</option>
                            <option value="high" <?= (($job['priority'] ?? '') === 'high') ? 'selected' : '' ?>>High</option>
                            <option value="urgent" <?= (($job['priority'] ?? '') === 'urgent') ? 'selected' : '' ?>>Urgent</option>
                        </select>
                    </div>

                    <div class="job-form-group">
                        <label>Status *</label>
                        <select name="status" required>
                            <option value="open" <?= (($job['status'] ?? '') === 'open') ? 'selected' : '' ?>>Open</option>
                            <option value="assigned" <?= (($job['status'] ?? '') === 'assigned') ? 'selected' : '' ?>>Assigned</option>
                            <option value="in_progress" <?= (($job['status'] ?? '') === 'in_progress') ? 'selected' : '' ?>>In Progress</option>
                            <option value="closed" <?= (($job['status'] ?? '') === 'closed') ? 'selected' : '' ?>>Closed</option>
                        </select>
                    </div>

                    <div class="job-form-group job-full">
                        <label>Issue Title *</label>
                        <input type="text" name="issue_title" value="<?= esc($job['issue_title'] ?? '') ?>" required>
                    </div>

                    <div class="job-form-group job-full">
                        <label>Issue Description</label>
                        <textarea name="issue_description"><?= esc($job['issue_description'] ?? '') ?></textarea>
                    </div>

                    <div class="job-form-group">
                        <label>Qty</label>
                        <input
                            type="number"
                            id="qty"
                            name="qty"
                            min="1"
                            step="1"
                            value="<?= esc($existingQty ?? 1) ?>"
                            class="no-spinner"
                            readonly
                        >
                    </div>

                    <div class="job-form-group">
                        <label>Manual Fee</label>
                        <input
                            type="number"
                            id="manual_fee"
                            name="manual_fee"
                            min="0"
                            step="0.01"
                            value="<?= esc($existingManualFee ?? '') ?>"
                            class="no-spinner"
                            readonly
                        >
                    </div>

                    <div class="job-form-group">
                        <label>Total Amount</label>
                        <input
                            type="text"
                            id="total_amount"
                            value="<?= esc(number_format((float)($job['staff_fee'] ?? 0), 0)) ?>"
                            readonly
                        >
                    </div>

                    <div class="job-form-group job-full">
                        <label>Assign Technicians</label>
                        <div class="staff-list">
                            <?php foreach ($staffList as $s): ?>
                                <label>
                                    <input
                                        type="checkbox"
                                        name="assigned_staff_ids[]"
                                        value="<?= $s['id'] ?>"
                                        <?= in_array((int)$s['id'], $assignedStaffIds, true) ? 'checked' : '' ?>
                                    >
                                    <?= esc($s['full_name']) ?>
                                </label>
                            <?php endforeach; ?>
                        </div>
                    </div>

                    <div class="job-form-group job-full">
                        <button type="submit" class="job-submit-btn">Update Job</button>
                    </div>

                </div>
            </form>
        </div>
    </div>

    <script>
        const machineData = <?= json_encode(array_map(function ($m) {
            return [
                'id' => $m['id'],
                'machine_no' => $m['unique_machine_no'] ?? '',
                'model' => $m['machine_model'] ?? '',
                'customer_id' => $m['customer_id'] ?? '',
                'customer_name' => $m['customer_name'] ?? '',
                'location_text' => $m['location_text'] ?? '',
                'telephone' => $m['telephone'] ?? '',
                'main_email' => $m['main_email'] ?? ''
            ];
        }, $machines), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

        const paymentTypeData = <?= json_encode($paymentOptions, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
        const qtyPaymentTypes = <?= json_encode(array_values($qtyPaymentTypes), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
        const oldMachineId = <?= json_encode($job['machine_id'] ?? '') ?>;
    </script>

    <script>
        function toggleFee() {
            const type = document.getElementById('payment_type').value;
            const fee = document.getElementById('manual_fee');
            const qty = document.getElementById('qty');
            const selected = paymentTypeData[type] || null;

            const isManualFee = selected && Number(selected.is_manual_fee) === 1;
            const isQtyType = qtyPaymentTypes.includes(type);

            if (isManualFee) {
                fee.readOnly = false;
                fee.required = true;
            } else {
                fee.readOnly = true;
                fee.required = false;
                if (!isManualFee) {
                    fee.value = '';
                }
            }

            if (isQtyType && !isManualFee) {
                qty.readOnly = false;
                qty.required = true;
                if (!qty.value || Number(qty.value) < 1) {
                    qty.value = 1;
                }
            } else {
                qty.readOnly = true;
                qty.required = false;
                qty.value = 1;
            }

            updateTotalAmount();
        }

        function updateTotalAmount() {
            const type = document.getElementById('payment_type').value;
            const feeInput = document.getElementById('manual_fee');
            const qtyInput = document.getElementById('qty');
            const totalInput = document.getElementById('total_amount');
            const selected = paymentTypeData[type] || null;

            let total = 0;

            if (selected) {
                const isManualFee = Number(selected.is_manual_fee) === 1;
                const isQtyType = qtyPaymentTypes.includes(type);

                if (isManualFee) {
                    total = parseFloat(feeInput.value || 0);
                } else if (isQtyType) {
                    const baseFee = parseFloat(selected.fee || 0);
                    const qty = parseInt(qtyInput.value || 1, 10);
                    total = baseFee * qty;
                } else {
                    total = parseFloat(selected.fee || 0);
                }
            }

            totalInput.value = Number(total).toLocaleString(undefined, {
                minimumFractionDigits: 0,
                maximumFractionDigits: 2
            });
        }

        function escapeHtml(str) {
            return String(str ?? '')
                .replace(/&/g, '&amp;')
                .replace(/</g, '&lt;')
                .replace(/>/g, '&gt;')
                .replace(/"/g, '&quot;')
                .replace(/'/g, '&#039;');
        }

        function renderMachineSuggestions(list) {
            const box = document.getElementById('machine_suggestions');

            if (!list.length) {
                box.innerHTML = '<div class="machine-item">No machine found</div>';
                box.classList.remove('hidden');
                return;
            }

            box.innerHTML = list.map(machine => `
                <div class="machine-item" onclick="selectMachine(${machine.id})">
                    <div class="machine-no">${escapeHtml(machine.machine_no || '-')} - ${escapeHtml(machine.model || '')}</div>
                    <div class="machine-sub">
                        ${escapeHtml(machine.customer_name || '')}
                        ${machine.location_text ? ' | ' + escapeHtml(machine.location_text) : ''}
                    </div>
                </div>
            `).join('');

            box.classList.remove('hidden');
        }

        function showMachineSuggestions() {
            const keyword = document.getElementById('machine_search').value.trim().toLowerCase();

            const filtered = machineData.filter(machine => {
                if (keyword === '') return true;

                return (machine.machine_no || '').toLowerCase().includes(keyword) ||
                    (machine.model || '').toLowerCase().includes(keyword) ||
                    (machine.customer_name || '').toLowerCase().includes(keyword) ||
                    (machine.location_text || '').toLowerCase().includes(keyword);
            }).slice(0, 30);

            renderMachineSuggestions(filtered);
        }

        function filterMachineSuggestions() {
            document.getElementById('machine_id').value = '';
            clearMachineInfo();
            showMachineSuggestions();
        }

        function selectMachine(machineId) {
            const machine = machineData.find(m => String(m.id) === String(machineId));
            if (!machine) return;

            document.getElementById('machine_id').value = machine.id;
            document.getElementById('machine_search').value =
                `${machine.machine_no || '-'} - ${machine.model || ''}`;

            document.getElementById('m_customer').innerText = machine.customer_name || '-';
            document.getElementById('m_customer_code').innerText = machine.customer_id || '-';
            document.getElementById('m_location').innerText = machine.location_text || '-';
            document.getElementById('m_phone').innerText = machine.telephone || '-';
            document.getElementById('m_email').innerText = machine.main_email || '-';

            document.getElementById('machine_suggestions').classList.add('hidden');
        }

        function clearMachineInfo() {
            document.getElementById('m_customer').innerText = '-';
            document.getElementById('m_customer_code').innerText = '-';
            document.getElementById('m_location').innerText = '-';
            document.getElementById('m_phone').innerText = '-';
            document.getElementById('m_email').innerText = '-';
        }

        function restoreSelectedMachine() {
            if (!oldMachineId) return;
            const machine = machineData.find(m => String(m.id) === String(oldMachineId));
            if (!machine) return;
            selectMachine(machine.id);
        }

        document.addEventListener('click', function (e) {
            const search = document.getElementById('machine_search');
            const box = document.getElementById('machine_suggestions');

            if (!search.contains(e.target) && !box.contains(e.target)) {
                box.classList.add('hidden');
            }
        });

        document.addEventListener('DOMContentLoaded', function () {
            restoreSelectedMachine();
            toggleFee();

            const paymentType = document.getElementById('payment_type');
            const manualFee = document.getElementById('manual_fee');
            const qty = document.getElementById('qty');

            paymentType.addEventListener('change', toggleFee);
            manualFee.addEventListener('input', updateTotalAmount);
            qty.addEventListener('input', updateTotalAmount);
        });
    </script>
</body>
</html>