<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/SystemSettings.php';
require_once __DIR__ . '/../../classes/Logger.php';
require_once __DIR__ . '/../../classes/Sales.php';
require_once __DIR__ . '/../../classes/Inventory.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: /IMS/login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();
$systemSettings = new SystemSettings();
$vatPercentage = $systemSettings->vatPercentage();
$vatRate = $systemSettings->vatRate();
$profitPercentageDefault = $systemSettings->profitPercentage();
$auth = new Auth($conn);


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);

$sales = new Sales($conn, $logger);
$inventory = new Inventory($conn, $logger);

if (!$auth->isBranchManager($_SESSION['user_id'])) {
    die("Access denied. Only branch managers can edit sales.");
}

$saleId = $_GET['id'] ?? null;
if (!$saleId || !is_numeric($saleId)) {
    die("Invalid sale ID provided.");
}

$sale = $sales->getSaleById($saleId);
if (!$sale) {
    die("Sale not found.");
}

if (strpos($sale['transaction_id'], '_VERIFIED_') !== false) {
    die("This sale has already been verified and cannot be edited.");
}

$branchId = $sale['branch_id'];
$quantity = count($sale['items']);
$amountPaid = array_sum(array_column($sale['items'], 'total_price'));

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_sale'])) {
    $quantity = (int)($_POST['quantity'] ?? 0);
    $uniqueCodes = $_POST['unique_code'] ?? [];
    $itemNames = $_POST['item_name'] ?? [];
    $prices = $_POST['price'] ?? [];
    $amountPaid = (float)($_POST['amount_paid'] ?? 0);
    $customerName = trim($_POST['customer_name'] ?? '');
    $customerPhone = trim($_POST['customer_phone'] ?? '');
    $soldAt = $_POST['sold_at'] ?? $sale['sold_at'];

    $errors = [];
    if ($quantity <= 0) {
        $errors[] = "Quantity must be greater than zero.";
    }
    if (count($uniqueCodes) != $quantity) {
        $errors[] = "Number of unique codes does not match quantity.";
    }

    $total = array_sum($prices);
    $maxDiscountRate = 0.17;
    $minimumAmount = $total * (1 - $maxDiscountRate);
    if ($amountPaid < $minimumAmount) {
        $errors[] = "Amount paid cannot be less than " . number_format($minimumAmount, 2) . ". Maximum discount allowed is 17%.";
    }
    if ($amountPaid > $total) {
        $errors[] = "Amount paid cannot exceed the total price of " . number_format($total, 2) . ".";
    }


    $itemIds = [];
    for ($i = 0; $i < $quantity; $i++) {
        $item = $inventory->getItemByUniqueCode($uniqueCodes[$i]);
        if (!$item) {
            $errors[] = "Item with unique code {$uniqueCodes[$i]} not found.";
        } elseif ($item['current_location_id'] != $branchId) {
            $errors[] = "Item {$uniqueCodes[$i]} is not available in this branch.";
        } else {
            $itemIds[] = $item['item_id'];
        }
    }

    if (empty($errors)) {
        $data = [
            'quantity' => $quantity,
            'unique_code' => $uniqueCodes,
            'item_id' => $itemIds,
            'price' => $prices,
            'amount_paid' => $amountPaid,
            'customer_name' => $customerName ?: null,
            'customer_phone' => $customerPhone ?: null,
            'sold_at' => $soldAt,
            'sold_by' => $_SESSION['user_id'],
            'branch_id' => $branchId
        ];

        if ($sales->updateSale($saleId, $data)) {
            header("Location: weekly2.php?success=Sale updated successfully");
            exit();
        } else {
            $errorMessage = "Error updating sale. Please try again.";
        }
    }
}
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <style>
        /* ── Google Font (matches create_sale.php) ───── */
        @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800;900&display=swap');

        *, *::before, *::after { box-sizing: border-box; }
        :root {
            --brand:          #4F46E5;
            --brand-dark:     #3730A3;
            --brand-light:    #EEF2FF;
            --brand-ring:     rgba(79,70,229,.18);

            --success:        #059669;
            --success-bg:     #ECFDF5;
            --success-border: #A7F3D0;
            --success-ring:   rgba(5,150,105,.18);
            --danger:         #DC2626;
            --danger-bg:      #FEF2F2;
            --danger-border:  #FECACA;
            --warning:        #D97706;
            --warning-bg:     #FFFBEB;
            --warning-border: #FDE68A;
            --info:           #0284C7;
            --info-bg:        #E0F2FE;

            --n900: #0F172A; --n800: #1E293B; --n700: #334155; --n600: #475569;
            --n500: #64748B; --n400: #94A3B8; --n300: #CBD5E1; --n200: #E2E8F0;
            --n100: #F1F5F9; --n50:  #F8FAFC; --white: #FFFFFF;

            --topbar-h: 58px;
            --r-sm: 6px; --r: 10px; --r-lg: 14px;
            --s1: 0 1px 2px rgba(0,0,0,.05);
            --s2: 0 1px 3px rgba(0,0,0,.07), 0 1px 2px rgba(0,0,0,.04);
            --s3: 0 4px 6px -1px rgba(0,0,0,.07), 0 2px 4px -1px rgba(0,0,0,.04);
        }

        body {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            color: var(--n800);
            background: var(--n100);
            -webkit-font-smoothing: antialiased;
        }

        /* ── Top Bar (matches create_sale.php) ───────── */
        .pos-topbar {
            display: flex; align-items: center; justify-content: space-between;
            background: var(--n900); color: var(--white);
            height: var(--topbar-h);
            position: sticky; top: 0; z-index: 300;
            border-bottom: 3px solid var(--brand);
            padding: 0 20px; margin: 0 -15px 24px;
        }
        .pos-topbar-left { display: flex; align-items: center; gap: 12px; min-width: 0; }
        .pos-topbar .brand-icon {
            width: 32px; height: 32px; border-radius: var(--r-sm);
            background: var(--brand); display: flex; align-items: center;
            justify-content: center; font-size: 14px; color: #fff; flex-shrink: 0;
        }
        .pos-topbar-title {
            font-size: .92rem; font-weight: 700; color: var(--white);
            overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
        }
        .pos-back {
            display: flex; align-items: center; gap: 6px;
            color: var(--n400); text-decoration: none; font-size: .78rem; font-weight: 500;
            padding: 6px 12px; border-radius: var(--r-sm);
            border: 1px solid rgba(255,255,255,.1);
            transition: all .15s; white-space: nowrap; flex-shrink: 0;
        }
        .pos-back:hover { background: rgba(255,255,255,.08); color: var(--white); border-color: rgba(255,255,255,.2); }

        /* ── Page wrap ────────────────────────────────── */
        .form-container { max-width: 900px; margin: 0 auto 60px; padding: 0 5px; }

        /* ── Section card (matches create_sale.php .pos-card) ── */
        .pos-card {
            background: var(--white); border-radius: var(--r);
            padding: 16px 18px; box-shadow: var(--s2);
            border: 1px solid var(--n200);
            margin-bottom: 18px;
        }
        .pos-card-title {
            display: flex; align-items: center; gap: 6px;
            font-size: .7rem; font-weight: 700;
            text-transform: uppercase; letter-spacing: .08em;
            color: var(--n400); margin-bottom: 12px;
        }
        .pos-card-title i { font-size: .8rem; }

        /* ── Item rows ────────────────────────────────── */
        .item-row {
            display: flex; align-items: flex-start; gap: 12px;
            padding: 12px; margin-bottom: 10px;
            border: 1px solid var(--n200); border-radius: var(--r-sm);
            background: var(--n50);
        }
        .item-row:last-child { margin-bottom: 0; }
        .item-row-num {
            flex-shrink: 0; width: 26px; height: 26px; margin-top: 26px;
            background: var(--brand-light); color: var(--brand);
            border-radius: 50%; display: flex; align-items: center;
            justify-content: center; font-size: .72rem; font-weight: 800;
        }
        .item-row-fields { flex: 1; min-width: 0; }
        .field-label {
            font-size: .72rem; font-weight: 700; color: var(--n500);
            text-transform: uppercase; letter-spacing: .04em; margin-bottom: 5px; display: block;
        }

        /* ── Inputs (matches create_sale.php) ────────── */
        .form-control {
            border-color: var(--n300); border-radius: var(--r-sm);
            font-family: 'Inter', system-ui, sans-serif; font-size: .88rem;
            color: var(--n800); transition: border-color .15s, box-shadow .15s;
        }
        .form-control:focus { border-color: var(--brand); box-shadow: 0 0 0 3px var(--brand-ring); outline: none; }
        .unique-code-input {
            font-family: 'JetBrains Mono', 'Fira Code', monospace;
            font-size: .85rem; letter-spacing: .04em;
        }
        .item-name-input {
            background: var(--n100) !important; border-color: var(--n200) !important;
            font-size: .85rem; color: var(--n700);
        }
        .price-input {
            font-weight: 700; font-size: .95rem; text-align: right;
            letter-spacing: -.02em;
        }
        .price-input:focus { border-color: var(--success); box-shadow: 0 0 0 3px var(--success-ring); }

        #generateFields {
            background: var(--brand); border-color: var(--brand);
            font-weight: 600; font-size: .85rem; border-radius: var(--r-sm);
        }
        #generateFields:hover { background: var(--brand-dark); border-color: var(--brand-dark); }

        /* ── Totals card (matches create_sale.php .pos-totals-card) ── */
        .total-section {
            background: linear-gradient(135deg, var(--n900) 0%, var(--n800) 100%);
            border-radius: var(--r-lg); padding: 18px 20px;
            border: 1px solid rgba(255,255,255,.05);
            box-shadow: 0 8px 24px rgba(15,23,42,.18);
            margin-bottom: 18px; position: relative; overflow: hidden;
        }
        .total-section::before {
            content: ''; position: absolute; top: -30px; right: -30px;
            width: 120px; height: 120px; border-radius: 50%;
            background: radial-gradient(circle, rgba(79,70,229,.25) 0%, transparent 70%);
            pointer-events: none;
        }
        .total-section .row { position: relative; }
        .total-section label { color: var(--n400); font-size: .82rem; font-weight: 500; margin: 0; }
        .total-section span { color: var(--white); font-weight: 700; font-variant-numeric: tabular-nums; }
        .total-section .row:last-child label,
        .total-section .row:last-child span { font-size: 1.3rem; font-weight: 900; letter-spacing: -.02em; }
        .total-section .row { padding: 5px 0; }

        /* ── Payment card ─────────────────────────────── */
        .payment-section {
            background: var(--white); border-radius: var(--r);
            padding: 16px 18px; margin-bottom: 18px;
            border: 1.5px solid var(--brand); box-shadow: var(--s2);
        }
        .amount-paid-input { font-size: 1.1em; font-weight: 700; border: 2px solid var(--success) !important; }
        .discount-info { font-size: .82rem; color: var(--success); margin-top: 6px; font-weight: 600; }
        .error-info { font-size: .82rem; color: var(--danger); margin-top: 6px; font-weight: 600; }
        .min-amount-info { font-size: .82rem; color: var(--n500); margin-top: 6px; }
        .vat-recalculated { color: var(--brand) !important; }

        /* ── Customer card ────────────────────────────── */
        .customer-section {
            background: var(--white); border-radius: var(--r);
            padding: 16px 18px; margin-bottom: 18px;
            border: 1px solid var(--n200); box-shadow: var(--s2);
        }
        .customer-section h5 {
            font-size: .7rem; font-weight: 700; text-transform: uppercase;
            letter-spacing: .08em; color: var(--n400); margin-bottom: 14px;
        }

        /* ── Submit button ────────────────────────────── */
        #recordSaleBtn {
            background: linear-gradient(135deg, var(--success), #047857);
            border: none; border-radius: var(--r); font-weight: 700;
            font-size: .95rem; padding: 14px; box-shadow: 0 4px 14px rgba(5,150,105,.3);
            transition: all .15s;
        }
        #recordSaleBtn:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 8px 20px rgba(5,150,105,.4); }
        #recordSaleBtn:disabled { background: var(--n300); box-shadow: none; }
    </style>
    <div class="pos-topbar">
        <div class="pos-topbar-left">
            <div class="brand-icon"><i class="fas fa-receipt"></i></div>
            <span class="pos-topbar-title">Edit Sale #<?php echo htmlspecialchars($sale['transaction_id']); ?></span>
        </div>
        <a href="weekly2.php" class="pos-back"><i class="fas fa-arrow-left"></i> Back to Reports</a>
    </div>

    <div class="form-container">
            <?php if (isset($errorMessage)): ?>
                <div class="alert alert-danger"><?php echo htmlspecialchars($errorMessage); ?></div>
            <?php endif; ?>
            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger">
                    <ul class="mb-0">
                        <?php foreach ($errors as $error): ?>
                            <li><?php echo htmlspecialchars($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form id="saleForm" method="POST" action="">
                <div class="pos-card">
                    <div class="pos-card-title"><i class="fas fa-box"></i> Sale Items</div>
                    <div class="form-group">
                        <label class="field-label" for="quantity">Quantity</label>
                        <input type="number" class="form-control" id="quantity" name="quantity" min="1" value="<?php echo htmlspecialchars($quantity); ?>" required>
                        <small class="form-text text-muted">Enter the number of items sold</small>
                    </div>

                    <button type="button" id="generateFields" class="btn btn-primary mt-3 mb-3">Generate Item Fields</button>

                    <div id="itemsContainer">
                        <?php foreach ($sale['items'] as $index => $item): ?>
                            <div class="item-row">
                                <div class="item-row-num"><?php echo $index + 1; ?></div>
                                <div class="item-row-fields">
                                    <div class="row g-2">
                                        <div class="col-md-4">
                                            <div class="form-group">
                                                <label class="field-label">Unique Code</label>
                                                <input type="text" class="form-control unique-code-input" name="unique_code[]" value="<?php echo htmlspecialchars($item['unique_code']); ?>" required>
                                                <input type="hidden" name="item_id[]" value="<?php echo htmlspecialchars($item['item_id']); ?>">
                                            </div>
                                        </div>
                                        <div class="col-md-5">
                                            <div class="form-group">
                                                <label class="field-label">Item Name</label>
                                                <input type="text" class="form-control item-name-input" name="item_name[]" value="<?php echo htmlspecialchars($item['item_name']); ?>" readonly>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="form-group">
                                                <label class="field-label">Price</label>
                                                <input type="number" step="0.01" class="form-control price-input" name="price[]" value="<?php echo htmlspecialchars($item['unit_price'] * $quantity); ?>" required>
                                                <small class="form-text text-muted">Standard price will auto-fill</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>

                <div class="customer-section">
                    <h5><i class="fas fa-user"></i> Customer Details (Optional)</h5>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="field-label" for="customer_name">Customer Name</label>
                                <input type="text" class="form-control" id="customer_name" name="customer_name" value="<?php echo htmlspecialchars($sale['customer_name'] ?? ''); ?>">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label class="field-label" for="customer_phone">Phone Number</label>
                                <input type="text" class="form-control" id="customer_phone" name="customer_phone" value="<?php echo htmlspecialchars($sale['customer_phone'] ?? ''); ?>">
                                <small class="form-text text-muted">Include country code if applicable</small>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="total-section">
                    <div class="row">
                        <div class="col-md-6"><label>Subtotal</label></div>
                        <div class="col-md-6 text-end"><span id="subtotalPrice">0.00</span></div>
                    </div>
                    <div class="row" id="vatRow">
                        <div class="col-md-6"><label>VAT (<?php echo htmlspecialchars(number_format($vatPercentage, 2)); ?>%)</label></div>
                        <div class="col-md-6 text-end"><span id="vatAmount">0.00</span></div>
                    </div>
                    <div class="row">
                        <div class="col-md-6"><label>Total Price</label></div>
                        <div class="col-md-6 text-end"><span id="totalPrice">0.00</span></div>
                    </div>
                </div>

                <div class="payment-section">
                    <div class="row">
                        <div class="col-md-12">
                            <label class="field-label" for="amount_paid">Amount Paid</label>
                            <input type="number" step="0.01" class="form-control amount-paid-input" id="amount_paid" name="amount_paid" value="<?php echo htmlspecialchars($amountPaid); ?>" required>
                            <div class="min-amount-info" id="minAmountInfo">
                                Minimum amount: <span id="minimumAmount">0.00</span> (Maximum 17% discount allowed)
                            </div>
                            <div class="discount-info" id="discountInfo" style="display: none;">
                                Discount: <span id="discountAmount">0.00</span> (<span id="discountPercentage">0.0</span>%)
                            </div>
                            <div class="error-info" id="errorInfo" style="display: none;"></div>
                            <div class="discount-info" id="vatRecalcInfo" style="display: none;">
                                <small><em>VAT recalculated based on amount paid</em></small>
                            </div>
                        </div>
                    </div>
                </div>

                <button type="submit" name="update_sale" class="btn btn-success btn-lg w-100" id="recordSaleBtn" disabled><i class="fas fa-save"></i> Update Sale</button>
            </form>
    </div>

    <script>
        function cleanLookupJsonText(text) {
            return String(text || '').replace(/^[\uFEFF\xEF\xBB\xBF\s]+/, '');
        }

        function parseLookupJson(text) {
            return JSON.parse(cleanLookupJsonText(text));
        }
        $(document).ready(function() {
            $('#generateFields').click(function() {
                const quantity = parseInt($('#quantity').val());
                if (quantity > 0) {
                    generateItemFields(quantity);
                } else {
                    alert('Please enter a valid quantity');
                }
            });

            $(document).on('blur', '.unique-code-input', function() {
                const uniqueCode = $(this).val();
                const row = $(this).closest('.item-row');

                if (uniqueCode) {
                    $.ajax({
                        url: 'get_item_details.php',
                        type: 'POST',
                        data: { unique_code: uniqueCode },
                        dataType: 'json',
                        dataFilter: cleanLookupJsonText,
                        success: function(response) {
                            if (response.success) {
                                const item = response.item;
                                const originalPrice = parseFloat(item.unit_price);
                                row.find('.item-name-input').val(item.item_name);
                                row.find('.price-input').val(originalPrice.toFixed(2));
                                row.find('.price-input').data('original-price', originalPrice);
                                row.find('input[name="item_id[]"]').val(item.item_id);
                                updateTotalPrice();
                            } else {
                                alert('Error: ' + response.message);
                                row.find('.item-name-input').val('');
                                row.find('.price-input').val('');
                                row.find('input[name="item_id[]"]').val('');
                            }
                        },
                        error: function(xhr) {
                            let errorMessage = 'Error looking up item details';
                            try {
                                const response = parseLookupJson(xhr.responseText);
                                if (response.message) {
                                    errorMessage = response.message;
                                }
                            } catch (e) {
                                errorMessage += ': ' + xhr.responseText;
                            }
                            alert('Error: ' + errorMessage);
                            row.find('.item-name-input').val('');
                            row.find('.price-input').val('');
                            row.find('input[name="item_id[]"]').val('');
                        }
                    });
                }
            });

            $(document).on('change', '.price-input', updateTotalPrice);
            $('#amount_paid').on('input', validateAmountPaid);

            $(document).on('click', '.item-name-input', function(e) {
                e.preventDefault();
                const row = $(this).closest('.item-row');
                const uniqueCode = row.find('.unique-code-input').val();
                if (!uniqueCode) {
                    alert('Please enter a unique code first');
                } else if (!$(this).val()) {
                    row.find('.unique-code-input').trigger('blur');
                }
            });


            updateTotalPrice();
            validateAmountPaid();
        });

        function generateItemFields(quantity) {
            let html = '';
            for (let i = 0; i < quantity; i++) {
                html += `
                <div class="item-row">
                    <div class="item-row-num">${i + 1}</div>
                    <div class="item-row-fields">
                        <div class="row g-2">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label class="field-label">Unique Code</label>
                                    <input type="text" class="form-control unique-code-input" name="unique_code[]" required>
                                    <input type="hidden" name="item_id[]">
                                </div>
                            </div>
                            <div class="col-md-5">
                                <div class="form-group">
                                    <label class="field-label">Item Name</label>
                                    <input type="text" class="form-control item-name-input" name="item_name[]" readonly>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label class="field-label">Price</label>
                                    <input type="number" step="0.01" class="form-control price-input" name="price[]" required>
                                    <small class="form-text text-muted">Standard price will auto-fill</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                `;
            }
            $('#itemsContainer').html(html);
        }

        function updateTotalPrice() {
            let total = 0;
            const vatRate = <?php echo json_encode($vatRate); ?>;
            $('.price-input').each(function() {
                total += parseFloat($(this).val()) || 0;
            });
            const subtotal = total / (1 + vatRate);
            const vatAmount = total - subtotal;
            const maxDiscountRate = 0.17;
            const minimumAmount = total * (1 - maxDiscountRate);
            $('#subtotalPrice').text(subtotal.toFixed(2));
            $('#vatAmount').text(vatAmount.toFixed(2));
            $('#totalPrice').text(total.toFixed(2));
            $('#minimumAmount').text(minimumAmount.toFixed(2));
            $('#amount_paid').attr('max', total.toFixed(2));
            $('#amount_paid').attr('min', minimumAmount.toFixed(2));
            $('#vatAmount').removeClass('vat-recalculated');
            $('#subtotalPrice').removeClass('vat-recalculated');
            $('#vatRecalcInfo').hide();
            validateAmountPaid();
        }

        function validateAmountPaid() {
            const originalTotal = parseFloat($('#totalPrice').text()) || 0;
            const amountPaid = parseFloat($('#amount_paid').val()) || 0;
            const maxDiscountRate = 0.17;
            const minimumAmount = originalTotal * (1 - maxDiscountRate);
            const vatRate = <?php echo json_encode($vatRate); ?>;
            $('#discountInfo').hide();
            $('#errorInfo').hide();
            $('#recordSaleBtn').prop('disabled', true);
            $('#amount_paid').removeClass('is-invalid is-valid');
            if (amountPaid === 0) {
                const originalSubtotal = originalTotal / (1 + vatRate);
                const originalVat = originalTotal - originalSubtotal;
                $('#subtotalPrice').text(originalSubtotal.toFixed(2));
                $('#vatAmount').text(originalVat.toFixed(2));
                $('#vatAmount').removeClass('vat-recalculated');
                $('#subtotalPrice').removeClass('vat-recalculated');
                $('#vatRecalcInfo').hide();
                return;
            }
            if (amountPaid < minimumAmount) {
                $('#errorInfo').text(`Amount too low. Minimum allowed: ${minimumAmount.toFixed(2)}`);
                $('#errorInfo').show();
                $('#amount_paid').addClass('is-invalid');
                const originalSubtotal = originalTotal / (1 + vatRate);
                const originalVat = originalTotal - originalSubtotal;
                $('#subtotalPrice').text(originalSubtotal.toFixed(2));
                $('#vatAmount').text(originalVat.toFixed(2));
                $('#vatAmount').removeClass('vat-recalculated');
                $('#subtotalPrice').removeClass('vat-recalculated');
                $('#vatRecalcInfo').hide();
            } else if (amountPaid > originalTotal) {
                $('#errorInfo').text(`Amount exceeds total price of ${originalTotal.toFixed(2)}`);
                $('#errorInfo').show();
                $('#amount_paid').addClass('is-invalid');
                const originalSubtotal = originalTotal / (1 + vatRate);
                const originalVat = originalTotal - originalSubtotal;
                $('#subtotalPrice').text(originalSubtotal.toFixed(2));
                $('#vatAmount').text(originalVat.toFixed(2));
                $('#vatAmount').removeClass('vat-recalculated');
                $('#subtotalPrice').removeClass('vat-recalculated');
                $('#vatRecalcInfo').hide();
            } else {
                $('#amount_paid').addClass('is-valid');
                $('#recordSaleBtn').prop('disabled', false);
                const newSubtotal = amountPaid / (1 + vatRate);
                const newVat = amountPaid - newSubtotal;
                $('#subtotalPrice').text(newSubtotal.toFixed(2));
                $('#vatAmount').text(newVat.toFixed(2));
                if (amountPaid < originalTotal) {
                    $('#vatAmount').addClass('vat-recalculated');
                    $('#subtotalPrice').addClass('vat-recalculated');
                    $('#vatRecalcInfo').show();
                    const discount = originalTotal - amountPaid;
                    const discountPercentage = (discount / originalTotal) * 100;
                    $('#discountAmount').text(discount.toFixed(2));
                    $('#discountPercentage').text(discountPercentage.toFixed(1));
                    $('#discountInfo').show();
                } else {
                    $('#vatAmount').removeClass('vat-recalculated');
                    $('#subtotalPrice').removeClass('vat-recalculated');
                    $('#vatRecalcInfo').hide();
                }
            }
        }
    </script>
<?php include __DIR__ . '/../../includes/footer.php'; ?>
