<?php if (!empty($all_open_credit)) {
	$this->load->model('credit_note_model');
	$invoice_due = (float) $this->invoice_model->calculate_to('invoice_due', $invoice_info->invoices_id);
	$currency_symbol = client_currency($invoice_info->client_id);
	$form_action = base_url('admin/invoice/apply_invoices_credit/' . $invoice_info->invoices_id);
?>
<?php echo form_open($form_action, array('class' => 'space-y-0', 'data-parsley-validate' => 'true', 'role' => 'form')); ?>
<div class="bg-background text-foreground">
    <div class="space-y-5 px-4 py-4 sm:px-5 sm:py-5" data-credit-apply-root
        data-invoice-due="<?php echo html_escape($invoice_due); ?>"
        data-currency-symbol="<?php echo html_escape($currency_symbol); ?>">
        <?php $first_credit = array_values($all_open_credit)[0]; ?>
        <div class="rounded-[20px] border border-border bg-card p-3.5 shadow-sm sm:p-4">
            <div class="flex flex-wrap items-center gap-3.5">
                <div
                    class="flex h-9 w-9 items-center justify-center rounded-xl bg-primary/10 text-primary sm:h-10 sm:w-10">
                    <i data-lucide="badge-dollar-sign" class="h-4 w-4 sm:h-5 sm:w-5"></i>
                </div>
                <div class="flex flex-wrap items-center gap-2.5 sm:gap-3">
                    <span
                        class="text-[10px] font-semibold uppercase tracking-[0.24em] text-muted-foreground sm:text-[11px]">Source:</span>
                    <span
                        class="inline-flex items-center rounded-lg border border-border bg-background px-2.5 py-1.5 text-[13px] font-semibold tracking-tight text-foreground shadow-sm sm:px-3 sm:py-1.5 sm:text-sm">
                        <?= html_escape($invoice_info->reference_no); ?>
                    </span>
                </div>
            </div>

            <div class="mt-3.5 grid gap-3 sm:gap-4 md:grid-cols-2 xl:grid-cols-4">
                <?php foreach (array(
						array('label' => 'Credit Note', 'value' => !empty($first_credit->reference_no) ? $first_credit->reference_no : ''),
						array('label' => 'Created Date', 'value' => !empty($first_credit->credit_note_date) ? display_date($first_credit->credit_note_date) : ''),
						array('label' => 'Original Amount', 'value' => !empty($first_credit->client_id) ? display_money($this->credit_note_model->credit_note_calculation('total', $first_credit->credit_note_id), client_currency($first_credit->client_id)) : ''),
						array('label' => 'Available to Apply', 'value' => !empty($first_credit->credit_note_id) ? display_money($this->credit_note_model->credit_note_calculation('credit_remaining', $first_credit->credit_note_id), client_currency($first_credit->client_id)) : ''),
					) as $stat) { ?>
                <div>
                    <div class="text-[11px] font-medium text-muted-foreground sm:text-xs"><?php echo $stat['label']; ?>
                    </div>
                    <div class="mt-1 text-sm font-semibold tracking-tight text-foreground sm:text-[15px]">
                        <?php echo $stat['value']; ?></div>
                </div>
                <?php } ?>
            </div>
        </div>

        <?php foreach ($all_open_credit as $open_credit) {
				$credit_remaining = (float) $this->credit_note_model->credit_note_calculation('credit_remaining', $open_credit->credit_note_id);
				$credit_total = (float) $this->credit_note_model->credit_note_calculation('total', $open_credit->credit_note_id);
			?>
        <div class="grid gap-4 lg:grid-cols-2 lg:items-start xl:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]"
            data-credit-row>
            <div class="space-y-4">
                <div>
                    <div class="mb-2.5 flex items-center justify-between gap-3">
                        <h3 class="text-[12px] font-semibold tracking-tight text-foreground sm:text-[13px]">Amount to
                            Apply</h3>
                        <button type="button"
                            class="text-[11px] font-semibold text-primary transition hover:text-primary/80 sm:text-[12px]"
                            data-apply-max data-credit-id="<?= $open_credit->credit_note_id; ?>">
                            Apply Max
                        </button>
                    </div>
                    <div class="rounded-[18px] border border-border bg-card p-2.5 shadow-sm transition focus-within:ring-4 focus-within:ring-primary/20 sm:p-3"
                        data-credit-amount-card>
                        <label class="flex items-center gap-2.5">
                            <span class="text-[13px] font-semibold text-muted-foreground sm:text-sm">$</span>
                            <input type="number" step="0.01" min="0" max="<?php echo html_escape($credit_remaining); ?>"
                                data-parsley-type="number" data-validate-skip="true"
                                data-credit-remaining="<?php echo html_escape($credit_remaining); ?>"
                                name="amount[<?php echo $open_credit->credit_note_id; ?>]"
                                class="amount-credit-field w-full border-0 bg-transparent text-sm font-semibold tracking-tight text-foreground outline-none placeholder:text-muted-foreground focus:ring-0 sm:text-[15px]"
                                value="0" placeholder="0.00" inputmode="decimal" aria-label="Amount to apply">
                        </label>
                        <div class="validate_error mt-2 hidden rounded-lg border border-rose-200 bg-rose-50 px-2.5 py-2 text-[11px] font-medium leading-5 text-rose-700 sm:text-xs"
                            data-credit-error role="alert" aria-live="polite">
                            <div class="flex items-start gap-2">
                                <i data-lucide="alert-circle"
                                    class="mt-0.5 h-3.5 w-3.5 shrink-0 text-rose-600 sm:h-4 sm:w-4"></i>
                                <span data-credit-error-text>Amount exceeds available credit.</span>
                            </div>
                        </div>
                    </div>
                </div>

                <div>
                    <h3 class="mb-2.5 text-[12px] font-semibold tracking-tight text-foreground sm:text-[13px]">Actions
                    </h3>
                    <div class="space-y-2">
                        <label
                            class="flex min-h-[58px] cursor-pointer select-none items-center justify-between gap-3 rounded-lg border border-border bg-card px-3 py-2 shadow-sm transition sm:px-3.5 sm:py-2.5"
                            data-credit-action-row>
                            <span class="flex items-center gap-3">
                                <span
                                    class="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10 text-primary sm:h-8 sm:w-8">
                                    <i data-lucide="wallet" class="h-3.5 w-3.5 sm:h-4 sm:w-4"></i>
                                </span>
                                <span class="text-[11px] font-semibold text-foreground sm:text-[12px]">Record as
                                    Payment</span>
                            </span>
                            <span class="relative inline-flex h-5 w-9 items-center sm:w-10">
                                <input type="checkbox" checked name="added_into_payment" id="use_postmark"
                                    class="peer sr-only" data-credit-toggle="postmark" data-credit-switch="postmark">
                                <span data-credit-switch-track
                                    class="pointer-events-none h-5 w-9 rounded-full bg-slate-300 transition dark:bg-slate-600 sm:w-10"></span>
                                <span data-credit-switch-thumb
                                    class="pointer-events-none absolute left-1 top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition translate-x-0 sm:translate-x-0"></span>
                            </span>
                        </label>

                        <label
                            class="postmark_config flex min-h-[58px] cursor-pointer select-none items-center justify-between gap-3 rounded-lg border border-border bg-card px-3 py-2 shadow-sm transition sm:px-3.5 sm:py-2.5"
                            data-credit-action-row>
                            <span class="flex items-center gap-3">
                                <span
                                    class="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10 text-primary sm:h-8 sm:w-8">
                                    <i data-lucide="mail" class="h-3.5 w-3.5 sm:h-4 sm:w-4"></i>
                                </span>
                                <span class="text-[11px] font-semibold text-foreground sm:text-[12px]">Send Email
                                    Receipt</span>
                            </span>
                            <span class="relative inline-flex h-5 w-9 items-center sm:w-10">
                                <input type="checkbox" checked name="send_thank_you" class="peer sr-only"
                                    data-credit-switch="send_thank_you">
                                <span data-credit-switch-track
                                    class="pointer-events-none h-5 w-9 rounded-full bg-slate-300 transition dark:bg-slate-600 sm:w-10"></span>
                                <span data-credit-switch-thumb
                                    class="pointer-events-none absolute left-1 top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition translate-x-0 sm:translate-x-0"></span>
                            </span>
                        </label>

                        <label
                            class="postmark_config flex min-h-[58px] cursor-pointer select-none items-center justify-between gap-3 rounded-lg border border-border bg-card px-3 py-2 shadow-sm transition sm:px-3.5 sm:py-2.5"
                            data-credit-action-row>
                            <span class="flex items-center gap-3">
                                <span
                                    class="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10 text-primary sm:h-8 sm:w-8">
                                    <i data-lucide="message-square" class="h-3.5 w-3.5 sm:h-4 sm:w-4"></i>
                                </span>
                                <span class="text-[11px] font-semibold text-foreground sm:text-[12px]">Send SMS
                                    Alert</span>
                            </span>
                            <span class="relative inline-flex h-5 w-9 items-center sm:w-10">
                                <input type="checkbox" checked name="send_sms" class="peer sr-only"
                                    data-credit-switch="send_sms">
                                <span data-credit-switch-track
                                    class="pointer-events-none h-5 w-9 rounded-full bg-slate-300 transition dark:bg-slate-600 sm:w-10"></span>
                                <span data-credit-switch-thumb
                                    class="pointer-events-none absolute left-1 top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition translate-x-0 sm:translate-x-0"></span>
                            </span>
                        </label>

                        <label
                            class="postmark_config flex min-h-[58px] cursor-pointer select-none items-center justify-between gap-3 rounded-lg border border-border bg-card px-3 py-2 shadow-sm transition sm:px-3.5 sm:py-2.5"
                            data-credit-action-row>
                            <span class="flex items-center gap-3">
                                <span
                                    class="flex h-7 w-7 items-center justify-center rounded-lg bg-primary/10 text-primary sm:h-8 sm:w-8">
                                    <i data-lucide="check-circle-2" class="h-3.5 w-3.5 sm:h-4 sm:w-4"></i>
                                </span>
                                <span class="text-[11px] font-semibold text-foreground sm:text-[12px]">Update Account
                                    Balance</span>
                            </span>
                            <span class="relative inline-flex h-5 w-9 items-center sm:w-10">
                                <input type="checkbox" checked name="save_into_account" class="peer sr-only"
                                    data-credit-switch="save_into_account">
                                <span data-credit-switch-track
                                    class="pointer-events-none h-5 w-9 rounded-full bg-slate-300 transition dark:bg-slate-600 sm:w-10"></span>
                                <span data-credit-switch-thumb
                                    class="pointer-events-none absolute left-1 top-0.5 h-4 w-4 rounded-full bg-white shadow-sm transition translate-x-0 sm:translate-x-0"></span>
                            </span>
                        </label>
                    </div>
                </div>
            </div>

            <div class="rounded-[20px] border border-border bg-card p-3.5 shadow-sm sm:p-4">
                <div class="h-full">
                    <h3 class="text-[12px] font-semibold tracking-tight text-foreground sm:text-[13px]">Payment Summary
                    </h3>
                    <div class="mt-3 border-t border-border"></div>

                    <div class="mt-3.5 space-y-2.5 sm:mt-4 sm:space-y-3">
                        <div class="flex items-center justify-between gap-4">
                            <span class="text-[11px] text-muted-foreground sm:text-xs">Invoice Due</span>
                            <span
                                class="summary-invoice-due text-sm font-semibold tracking-tight text-foreground sm:text-[15px]"
                                data-summary-invoice-due><?php echo display_money($invoice_due, $currency_symbol); ?></span>
                        </div>

                        <div class="flex items-center justify-between gap-4">
                            <span class="text-[11px] text-muted-foreground sm:text-xs">Amount Applied</span>
                            <span
                                class="amount-credit text-sm font-semibold tracking-tight text-emerald-600 sm:text-[15px]"
                                data-summary-applied>-<?= display_money(0, $currency_symbol); ?></span>
                        </div>

                        <div class="border-t border-dashed border-border"></div>

                        <div class="flex items-center justify-between gap-4">
                            <span class="text-sm font-semibold tracking-tight text-foreground sm:text-[13px]">Remaining
                                Balance</span>
                            <span
                                class="summary-remaining-balance text-base font-semibold tracking-tight text-foreground sm:text-[17px]"
                                data-summary-remaining><?php echo display_money($invoice_due, $currency_symbol); ?></span>
                        </div>

                        <div class="hidden rounded-lg border border-emerald-200 bg-emerald-50 p-2.5 text-emerald-700"
                            data-summary-note>
                            <div class="flex items-start gap-3">
                                <i data-lucide="check-circle-2" class="mt-0.5 h-4 w-4 shrink-0 text-emerald-600"></i>
                                <p
                                    class="text-[11px] font-semibold leading-5 text-emerald-700 sm:text-[12px] sm:leading-6">
                                    Applying this credit will reduce the open invoice balance to
                                    <span
                                        data-summary-note-value><?php echo display_money($invoice_due, $currency_symbol); ?></span>.
                                </p>
                            </div>
                        </div>
                        <div class="hidden rounded-lg border border-rose-200 bg-rose-50 p-2.5 text-rose-700"
                            data-summary-warning>
                            <div class="flex items-start gap-3">
                                <i data-lucide="alert-circle" class="mt-0.5 h-4 w-4 shrink-0 text-rose-600"></i>
                                <p
                                    class="text-[11px] font-semibold leading-5 text-rose-700 sm:text-[12px] sm:leading-6">
                                    Amount exceeds available credit.
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php } ?>

        <div class="flex items-center justify-end gap-3 border-t border-border pt-4">
            <button type="button" data-dismiss="modal"
                class="inline-flex h-10 items-center justify-center rounded-xl border border-border bg-background px-4 text-xs font-semibold text-foreground transition hover:bg-muted sm:px-5 sm:text-sm">
                Cancel
            </button>
            <?php if (count($all_open_credit) > 0) { ?>
            <button type="submit" data-credit-submit
                class="amount_exceed inline-flex h-10 items-center justify-center rounded-xl bg-primary px-4 text-xs font-semibold text-primary-foreground shadow-sm transition hover:bg-primary/90 sm:px-5 sm:text-sm">
                Apply Credit
            </button>
            <?php } ?>
        </div>
    </div>
</div>
<?php echo form_close(); ?>
<?php } ?>

