@extends('layouts.app')
@section('title', 'Edit Account')

@section('breadcrumb')
    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">Dashboard</a></li>
    <li class="breadcrumb-item"><a href="{{ route('coa.index') }}">Chart of Accounts</a></li>
    <li class="breadcrumb-item active">Edit Account</li>
@endsection

@section('content')
<div class="page-header">
    <div>
        <h1 class="page-title">Edit Account</h1>
        <p class="page-subtitle text-muted">
            @if($account->code)<code>{{ $account->code }}</code> — @endif{{ $account->name }}
        </p>
    </div>
    <a href="{{ route('coa.index') }}" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i>Back
    </a>
</div>

<div class="row justify-content-center">
<div class="col-12 col-lg-9 col-xl-7">
<div class="card">
    <div class="card-header fw-semibold">
        <i class="bi bi-pencil-square me-2 text-primary"></i>Account Details
    </div>
    <div class="card-body">
        @if($account->is_system)
        <div class="alert alert-warning d-flex align-items-start gap-2 mb-4" style="font-size:13.5px">
            <i class="bi bi-shield-exclamation fs-5 flex-shrink-0"></i>
            <div><strong>System Account</strong> — This account was created automatically. Some fields are locked to protect system integrity.</div>
        </div>
        @endif

        <form method="POST" action="{{ route('coa.update', $account) }}" id="coaForm">
        @csrf @method('PUT')
        @if($account->is_system)
            <input type="hidden" name="account_section" value="{{ $accountSection }}">
            <input type="hidden" name="type" value="{{ $account->type }}">
            <input type="hidden" name="sub_type" value="{{ $account->sub_type }}">
        @else
            <input type="hidden" name="account_section" id="accountSection" value="{{ old('account_section', $accountSection) }}">
            <input type="hidden" name="type" id="typeHidden" value="{{ old('type', $account->type) }}">
            <input type="hidden" name="sub_type" id="subTypeHidden" value="{{ old('sub_type', $account->sub_type) }}">
        @endif
        <div class="row g-3">

            <div class="col-12">
                <label class="form-label fw-semibold">Account Name <span class="text-danger">*</span></label>
                <input type="text" name="name" required
                       class="form-control form-control-lg @error('name') is-invalid @enderror"
                       value="{{ old('name', $account->name) }}">
                @error('name')<div class="invalid-feedback">{{ $message }}</div>@enderror
            </div>

            <div class="col-12 col-sm-5">
                <label class="form-label fw-semibold">Account Code</label>
                <input type="text" name="code"
                       class="form-control @error('code') is-invalid @enderror"
                       value="{{ old('code', $account->code) }}"
                       {{ $account->is_system ? 'readonly' : '' }}>
                @error('code')<div class="invalid-feedback">{{ $message }}</div>@enderror
            </div>

            <div class="col-12 col-sm-7">
                <label class="form-label fw-semibold">Status</label>
                <div class="d-flex gap-3 mt-2">
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="is_active" value="1"
                               id="activeYes" {{ old('is_active', $account->is_active) ? 'checked':'' }}>
                        <label class="form-check-label" for="activeYes">Active</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="radio" name="is_active" value="0"
                               id="activeNo" {{ !old('is_active', $account->is_active) ? 'checked':'' }}>
                        <label class="form-check-label" for="activeNo">Inactive</label>
                    </div>
                </div>
            </div>

            <div class="col-12">
                <label class="form-label fw-semibold">Account Type <span class="text-danger">*</span></label>
                <select id="sectionSelect" required class="form-select @error('account_section') is-invalid @enderror"
                        {{ $account->is_system ? 'disabled' : '' }}>
                    <option value="">— Select Account Type —</option>
                    <option value="bank">Bank</option>
                    <option value="accounts_receivable">Accounts Receivable (A/R)</option>
                    <option value="other_current_assets">Other Current Assets</option>
                    <option value="fixed_assets">Fixed Assets</option>
                    <option value="other_assets">Other Assets</option>
                    <option value="accounts_payable">Accounts Payable (A/P)</option>
                    <option value="credit_card">Credit Card</option>
                    <option value="other_current_liabilities">Other Current Liabilities</option>
                    <option value="long_term_liabilities">Long-Term Liabilities</option>
                    <option value="equity">Equity</option>
                    <option value="income">Income</option>
                    <option value="other_income">Other Income</option>
                    <option value="cost_of_goods_sold">Cost of Goods Sold</option>
                    <option value="expenses">Expenses</option>
                    <option value="other_expense">Other Expense</option>
                </select>
                @error('account_section')<div class="invalid-feedback d-block">{{ $message }}</div>@enderror
            </div>

            <div class="col-12">
                <label class="form-label fw-semibold">Parent Account</label>
                <select name="parent_id" id="parentSelect" class="form-select select2"
                        {{ $account->is_system ? 'disabled' : '' }}>
                    <option value="">— No Parent (Top Level) —</option>
                    @foreach($parents as $parent)
                        <option value="{{ $parent->id }}" data-type="{{ $parent->type }}"
                            {{ old('parent_id',$account->parent_id)==$parent->id ? 'selected':'' }}>
                            {{ str_repeat('›  ', $parent->depth) }}{{ $parent->code ? "[{$parent->code}] " : "" }}{{ $parent->name }}
                        </option>
                    @endforeach
                </select>
            </div>

            @if(!$account->is_system)
            <div class="col-12" id="bankCashRow" style="display:none">
                <label class="form-label fw-semibold d-block mb-2">Account Flags</label>
                <div class="row g-2">
                    <div class="col-12 col-sm-6">
                        <div class="form-check p-3 rounded-2 border" style="background:#f8f9fa">
                            <input class="form-check-input" type="checkbox" name="is_bank" value="1"
                                   id="is_bank" {{ old('is_bank', $account->is_bank) ? 'checked':'' }}>
                            <label class="form-check-label ms-1" for="is_bank">
                                <i class="bi bi-bank text-info me-1"></i><strong>Bank Account</strong>
                                <div class="text-muted" style="font-size:11.5px;margin-top:2px">Available for bank reconciliation</div>
                            </label>
                        </div>
                    </div>
                    <div class="col-12 col-sm-6">
                        <div class="form-check p-3 rounded-2 border" style="background:#f8f9fa">
                            <input class="form-check-input" type="checkbox" name="is_cash" value="1"
                                   id="is_cash" {{ old('is_cash', $account->is_cash) ? 'checked':'' }}>
                            <label class="form-check-label ms-1" for="is_cash">
                                <i class="bi bi-cash text-success me-1"></i><strong>Cash Account</strong>
                                <div class="text-muted" style="font-size:11.5px;margin-top:2px">Cash payment and receipt</div>
                            </label>
                        </div>
                    </div>
                </div>
            </div>
            @endif

            <div class="col-12">
                <label class="form-label fw-semibold">Description</label>
                <textarea name="description" class="form-control" rows="2">{{ old('description', $account->description) }}</textarea>
            </div>

            <div class="col-12 d-flex gap-2 justify-content-end pt-2">
                <a href="{{ route('coa.index') }}" class="btn btn-outline-secondary px-4">Cancel</a>
                <button type="submit" class="btn btn-primary px-4" id="saveBtn">
                    <i class="bi bi-check-circle me-1"></i>Save Changes
                </button>
            </div>
        </div>
        </form>
    </div>
