@php
    $isEdit = !empty($budget);
    $canSave = $isEdit ? ($canEdit ?? false) : auth()->user()->hasPermission('budget', 'create');
    $selectedScope = old('scope_type', $budget->type ?? \App\Models\Budget::TYPE_GENERAL);
    $periodMonths = $periodMonths ?? [];
@endphp
@extends('layouts.app')
@section('title', $isEdit ? 'Edit Budget' : 'New Budget')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('admin.budgets.index') }}">Budgets</a></li>
    <li class="breadcrumb-item active">{{ $isEdit ? 'Edit' : 'New' }}</li>
@endsection

@push('styles')
@include('partials.report-datepicker-assets')
<style>
    .budget-grid-wrap { max-height: 58vh; overflow: auto; border: 1px solid var(--bs-border-color); border-radius: .5rem; }
    .budget-grid { margin-bottom: 0; }
    .budget-grid th, .budget-grid td { white-space: nowrap; font-size: 12.5px; vertical-align: middle; }
    .budget-grid .account-col { min-width: 260px; position: sticky; left: 0; background: #fff; z-index: 2; box-shadow: 1px 0 0 var(--bs-border-color); }
    .budget-grid thead .account-col { z-index: 3; background: #f8f9fa; }
    .budget-grid tfoot .account-col { background: #f8f9fa; font-weight: 600; }
    .budget-grid input.form-control { min-width: 84px; padding: .25rem .4rem; font-size: 12.5px; text-align: right; }
    .budget-grid input.form-control.budget-month-active { border-color: var(--bs-primary); box-shadow: 0 0 0 .15rem rgba(var(--bs-primary-rgb), .2); }
    .budget-scope-panel { background: #f8fafc; border: 1px solid #e5e7eb; border-radius: .5rem; padding: 1rem; }
</style>
@endpush

@section('content')
@if(session('success'))
<div class="alert alert-success alert-dismissible d-flex gap-2 mb-3" style="font-size:13.5px">
    <i class="bi bi-check-circle flex-shrink-0"></i><div>{{ session('success') }}</div>
    <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert"></button>
</div>
@endif
@if($errors->any())
<div class="alert alert-danger alert-dismissible mb-3">
    @foreach($errors->all() as $error)<div>{{ $error }}</div>@endforeach
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
@endif

<div class="card shadow-sm">
    <div class="card-header d-flex flex-wrap justify-content-between align-items-center gap-2">
        <div>
            <h2 class="h5 mb-1">{{ $isEdit ? 'Edit Budget' : 'New Budget' }}</h2>
            <p class="text-muted mb-0" style="font-size:13px">Enter monthly amounts per income/expense account for the selected budget period.</p>
        </div>
        <a href="{{ route('admin.budgets.index') }}" class="btn btn-outline-secondary btn-sm">Close</a>
    </div>
    <div class="card-body">
        <form method="POST" action="{{ $isEdit ? route('admin.budgets.update', $budget) : route('admin.budgets.store') }}" id="budgetForm">
            @csrf
            @if($isEdit) @method('PUT') @endif

            <div class="row g-3 mb-3">
                <div class="col-12">
                    <label class="form-label fw-semibold">Name</label>
                    <input type="text" name="name" class="form-control" required maxlength="150"
                           placeholder="e.g. FY 2026 Operating Budget"
                           value="{{ old('name', $budget->name ?? '') }}" {{ $canSave ? '' : 'readonly' }}>
                </div>
                <div class="col-12">
                    <label class="form-label fw-semibold">Budget Period</label>
                </div>
                @include('partials.report-date-range-fields', [
                    'fromName' => 'period_from',
                    'toName' => 'period_to',
                    'fromLabel' => 'From',
                    'toLabel' => 'To',
                    'dateFrom' => $periodFrom ?? '',
                    'dateTo' => $periodTo ?? '',
                    'colClass' => 'col-md-4',
                    'readOnly' => !$canSave,
                ])
            </div>

            <div class="budget-scope-panel mb-3">
                <label class="form-label fw-semibold d-block mb-2">Budget scope</label>
                <div class="d-flex flex-wrap gap-3 mb-3">
                    @foreach($scopeTypes as $value => $label)
                    <div class="form-check">
                        <input class="form-check-input scope-type-radio" type="radio" name="scope_type" id="scope{{ $value }}"
                               value="{{ $value }}" {{ $selectedScope === $value ? 'checked' : '' }} {{ $canSave ? '' : 'disabled' }}>
                        <label class="form-check-label" for="scope{{ $value }}">{{ $label }}</label>
                    </div>
                    @endforeach
                </div>

                <div id="dimensionScopeField" class="{{ $selectedScope === 'dimension' ? '' : 'd-none' }}">
                    <label class="form-label fw-semibold">Dimension</label>
                    <select name="dimension_value_id" id="dimensionValueId" class="form-select" {{ $canSave ? '' : 'disabled' }}>
                        <option value="">Select dimension value…</option>
                        @foreach($dimensions as $dimension)
                            <optgroup label="{{ $dimension->name }}">
                                @foreach($dimension->values as $value)
                                    <option value="{{ $value->id }}"
                                        {{ (int) old('dimension_value_id', $selectedDimensionValueId ?? 0) === $value->id ? 'selected' : '' }}>
                                        {{ $value->name }}
                                    </option>
                                @endforeach
                            </optgroup>
                        @endforeach
                    </select>
                </div>

                <div id="jobScopeField" class="{{ $selectedScope === 'job' ? '' : 'd-none' }}">
                    <label class="form-label fw-semibold">Customer: Job</label>
                    <select name="customer_id" id="customerJobId" class="form-select" {{ $canSave ? '' : 'disabled' }}>
                        <option value="">Select job…</option>
                        @foreach($jobs as $job)
                            <option value="{{ $job->id }}"
                                {{ (int) old('customer_id', $budget->customer_id ?? 0) === $job->id ? 'selected' : '' }}>
                                {{ $job->code ? $job->code . ' — ' : '' }}{{ $job->name }}
                            </option>
                        @endforeach
                    </select>
                    @if($jobs->isEmpty())
                        <div class="form-text">No customer jobs found. Create jobs under Customers first.</div>
                    @endif
                </div>
            </div>

            @if($canSave)
            <div class="d-flex flex-wrap justify-content-end align-items-center gap-2 mb-2">
                <span class="text-muted me-auto" style="font-size:12.5px" id="copyAcrossHint">Select a month amount, then copy it across the rest of the row.</span>
                <button type="button" class="btn btn-outline-secondary btn-sm" id="copyAcrossBtn">
                    <i class="bi bi-arrow-right-square me-1"></i>Copy Across
                </button>
            </div>
            @endif

            <div class="budget-grid-wrap mb-3">
                <table class="table table-sm table-bordered budget-grid" id="budgetGrid">
                    <thead class="table-light" id="budgetGridHead"></thead>
                    <tbody id="budgetGridBody"></tbody>
                    <tfoot class="table-light" id="budgetGridFoot"></tfoot>
                </table>
            </div>

            <div class="mb-3">
                <label class="form-label fw-semibold">Notes (optional)</label>
                <textarea name="notes" class="form-control" rows="3" placeholder="Optional notes" {{ $canSave ? '' : 'readonly' }}>{{ old('notes', $budget->notes ?? '') }}</textarea>
            </div>

            <div class="d-flex flex-wrap justify-content-end gap-2">
                <a href="{{ route('admin.budgets.index') }}" class="btn btn-outline-secondary">Cancel</a>
                @if($canSave)
                <button type="submit" class="btn btn-primary">Save Budget</button>
                @endif
            </div>
        </form>
        @if($isEdit && ($canEdit ?? false))
        <form method="POST" action="{{ route('admin.budgets.destroy', $budget) }}" class="d-flex justify-content-end mt-2"
              onsubmit="return confirm('Delete this budget?');">
            @csrf @method('DELETE')
            <button type="submit" class="btn btn-outline-danger btn-sm">Delete budget</button>
        </form>
        @endif
    </div>
</div>
@endsection

@push('scripts')
@include('partials.report-datepicker-init')
<script>
(function () {
    const canSave = @json($canSave);
    const budgetAccounts = @json($accounts->values());
    const initialLineAmounts = @json(old('lines', $lineAmounts));
    const initialPeriodMonths = @json($periodMonths);

    const scopeRadios = document.querySelectorAll('.scope-type-radio');
    const dimensionField = document.getElementById('dimensionScopeField');
    const jobField = document.getElementById('jobScopeField');
    const copyAcrossBtn = document.getElementById('copyAcrossBtn');
    const copyAcrossHint = document.getElementById('copyAcrossHint');
    const budgetGrid = document.getElementById('budgetGrid');
    const budgetGridHead = document.getElementById('budgetGridHead');
    const budgetGridBody = document.getElementById('budgetGridBody');
    const budgetGridFoot = document.getElementById('budgetGridFoot');
    const periodFromInput = document.querySelector('input[name="period_from"]');
    const periodToInput = document.querySelector('input[name="period_to"]');

    let activeMonthInput = null;
    let lineAmounts = initialLineAmounts;

    const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];

    function syncScopeFields() {
        const selected = document.querySelector('.scope-type-radio:checked');
        const value = selected ? selected.value : 'account';
        dimensionField?.classList.toggle('d-none', value !== 'dimension');
        jobField?.classList.toggle('d-none', value !== 'job');
    }

    scopeRadios.forEach(function (radio) {
        radio.addEventListener('change', syncScopeFields);
    });
    syncScopeFields();

    function readPeriodValue(input) {
        if (!input) {
            return '';
        }
        return input._flatpickr?.input?.value || input.value || '';
    }

    function buildPeriodMonths(fromStr, toStr) {
        if (!fromStr || !toStr) {
            return [];
        }

        const fromParts = fromStr.split('-').map(Number);
        const toParts = toStr.split('-').map(Number);
        if (fromParts.length !== 3 || toParts.length !== 3) {
            return [];
        }

        let cursor = new Date(fromParts[0], fromParts[1] - 1, 1);
        const end = new Date(toParts[0], toParts[1] - 1, 1);

        if (end < cursor) {
            return [];
        }

        const months = [];
        while (cursor <= end) {
            const key = cursor.getFullYear() + '-' + String(cursor.getMonth() + 1).padStart(2, '0');
            const label = monthNames[cursor.getMonth()] + '-' + String(cursor.getFullYear()).slice(-2);
            months.push({ key: key, label: label });
            cursor = new Date(cursor.getFullYear(), cursor.getMonth() + 1, 1);
        }

        return months;
    }

    function captureCurrentAmounts() {
        const captured = {};

        document.querySelectorAll('[data-account-row]').forEach(function (row) {
            const accountId = row.dataset.accountRow;
            captured[accountId] = captured[accountId] || {};

            row.querySelectorAll('.budget-month-input').forEach(function (input) {
                if (input.value !== '') {
                    captured[accountId][input.dataset.monthKey] = input.value;
                }
            });
        });

        return captured;
    }

    function mergeAmounts(captured) {
        const merged = { ...lineAmounts };

        Object.keys(captured).forEach(function (accountId) {
            merged[accountId] = { ...(merged[accountId] || {}), ...captured[accountId] };
        });

        lineAmounts = merged;
    }

    function formatInputValue(value) {
        const amount = parseFloat(value);
        if (isNaN(amount) || amount <= 0) {
            return '';
        }
        return amount.toFixed(2);
    }

    function renderBudgetGrid(periodMonths) {
        const minWidth = Math.max(420, 260 + (periodMonths.length * 92) + 100);
        budgetGrid.style.minWidth = minWidth + 'px';

        if (!budgetAccounts.length) {
            budgetGridHead.innerHTML = '';
            budgetGridBody.innerHTML = '<tr><td class="text-center text-muted py-4">No income or expense accounts found in the chart of accounts.</td></tr>';
            budgetGridFoot.innerHTML = '';
            return;
        }

        if (!periodMonths.length) {
            budgetGridHead.innerHTML = '<tr><th class="account-col">Account</th><th>Select a valid budget period</th></tr>';
            budgetGridBody.innerHTML = '<tr><td colspan="2" class="text-center text-muted py-4">Choose From and To dates to display budget months.</td></tr>';
            budgetGridFoot.innerHTML = '';
            return;
        }

        let headHtml = '<tr><th class="account-col">Account</th>';
        periodMonths.forEach(function (month) {
            headHtml += '<th class="text-end">' + month.label + '</th>';
        });
        headHtml += '<th class="text-end">Total</th></tr>';
        budgetGridHead.innerHTML = headHtml;

        let bodyHtml = '';
        budgetAccounts.forEach(function (account) {
            const amounts = lineAmounts[account.id] || {};
            bodyHtml += '<tr data-account-row="' + account.id + '">';
            bodyHtml += '<td class="account-col"><div class="fw-semibold">' + escapeHtml(account.label) + '</div>';
            bodyHtml += '<div class="text-muted" style="font-size:11.5px">' + escapeHtml(account.category || '') + '</div></td>';

            periodMonths.forEach(function (month) {
                const value = formatInputValue(amounts[month.key] ?? '');
                bodyHtml += '<td><input type="number" step="0.01" min="0" class="form-control budget-month-input"';
                bodyHtml += ' name="lines[' + account.id + '][' + month.key + ']"';
                bodyHtml += ' data-month-key="' + month.key + '"';
                bodyHtml += ' value="' + value + '"';
                bodyHtml += canSave ? '' : ' readonly';
                bodyHtml += '></td>';
            });

            bodyHtml += '<td class="text-end fw-semibold row-total">0.00</td></tr>';
        });
        budgetGridBody.innerHTML = bodyHtml;

        let footHtml = '<tr><td class="account-col">Total</td>';
        periodMonths.forEach(function (month) {
            footHtml += '<td class="text-end fw-semibold column-total" data-month-total="' + month.key + '">0.00</td>';
        });
        footHtml += '<td class="text-end fw-bold" id="grandTotal">0.00</td></tr>';
        budgetGridFoot.innerHTML = footHtml;

        bindGridInputs();
        recalculateBudgetGrid();
    }

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

    function setActiveMonthInput(input) {
        document.querySelectorAll('.budget-month-input.budget-month-active').forEach(function (el) {
            el.classList.remove('budget-month-active');
        });
        activeMonthInput = input || null;
        if (activeMonthInput) {
            activeMonthInput.classList.add('budget-month-active');
        }
    }

    function parseAmount(input) {
        const value = parseFloat(input.value);
        return isNaN(value) ? 0 : value;
    }

    function formatAmount(value) {
        return value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    }

    function recalculateBudgetGrid() {
        const rows = document.querySelectorAll('[data-account-row]');
        const monthTotals = {};
        let grand = 0;

        rows.forEach(function (row) {
            let rowTotal = 0;
            row.querySelectorAll('.budget-month-input').forEach(function (input) {
                const amount = parseAmount(input);
                rowTotal += amount;
                const month = input.dataset.monthKey;
                monthTotals[month] = (monthTotals[month] || 0) + amount;
            });
            const totalCell = row.querySelector('.row-total');
            if (totalCell) {
                totalCell.textContent = formatAmount(rowTotal);
            }
            grand += rowTotal;
        });

        document.querySelectorAll('[data-month-total]').forEach(function (cell) {
            const month = cell.dataset.monthTotal;
            cell.textContent = formatAmount(monthTotals[month] || 0);
        });

        const grandEl = document.getElementById('grandTotal');
        if (grandEl) {
            grandEl.textContent = formatAmount(grand);
        }
    }

    function bindGridInputs() {
        document.querySelectorAll('.budget-month-input').forEach(function (input) {
            input.addEventListener('input', recalculateBudgetGrid);
            input.addEventListener('focus', function () {
                setActiveMonthInput(input);
            });
        });
    }

    function refreshGridFromPeriod() {
        mergeAmounts(captureCurrentAmounts());
        const periodMonths = buildPeriodMonths(readPeriodValue(periodFromInput), readPeriodValue(periodToInput));
        renderBudgetGrid(periodMonths);
    }

    copyAcrossBtn?.addEventListener('click', function () {
        if (!activeMonthInput) {
            if (copyAcrossHint) {
                copyAcrossHint.textContent = 'Select a month amount first, then click Copy Across.';
            }
            return;
        }

        const row = activeMonthInput.closest('[data-account-row]');
        if (!row) {
            return;
        }

        const inputs = Array.from(row.querySelectorAll('.budget-month-input'));
        const startIndex = inputs.indexOf(activeMonthInput);
        if (startIndex < 0) {
            return;
        }

        const value = activeMonthInput.value;
        for (let i = startIndex + 1; i < inputs.length; i++) {
            inputs[i].value = value;
        }

        recalculateBudgetGrid();
        if (copyAcrossHint) {
            copyAcrossHint.textContent = 'Copied the selected amount to the remaining months in this row.';
        }
    });

    function bindPeriodPickers() {
        [periodFromInput, periodToInput].forEach(function (input) {
            if (!input) {
                return;
            }

            const attach = function () {
                if (!input._flatpickr) {
                    return false;
                }

                input._flatpickr.set('onChange', function () {
                    refreshGridFromPeriod();
                });

                return true;
            };

            if (!attach()) {
                setTimeout(attach, 100);
            }

            input.addEventListener('change', refreshGridFromPeriod);
        });
    }

    renderBudgetGrid(initialPeriodMonths);
    bindPeriodPickers();
})();
</script>
@endpush