<script type="text/javascript">
(function() {
    if (window.erpInitCreditApplyForms) {
        window.erpInitCreditApplyForms(document);
    } else if (!window.erpCreditApplyDelegatedBound) {
        window.erpCreditApplyDelegatedBound = true;

        function formatMoney(value, symbol) {
            var amount = Number(value) || 0;
            var parts = amount.toFixed(2).split('.');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            return (symbol || '$') + parts.join('.');
        }

        function updateCreditSummary(root) {
            if (!root) return;
            var invoiceDue = Number(root.getAttribute('data-invoice-due') || 0);
            var symbol = root.getAttribute('data-currency-symbol') || '$';
            var totalApplied = 0;
            var hasExceeded = false;
            var hasPositiveAmount = false;
            var inputs = root.querySelectorAll('.amount-credit-field');
            var submitButton = root.querySelector('[data-credit-submit]');

            inputs.forEach(function(input) {
                var remaining = Number(input.getAttribute('data-credit-remaining') || 0);
                var rawValue = Number(input.value || 0);
                var value = Math.min(rawValue, remaining);
                var card = input.closest('[data-credit-amount-card]');
                var row = card ? card.closest('[data-credit-row]') : null;
                var error = card ? card.querySelector('[data-credit-error]') : null;
                var errorText = card ? card.querySelector('[data-credit-error-text]') : null;
                var summaryNote = row ? row.querySelector('[data-summary-note]') : null;
                var summaryWarning = row ? row.querySelector('[data-summary-warning]') : null;
                var exceeded = rawValue > remaining;

                if (exceeded) {
                    hasExceeded = true;
                }
                if (value > 0) {
                    hasPositiveAmount = true;
                }
                totalApplied += value;

                if (card) {
                    card.classList.toggle('border-rose-300', exceeded);
                    card.classList.toggle('ring-4', exceeded);
                    card.classList.toggle('ring-rose-100', exceeded);
                    card.classList.toggle('bg-rose-50/40', exceeded);
                }
                input.classList.toggle('text-rose-700', exceeded);
                input.classList.toggle('placeholder:text-rose-300', exceeded);
                input.setAttribute('aria-invalid', exceeded ? 'true' : 'false');

                if (error) {
                    error.classList.toggle('hidden', !exceeded);
                }
                if (errorText) {
                    errorText.textContent = 'Amount exceeds available credit.';
                }
                if (summaryNote) {
                    summaryNote.classList.toggle('hidden', exceeded || value <= 0);
                }
                if (summaryWarning) {
                    summaryWarning.classList.toggle('hidden', !exceeded);
                }
            });

            var applied = Math.min(totalApplied, invoiceDue);
            var remainingBalance = Math.max(invoiceDue - applied, 0);
            var appliedEl = root.querySelector('[data-summary-applied]');
            var remainingEl = root.querySelector('[data-summary-remaining]');
            var noteValues = root.querySelectorAll('[data-summary-note-value]');
            if (appliedEl) {
                appliedEl.textContent = '-' + formatMoney(applied, symbol);
            }
            if (remainingEl) {
                remainingEl.textContent = formatMoney(remainingBalance, symbol);
            }
            noteValues.forEach(function(noteValue) {
                noteValue.textContent = formatMoney(remainingBalance, symbol);
            });
            if (submitButton) {
                submitButton.disabled = hasExceeded || !hasPositiveAmount;
                submitButton.classList.toggle('opacity-60', hasExceeded || !hasPositiveAmount);
                submitButton.classList.toggle('cursor-not-allowed', hasExceeded || !hasPositiveAmount);
            }
        }

        function updateActionSwitches(scope) {
            var nodes = (scope || document).querySelectorAll('[data-credit-switch]');
            nodes.forEach(function(toggle) {
                var row = toggle.closest('[data-credit-action-row]');
                var shell = toggle.parentElement;
                var track = shell ? shell.querySelector('[data-credit-switch-track]') : null;
                var thumb = shell ? shell.querySelector('[data-credit-switch-thumb]') : null;
                var checked = !!toggle.checked;
                if (row) {
                    row.classList.toggle('border-primary/30', checked);
                    row.classList.toggle('bg-primary/5', checked);
                    row.classList.toggle('ring-1', checked);
                    row.classList.toggle('ring-primary/10', checked);
                    row.classList.toggle('dark:bg-primary/10', checked);
                    row.classList.toggle('dark:border-primary/30', checked);
                    row.classList.toggle('dark:ring-primary/20', checked);
                }
                if (track) {
                    track.classList.toggle('bg-slate-300', !checked);
                    track.classList.toggle('dark:bg-slate-600', !checked);
                    track.classList.toggle('bg-primary/90', checked);
                    track.classList.toggle('dark:bg-primary', checked);
                }
                if (thumb) {
                    thumb.classList.toggle('translate-x-0', !checked);
                    thumb.classList.toggle('sm:translate-x-0', !checked);
                    thumb.classList.toggle('translate-x-4', checked);
                    thumb.classList.toggle('sm:translate-x-5', checked);
                }
            });
        }

        var handleAmountEvent = function(event) {
            if (!event.target.classList || !event.target.classList.contains('amount-credit-field')) return;
            var root = event.target.closest('[data-credit-apply-root]');
            updateCreditSummary(root);
        };

        document.addEventListener('input', handleAmountEvent);
        document.addEventListener('change', handleAmountEvent);
        document.addEventListener('keyup', handleAmountEvent);

        document.addEventListener('click', function(event) {
            var maxButton = event.target.closest('[data-apply-max]');
            if (maxButton) {
                event.preventDefault();
                var root = maxButton.closest('[data-credit-apply-root]');
                if (!root) return;
                var input = root.querySelector('.amount-credit-field');
                if (!input) return;
                input.value = input.getAttribute('data-credit-remaining') || '0';
                input.dispatchEvent(new Event('input', {
                    bubbles: true
                }));
                input.dispatchEvent(new Event('change', {
                    bubbles: true
                }));
            }
        });

        document.addEventListener('click', function(event) {
            var row = event.target.closest('[data-credit-action-row]');
            if (!row) return;
            if (event.target && (event.target.matches('input') || event.target.closest('input'))) return;
            var input = row.querySelector('[data-credit-switch]');
            if (!input) return;
            event.preventDefault();
            input.checked = !input.checked;
            input.dispatchEvent(new Event('change', {
                bubbles: true
            }));
        });

        document.addEventListener('change', function(event) {
            if (event.target && event.target.matches('[data-credit-switch]')) {
                updateActionSwitches(event.target.closest('[data-credit-apply-root]') || document);
            }
            var toggle = event.target.closest('[data-credit-toggle="postmark"]');
            if (!toggle) return;
            document.querySelectorAll('.postmark_config').forEach(function(node) {
                node.classList.toggle('hidden', !toggle.checked);
            });
        });

        var masterToggle = document.querySelector('[data-credit-toggle="postmark"]');
        if (masterToggle) {
            document.querySelectorAll('.postmark_config').forEach(function(node) {
                node.classList.toggle('hidden', !masterToggle.checked);
            });
        }

        document.querySelectorAll('[data-credit-apply-root]').forEach(function(root) {
            root.setAttribute('data-credit-apply-bound', '1');
            updateCreditSummary(root);
        });
        updateActionSwitches(document);
    }
})();
</script>