</div>
</div>
</div>
@endsection

@push('scripts')
<script>
const sectionMeta = @json($sectionMeta);
const initialSection = @json(old('account_section', $accountSection));

function syncBankCashRow(sectionKey) {
    const row = document.getElementById('bankCashRow');
    const isBankSection = sectionKey === 'bank';
    if (row) row.style.display = isBankSection ? '' : 'none';
    if (!isBankSection) {
        const bank = document.getElementById('is_bank');
        const cash = document.getElementById('is_cash');
        if (bank) bank.checked = false;
        if (cash) cash.checked = false;
    }
}

function applySection(key) {
    const section = sectionMeta[key] || null;
    const sectionInput = document.getElementById('accountSection');
    const typeInput = document.getElementById('typeHidden');
    const subTypeInput = document.getElementById('subTypeHidden');
    if (sectionInput) sectionInput.value = key;
    if (typeInput) typeInput.value = section?.type || '';
    if (subTypeInput) subTypeInput.value = section?.sub_type || '';
    filterParents(section?.type || '');
    syncBankCashRow(key);
}

function filterParents(type) {
    const parentSelect = document.getElementById('parentSelect');
    if (!parentSelect) return;
    Array.from(parentSelect.options).forEach(option => {
        if (!option.value) return;
        const matches = !type || option.dataset.type === type;
        option.hidden = !matches;
        option.disabled = !matches;
    });
    if (parentSelect.value) {
        const selected = parentSelect.options[parentSelect.selectedIndex];
        if (selected?.disabled) parentSelect.value = '';
    }
}

(function () {
    const bankInput = document.getElementById('is_bank');
    const cashInput = document.getElementById('is_cash');
    if (!bankInput || !cashInput) return;
    bankInput.addEventListener('change', function () {
        if (this.checked) cashInput.checked = false;
    });
    cashInput.addEventListener('change', function () {
        if (this.checked) bankInput.checked = false;
    });
})();

const sectionSelect = document.getElementById('sectionSelect');
if (sectionSelect && !sectionSelect.disabled) {
    sectionSelect.addEventListener('change', function() {
        applySection(this.value);
    });
}

if (initialSection) {
    if (sectionSelect) sectionSelect.value = initialSection;
    applySection(initialSection);
}

document.getElementById('coaForm').addEventListener('submit', function() {
    const b = document.getElementById('saveBtn');
    b.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Saving...';
    b.disabled = true;
});
</script>
@endpush
