<?php
require_once __DIR__ . '/../app/helpers.php';
require_once __DIR__ . '/../app/db.php';
require_once __DIR__ . '/../app/layout.php';
require_once __DIR__ . '/account_lib.php';
require_login();

$pdo = db();
$cid = (int)$_SESSION['company_id'];

$st = $pdo->prepare("SELECT * FROM accounts WHERE company_id=? ORDER BY CAST(code AS UNSIGNED), code");
$st->execute([$cid]);
$accounts = $st->fetchAll(PDO::FETCH_ASSOC);

$byParent = [];
foreach ($accounts as $a) {
    $pid = $a['parent_id'] !== null ? (int)$a['parent_id'] : 0;
    $byParent[$pid][] = $a;
}

function account_label(string $type): string {
    return match($type){
        'ASSET' => 'أصول',
        'LIABILITY' => 'خصوم',
        'EQUITY' => 'حقوق الملكية',
        'REVENUE' => 'إيرادات',
        'EXPENSE' => 'مصروفات',
        default => $type,
    };
}

function render_account_nodes(int $parentId, array $byParent): void {
    if (empty($byParent[$parentId])) return;

    echo '<ul class="coa-tree">';
    foreach ($byParent[$parentId] as $a) {
        $id = (int)$a['id'];
        $children = $byParent[$id] ?? [];
        $hasChildren = !empty($children);
        $isCash = (int)$a['is_cash'] === 1;
        $isActive = (int)$a['is_active'] === 1;
        $isLocked = (int)($a['is_locked'] ?? 0) === 1;

        echo '<li class="coa-node '.($hasChildren ? 'has-children collapsed' : 'is-leaf').'" data-node-id="'.$id.'">';

        echo '<div class="coa-row" data-account-row data-id="'.$id.'" data-name="'.h($a['name']).'" data-code="'.h($a['code']).'" data-has-children="'.($hasChildren ? '1' : '0').'">';
            echo '<div class="coa-main">';
                if ($hasChildren) {
                    echo '<button type="button" class="coa-toggle" data-toggle-children aria-label="فتح أو غلق">';
                        echo '<i class="bi bi-caret-down-fill"></i>';
                    echo '</button>';
                } else {
                    echo '<span class="coa-toggle empty"></span>';
                }

                echo '<span class="coa-icon '.($hasChildren ? 'folder' : 'file').'">';
                    echo '<i class="bi '.($hasChildren ? 'bi-folder-fill' : 'bi-file-earmark').'"></i>';
                echo '</span>';

                echo '<span class="coa-name">'.h($a['name']).'</span>';
                echo '<span class="coa-code">'.h($a['code']).'#</span>';

                if ($isCash) {
                    echo '<span class="coa-mini-badge">نقدي</span>';
                }
                if (!$isActive) {
                    echo '<span class="coa-mini-badge danger">معطل</span>';
                }
                if ($isLocked) {
                    echo '<span class="coa-mini-badge">أساسي</span>';
                }
            echo '</div>';

            echo '<div class="coa-actions">';
                echo '<button type="button" class="coa-icon-btn account-add-child" data-id="'.$id.'" data-name="'.h($a['name']).'" data-type="'.h($a['type']).'" title="إضافة حساب فرعي">';
                    echo '<i class="bi bi-plus-circle"></i>';
                echo '</button>';

                echo '<button type="button" class="coa-icon-btn account-edit-btn" '
                    .'data-id="'.$id.'" '
                    .'data-parent-id="'.($a['parent_id'] !== null ? (int)$a['parent_id'] : '').'" '
                    .'data-name="'.h($a['name']).'" '
                    .'data-type="'.h($a['type']).'" '
                    .'data-code="'.h($a['code']).'" '
                    .'data-is-cash="'.($isCash ? 1 : 0).'" '
                    .'data-is-active="'.($isActive ? 1 : 0).'" '
                    .'title="تعديل الحساب">';
                    echo '<i class="bi bi-gear-fill"></i>';
                echo '</button>';

                if (!$isLocked) {
                    echo '<button type="button" class="coa-icon-btn account-delete-btn" '
                        .'data-id="'.$id.'" '
                        .'data-name="'.h($a['name']).'" '
                        .'title="حذف الحساب">';
                        echo '<i class="bi bi-trash"></i>';
                    echo '</button>';
                }
            echo '</div>';
        echo '</div>';

        if ($hasChildren) {
            render_account_nodes($id, $byParent);
        }

        echo '</li>';
    }
    echo '</ul>';
}

function page_actions(){
    echo '<button type="button" class="btn btn-primary btn-sm" id="rootAccountBtn"><i class="bi bi-plus-circle"></i> إضافة حساب رئيسي</button>';
}

render_layout(
    'دليل الحسابات',
    '<a href="'.h(url('/index.php')).'">الرئيسية</a> <span class="mx-1">/</span> <a href="'.h(url('/accounts/index.php')).'">الحسابات</a> <span class="mx-1">/</span> <span>دليل الحسابات</span>',
    function() use ($byParent, $accounts) {
?>
<style>
.coa-shell{
    background:#fff;
    border:1px solid #dfe6ee;
    border-radius:0;
    overflow:hidden;
}
.coa-head{
    background:#fff;
    border-bottom:1px solid #e8edf3;
    padding:14px 16px;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
}
.coa-head-title{
    display:flex;
    align-items:center;
    gap:10px;
}
.coa-head-title .icon-box{
    width:38px;
    height:38px;
    display:grid;
    place-items:center;
    background:#f1f4f8;
    color:#46576d;
    border-radius:8px;
    font-size:1rem;
}
.coa-head-title h3{
    margin:0;
    color:#23364b;
    font-size:1.05rem;
    font-weight:800;
}
.coa-head-title p{
    margin:2px 0 0;
    color:#7f8b99;
    font-size:.84rem;
}
.coa-tools{
    display:flex;
    align-items:center;
    gap:8px;
    flex-wrap:wrap;
}
.coa-tools .form-control{
    min-width:240px;
    min-height:36px;
    border-radius:8px;
}
.coa-summary{
    padding:12px 16px;
    background:#fafbfd;
    border-bottom:1px solid #e8edf3;
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    flex-wrap:wrap;
}
.coa-summary-boxes{
    display:flex;
    align-items:center;
    gap:0;
}
.coa-summary-box{
    min-width:90px;
    padding:0 16px;
    border-left:1px solid #dfe5ec;
    text-align:center;
}
.coa-summary-box:last-child{
    border-left:0;
}
.coa-summary-box .v{
    display:block;
    font-size:1.3rem;
    font-weight:800;
    color:#394b61;
    line-height:1;
}
.coa-summary-box .k{
    display:block;
    font-size:.84rem;
    color:#8895a4;
    margin-top:4px;
}
.coa-selected-inline{
    color:#5d6b7a;
    font-size:.94rem;
}
.coa-selected-inline strong{
    color:#26384d;
}
.coa-wrap{
    padding:14px 10px 22px 10px;
    min-height:540px;
    overflow:auto;
    background:#fff;
    direction:rtl;
}

/* أهم تعديل: نخلي للشجرة عرض أكبر من الحاوية عند الحاجة */
.coa-tree{
    position:relative;
    min-width:1100px;
}

.coa-tree,
.coa-tree ul{
    list-style:none;
    margin:0;
    padding:0;
}

.coa-node{
    position:relative;
}
.coa-node::before{
    content:"";
    position:absolute;
    right:16px;
    top:-6px;
    bottom:-6px;
    border-right:1px dashed #cbd4de;
}
.coa-node:last-child::before{
    bottom:26px;
}

/* خلي الصف نفسه يتمدد حسب المحتوى */
.coa-row{
    position:relative;
    min-height:40px;
    padding:6px 8px 6px 8px;
    margin:1px 0;
    display:grid;
    grid-template-columns:minmax(0, 1fr) auto;
    align-items:center;
    gap:10px;
    cursor:pointer;
    transition:.15s ease;
    min-width:max-content;
}
.coa-row::before{
    content:"";
    position:absolute;
    right:16px;
    top:50%;
    width:18px;
    border-top:1px dashed #cbd4de;
    transform:translateY(-50%);
}
.coa-row:hover{
    background:#f7f9fc;
}
.coa-row.active{
    background:#e8e6f7;
}
.coa-row.is-match{
    background:#f2f6fb;
}
.row-flash{
    animation:rowFlash 1.8s ease;
}
.new-account-highlight{
    animation:newAccountGlow 2s ease;
}
@keyframes rowFlash{
    0%{background:#fff7d6;}
    100%{background:transparent;}
}
@keyframes newAccountGlow{
    0%{background:#dff7e7;}
    70%{background:#dff7e7;}
    100%{background:transparent;}
}

.coa-main{
    display:flex;
    align-items:center;
    gap:8px;
    min-width:max-content;
    flex-wrap:nowrap;
    cursor:pointer;
}

.coa-tree .coa-tree{
    margin-right:26px;
}

.coa-toggle{
    width:16px;
    height:16px;
    border:0;
    background:transparent;
    color:#7e8b98;
    display:grid;
    place-items:center;
    padding:0;
    flex:0 0 auto;
    font-size:.72rem;
}
.coa-toggle.empty{
    visibility:hidden;
}
.coa-node.collapsed > .coa-row .coa-toggle i{
    transform:rotate(-90deg);
}
.coa-node.collapsed > ul{
    display:none;
}
.coa-icon{
    width:18px;
    text-align:center;
    flex:0 0 auto;
    font-size:1.05rem;
}
.coa-icon.folder{
    color:#2f6691;
}
.coa-icon.file{
    color:#4d6d8d;
}

/* أهم تعديل: إلغاء إخفاء النص */
.coa-name{
    color:#32597e;
    font-size:.95rem;
    white-space:nowrap;
    overflow:visible;
    text-overflow:clip;
    min-width:max-content;
}
.coa-code{
    color:#252525;
    font-size:.93rem;
    font-weight:700;
    margin-right:6px;
    white-space:nowrap;
}
.coa-mini-badge{
    font-size:.72rem;
    color:#4b5e73;
    background:#edf2f7;
    border-radius:999px;
    padding:3px 8px;
    white-space:nowrap;
}
.coa-mini-badge.danger{
    color:#a61b3c;
    background:#fff0f3;
}

/* نخلي الأزرار واضحة وثابتة على الطرف */
.coa-actions{
    display:flex;
    align-items:center;
    gap:4px;
    opacity:1;
    transition:.15s ease;
    flex:0 0 auto;
    position:sticky;
    left:0;
    background:#fff;
    padding-right:8px;
    z-index:2;
}
.coa-row:hover .coa-actions,
.coa-row.active .coa-actions{
    opacity:1;
}
.coa-icon-btn{
    width:28px;
    height:28px;
    border:0;
    background:transparent;
    color:#617284;
    border-radius:6px;
    display:grid;
    place-items:center;
}
.coa-icon-btn:hover{
    background:#edf2f7;
    color:#24374c;
}
.account-delete-btn{
    color:#b42318;
}
.account-delete-btn:hover{
    background:#fff1f2;
    color:#b42318;
}
.coa-bottom{
    padding:26px 16px;
    border-top:1px solid #e8edf3;
    background:#fff;
    text-align:center;
}
.coa-bottom h4{
    margin:0 0 10px;
    color:#24374b;
    font-size:1.9rem;
    font-weight:700;
}
.coa-bottom p{
    margin:0 0 12px;
    color:#617488;
    font-size:1rem;
}
.coa-bottom .btn-link{
    text-decoration:none;
    font-size:1.15rem;
    font-weight:700;
}
.coa-bottom .btn-link i{
    margin-left:6px;
}
.account-modal .modal-dialog{max-width:760px}
.account-modal .modal-title{font-weight:800}
.account-hint{font-size:.84rem;color:#7b8a9a}
.code-preview{background:#f7f9fc;font-weight:700;direction:ltr}
.inline-add-shell{margin:8px 0 10px;border:1px solid #cfe3d4;background:#f7fcf8;border-radius:10px;padding:10px}
.inline-add-shell .inline-add-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:10px;color:#23543c;font-weight:700}
.inline-add-shell .inline-add-grid{display:grid;grid-template-columns:180px minmax(220px,1fr) 180px auto;gap:8px;align-items:end}
.inline-add-shell .form-label{font-size:.82rem;margin-bottom:4px;color:#4d5e6f}
.inline-add-shell .inline-actions{display:flex;gap:6px;align-items:end}
.inline-add-shell .inline-error{margin-top:8px;color:#b42318;font-size:.84rem}
.inline-add-anchor{list-style:none}

@media (max-width: 900px){
    .inline-add-shell .inline-add-grid{grid-template-columns:1fr;}
    .inline-add-shell .inline-actions{justify-content:flex-start;}
}

@media (max-width: 768px){
    .coa-head,
    .coa-summary{
        padding:12px;
    }
    .coa-tools{
        width:100%;
    }
    .coa-tools .form-control{
        min-width:0;
        width:100%;
    }
    .coa-wrap{
        padding:10px 4px 18px;
    }
    .coa-tree{
        min-width:900px;
    }
    .coa-name{
        font-size:.92rem;
    }
    .coa-code{
        font-size:.86rem;
    }
    .coa-actions{
        opacity:1;
    }
}
</style>

<div class="coa-shell">
    <div class="coa-head">
        <div class="coa-head-title">
            <div class="icon-box"><i class="bi bi-diagram-3-fill"></i></div>
            <div>
                <h3 id="pageAccountTitle">دليل الحسابات</h3>
                <p>شجرة الحسابات</p>
            </div>
        </div>

        <div class="coa-tools">
            <input type="text" class="form-control" id="treeSearchInput" placeholder="ابحث باسم الحساب أو الكود...">
            <button type="button" class="btn btn-outline-secondary btn-sm" id="expandAllBtn"><i class="bi bi-arrows-expand"></i></button>
            <button type="button" class="btn btn-outline-secondary btn-sm" id="collapseAllBtn"><i class="bi bi-arrows-collapse"></i></button>
        </div>
    </div>

    <div class="coa-summary">
        <div class="coa-summary-boxes">
            <div class="coa-summary-box">
                <span class="v"><?= count($accounts) ?></span>
                <span class="k">ALL</span>
            </div>
            <div class="coa-summary-box">
                <span class="v"><?= count(array_filter($accounts, fn($a) => $a['type'] === 'LIABILITY')) ?></span>
                <span class="k">دائن</span>
            </div>
        </div>

        <div class="coa-selected-inline">
            الحساب المحدد: <strong id="selectedAccountInline">لا يوجد</strong>
        </div>
    </div>

    <div class="coa-wrap" id="accountTreeWrap">
        <?php render_account_nodes(0, $byParent); ?>
    </div>

    <div class="coa-bottom">
        <h4 id="bottomPanelTitle">هذا الحساب فارغ</h4>
        <p id="bottomPanelText">اختر حسابًا من الشجرة أو أضف حسابًا جديدًا.</p>
        <button type="button" class="btn btn-link" id="quickRootAdd"><i class="bi bi-plus-circle"></i> أضف حساب داخل الشجرة</button>
    </div>
</div>

<div class="modal fade account-modal" id="accountTreeModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form id="accountTreeForm">
                <div class="modal-header">
                    <h5 class="modal-title" id="accountTreeModalTitle">إضافة حساب</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>

                <div class="modal-body">
                    <div class="alert alert-danger d-none" id="accountTreeError"></div>

                    <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                    <input type="hidden" name="id" id="treeAccountId">

                    <div class="row g-3">
                        <div class="col-md-4">
                            <label class="form-label">كود الحساب</label>
                            <input type="text" class="form-control code-preview" id="treeAccountCodePreview" readonly>
                            <div class="account-hint mt-1">يتم توليده تلقائيًا حسب موضع الحساب في الشجرة.</div>
                        </div>

                        <div class="col-md-8">
                            <label class="form-label">اسم الحساب</label>
                            <input type="text" class="form-control" name="name" id="treeAccountName" required>
                        </div>

                        <div class="col-md-4">
                            <label class="form-label">النوع</label>
                            <select class="form-select" name="type" id="treeAccountType" required>
                                <option value="ASSET">أصول</option>
                                <option value="LIABILITY">خصوم</option>
                                <option value="EQUITY">حقوق الملكية</option>
                                <option value="REVENUE">إيرادات</option>
                                <option value="EXPENSE">مصروفات</option>
                            </select>
                        </div>

                        <div class="col-md-8">
                            <label class="form-label">الحساب الأب</label>
                            <select class="form-select" name="parent_id" id="treeParentId">
                                <option value="">— حساب رئيسي —</option>
                                <?php foreach ($accounts as $a): ?>
                                    <option value="<?= (int)$a['id'] ?>"><?= h($a['code'].' - '.$a['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <div class="form-check mt-4 pt-1">
                                <input class="form-check-input" type="checkbox" value="1" id="treeIsCash" name="is_cash">
                                <label class="form-check-label" for="treeIsCash">حساب نقدي</label>
                            </div>
                        </div>

                        <div class="col-md-6">
                            <div class="form-check mt-4 pt-1">
                                <input class="form-check-input" type="checkbox" value="1" id="treeIsActive" name="is_active" checked>
                                <label class="form-check-label" for="treeIsActive">حساب نشط</label>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary" id="saveAccountTreeBtn">حفظ الحساب</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', () => {
    const modalEl = document.getElementById('accountTreeModal');
    const modal = modalEl ? new bootstrap.Modal(modalEl) : null;

    const form = document.getElementById('accountTreeForm');
    const errorBox = document.getElementById('accountTreeError');
    const titleEl = document.getElementById('accountTreeModalTitle');
    const idEl = document.getElementById('treeAccountId');
    const nameEl = document.getElementById('treeAccountName');
    const typeEl = document.getElementById('treeAccountType');
    const parentEl = document.getElementById('treeParentId');
    const cashEl = document.getElementById('treeIsCash');
    const activeEl = document.getElementById('treeIsActive');
    const codeEl = document.getElementById('treeAccountCodePreview');

    const selectedInline = document.getElementById('selectedAccountInline');
    const pageAccountTitle = document.getElementById('pageAccountTitle');
    const bottomPanelTitle = document.getElementById('bottomPanelTitle');
    const bottomPanelText = document.getElementById('bottomPanelText');
    const searchInput = document.getElementById('treeSearchInput');
    const treeWrap = document.getElementById('accountTreeWrap');

    function setError(message = '') {
        if (!errorBox) return;
        errorBox.textContent = message;
        errorBox.classList.toggle('d-none', !message);
    }

    function loadPreview() {
        if (!typeEl || !codeEl) return;
        const params = new URLSearchParams({ type: typeEl.value || 'EXPENSE' });
        if (parentEl && parentEl.value) params.set('parent_id', parentEl.value);

        fetch('<?= url('/accounts/code_preview.php') ?>?' + params.toString())
            .then(r => r.json())
            .then(data => {
                if (data && data.success) {
                    codeEl.value = data.code || '';
                    if (data.type && typeEl) typeEl.value = data.type;
                }
            })
            .catch(() => {});
    }
    let activeInlineAdd = null;

    function closeInlineAdd() {
        activeInlineAdd?.remove();
        activeInlineAdd = null;
    }

    function createInlineAddForm(parentId = '', parentName = '', parentType = '') {
        closeInlineAdd();

        const shell = document.createElement('li');
        shell.className = 'inline-add-anchor';
        shell.innerHTML = `
            <div class="inline-add-shell">
                <div class="inline-add-head">
                    <span><i class="bi bi-plus-circle"></i> ${parentId ? 'إضافة حساب فرعي تحت: ' + escapeHtml(parentName || '') : 'إضافة حساب رئيسي جديد'}</span>
                    <button type="button" class="btn btn-sm btn-outline-secondary" data-inline-cancel>إلغاء</button>
                </div>
                <form class="inline-add-form">
                    <input type="hidden" name="_csrf" value="<?= h(csrf_token()) ?>">
                    <input type="hidden" name="parent_id" value="${escapeHtml(parentId || '')}">
                    <div class="inline-add-grid">
                        <div>
                            <label class="form-label">كود الحساب</label>
                            <input type="text" class="form-control code-preview" name="inline_code_preview" value="" readonly>
                        </div>
                        <div>
                            <label class="form-label">اسم الحساب</label>
                            <input type="text" class="form-control" name="name" required>
                        </div>
                        <div>
                            <label class="form-label">النوع</label>
                            <select class="form-select" name="type" ${parentId ? 'disabled' : ''}>
                                <option value="ASSET">أصول</option>
                                <option value="LIABILITY">خصوم</option>
                                <option value="EQUITY">حقوق الملكية</option>
                                <option value="REVENUE">إيرادات</option>
                                <option value="EXPENSE">مصروفات</option>
                            </select>
                        </div>
                        <div class="inline-actions">
                            <button type="submit" class="btn btn-primary">حفظ</button>
                        </div>
                    </div>
                    <div class="inline-error d-none"></div>
                </form>
            </div>
        `;

        const formEl = shell.querySelector('.inline-add-form');
        const typeField = formEl.querySelector('[name="type"]');
        const codeField = formEl.querySelector('[name="inline_code_preview"]');
        const nameField = formEl.querySelector('[name="name"]');
        const errorField = formEl.querySelector('.inline-error');

        if (parentType && typeField) typeField.value = parentType;

        let targetList = null;
        if (parentId) {
            targetList = ensureParentExpanded(String(parentId));
        } else {
            targetList = treeWrap.querySelector(':scope > .coa-tree');
            if (!targetList) {
                targetList = document.createElement('ul');
                targetList.className = 'coa-tree';
                treeWrap.appendChild(targetList);
            }
        }

        targetList.prepend(shell);
        activeInlineAdd = shell;
        nameField?.focus();
        shell.scrollIntoView({ behavior: 'smooth', block: 'center' });

        async function refreshPreview() {
            const params = new URLSearchParams({ type: typeField?.value || 'EXPENSE' });
            if (parentId) params.set('parent_id', parentId);
            const resp = await fetch('<?= url('/accounts/code_preview.php') ?>?' + params.toString());
            const data = await resp.json().catch(() => ({}));
            if (data?.success) {
                codeField.value = data.code || '';
                if (parentId && typeField) typeField.value = data.type || typeField.value;
            }
        }

        refreshPreview().catch(() => {});
        typeField?.addEventListener('change', () => refreshPreview().catch(() => {}));
        shell.querySelector('[data-inline-cancel]')?.addEventListener('click', closeInlineAdd);

        formEl?.addEventListener('submit', async (ev) => {
            ev.preventDefault();
            errorField.classList.add('d-none');
            errorField.textContent = '';

            const fd = new FormData(formEl);
            if (typeField) fd.set('type', typeField.value || parentType || 'EXPENSE');
            fd.set('is_active', '1');

            const resp = await fetch('<?= url('/accounts/save.php') ?>', { method: 'POST', body: fd });
            const data = await resp.json().catch(() => ({ success: false, message: 'تعذر حفظ الحساب' }));
            if (!resp.ok || !data.success) {
                errorField.textContent = data.message || 'تعذر حفظ الحساب';
                errorField.classList.remove('d-none');
                return;
            }

            closeInlineAdd();
            if (typeof showErpToast === 'function') showErpToast('تم إضافة الحساب بنجاح');
            if (data.item) insertNewAccount(data.item);
        });
    }

    function openForCreate(parentId = '', parentName = '', parentType = '') {
        createInlineAddForm(parentId, parentName, parentType);
    }

    function openForEdit(btn) {
        if (!form || !modal || !btn) return;
        form.reset();
        setError('');
        if (idEl) idEl.value = btn.dataset.id || '';
        if (titleEl) titleEl.textContent = 'تعديل الحساب';
        if (nameEl) nameEl.value = btn.dataset.name || '';
        if (typeEl) typeEl.value = btn.dataset.type || 'EXPENSE';
        if (parentEl) parentEl.value = btn.dataset.parentId || '';
        if (cashEl) cashEl.checked = btn.dataset.isCash === '1';
        if (activeEl) activeEl.checked = btn.dataset.isActive !== '0';
        if (codeEl) codeEl.value = btn.dataset.code || '';
        modal.show();
    }

    function updateSelectedAccount(row) {
        if (!row) return;
        document.querySelectorAll('[data-account-row]').forEach(r => r.classList.remove('active'));
        row.classList.add('active');

        const name = row.dataset.name || '';
        const code = row.dataset.code || '';

        if (selectedInline) selectedInline.textContent = name || 'لا يوجد';
        if (pageAccountTitle) pageAccountTitle.textContent = (name ? name : 'دليل الحسابات') + (code ? ' ' + code + '#' : '');
        if (bottomPanelTitle) bottomPanelTitle.textContent = 'هذا الحساب فارغ';
        if (bottomPanelText) bottomPanelText.textContent = code ? ('الحساب المحدد: ' + name + ' - ' + code + '#') : ('الحساب المحدد: ' + name);
    }

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

    function buildAccountNode(item) {
        const li = document.createElement('li');
        li.className = 'coa-node is-leaf';
        li.setAttribute('data-node-id', item.id || '');

        const badges = [];
        if (String(item.is_cash) === '1') badges.push('<span class="coa-mini-badge">نقدي</span>');
        if (String(item.is_active) === '0') badges.push('<span class="coa-mini-badge danger">معطل</span>');

        li.innerHTML = `
            <div class="coa-row row-flash new-account-highlight" data-account-row data-id="${item.id}" data-name="${escapeHtml(item.name || '')}" data-code="${escapeHtml(item.code || '')}" data-has-children="0">
                <div class="coa-main">
                    <span class="coa-toggle empty"></span>
                    <span class="coa-icon file"><i class="bi bi-file-earmark"></i></span>
                    <span class="coa-name">${escapeHtml(item.name || '')}</span>
                    <span class="coa-code">${escapeHtml(item.code || '')}#</span>
                    ${badges.join('')}
                </div>
                <div class="coa-actions">
                    <button type="button" class="coa-icon-btn account-add-child" data-id="${item.id}" data-name="${escapeHtml(item.name || '')}" data-type="${escapeHtml(item.type || '')}" title="إضافة حساب فرعي">
                        <i class="bi bi-plus-circle"></i>
                    </button>
                    <button type="button" class="coa-icon-btn account-edit-btn"
                        data-id="${item.id}"
                        data-parent-id="${item.parent_id ?? ''}"
                        data-name="${escapeHtml(item.name || '')}"
                        data-type="${escapeHtml(item.type || '')}"
                        data-code="${escapeHtml(item.code || '')}"
                        data-is-cash="${String(item.is_cash) === '1' ? '1' : '0'}"
                        data-is-active="${String(item.is_active) === '0' ? '0' : '1'}"
                        title="تعديل الحساب">
                        <i class="bi bi-gear-fill"></i>
                    </button>
                    <button type="button" class="coa-icon-btn account-delete-btn" data-id="${item.id}" data-name="${escapeHtml(item.name || '')}" title="حذف الحساب">
                        <i class="bi bi-trash"></i>
                    </button>
                </div>
            </div>
        `;
        return li;
    }

    function ensureParentExpanded(parentId) {
        if (!parentId) return null;
        const parentNode = document.querySelector('.coa-node[data-node-id="' + String(parentId).replace(/"/g, '\"') + '"]');
        if (!parentNode) return null;

        parentNode.classList.remove('collapsed');
        let childList = parentNode.querySelector(':scope > ul');
        if (!childList) {
            childList = document.createElement('ul');
            childList.className = 'coa-tree';
            parentNode.appendChild(childList);
        }

        const parentRow = parentNode.querySelector(':scope > .coa-row');
        if (parentRow) parentRow.dataset.hasChildren = '1';

        if (parentNode.classList.contains('is-leaf')) {
            parentNode.classList.remove('is-leaf');
            parentNode.classList.add('has-children');

            const togglePlaceholder = parentNode.querySelector(':scope > .coa-row .coa-toggle.empty');
            if (togglePlaceholder) {
                const btn = document.createElement('button');
                btn.type = 'button';
                btn.className = 'coa-toggle';
                btn.setAttribute('data-toggle-children', '1');
                btn.setAttribute('aria-label', 'فتح أو غلق');
                btn.innerHTML = '<i class="bi bi-caret-down-fill"></i>';
                togglePlaceholder.replaceWith(btn);
            }

            const icon = parentNode.querySelector(':scope > .coa-row .coa-icon');
            if (icon) {
                icon.classList.remove('file');
                icon.classList.add('folder');
                const i = icon.querySelector('i');
                if (i) i.className = 'bi bi-folder-fill';
            }
        }

        return childList;
    }

    function insertNewAccount(item) {
        if (!item) return;

        let targetList = null;
        const parentId = item.parent_id ? String(item.parent_id) : '';

        if (parentId) {
            targetList = ensureParentExpanded(parentId);
        } else {
            targetList = treeWrap ? treeWrap.querySelector(':scope > .coa-tree') : null;
            if (!targetList && treeWrap) {
                targetList = document.createElement('ul');
                targetList.className = 'coa-tree';
                treeWrap.appendChild(targetList);
            }
        }

        if (!targetList) {
            window.location.reload();
            return;
        }

        const newNode = buildAccountNode(item);
        targetList.appendChild(newNode);

        const newRow = newNode.querySelector('[data-account-row]');
        if (newRow) {
            updateSelectedAccount(newRow);
            newRow.scrollIntoView({ behavior: 'smooth', block: 'center' });
            setTimeout(() => { newRow.classList.remove('row-flash'); newRow.classList.remove('new-account-highlight'); }, 2000);
        }

        if (parentEl) {
            const option = document.createElement('option');
            option.value = String(item.id || '');
            option.textContent = `${item.code || ''} - ${item.name || ''}`;
            parentEl.appendChild(option);
        }
    }

    function cleanupParentState(node) {
        if (!node) return;
        const childList = node.querySelector(':scope > ul');
        const hasVisibleChildren = !!(childList && childList.querySelector(':scope > .coa-node'));
        if (hasVisibleChildren) return;

        if (childList) childList.remove();
        node.classList.remove('has-children');
        node.classList.add('is-leaf');
        node.classList.remove('collapsed');

        const row = node.querySelector(':scope > .coa-row');
        if (row) row.dataset.hasChildren = '0';

        const toggleBtn = node.querySelector(':scope > .coa-row [data-toggle-children]');
        if (toggleBtn) {
            const placeholder = document.createElement('span');
            placeholder.className = 'coa-toggle empty';
            toggleBtn.replaceWith(placeholder);
        }

        const icon = node.querySelector(':scope > .coa-row .coa-icon');
        if (icon) {
            icon.classList.remove('folder');
            icon.classList.add('file');
            const i = icon.querySelector('i');
            if (i) i.className = 'bi bi-file-earmark';
        }
    }

    function removeAccountNode(accountId) {
        const node = document.querySelector('.coa-node[data-node-id="' + String(accountId).replace(/"/g, '\"') + '"]');
        if (!node) {
            window.location.reload();
            return;
        }

        const parentNode = node.parentElement ? node.parentElement.closest('.coa-node') : null;
        const parentList = node.parentElement;
        node.remove();

        if (parentEl) {
            const option = parentEl.querySelector('option[value="' + String(accountId).replace(/"/g, '\"') + '"]');
            if (option) option.remove();
        }

        if (parentNode && parentList && !parentList.querySelector(':scope > .coa-node')) {
            cleanupParentState(parentNode);
        }

        if (!document.querySelector('[data-account-row].active')) {
            if (selectedInline) selectedInline.textContent = 'لا يوجد';
            if (pageAccountTitle) pageAccountTitle.textContent = 'دليل الحسابات';
            if (bottomPanelTitle) bottomPanelTitle.textContent = 'هذا الحساب فارغ';
            if (bottomPanelText) bottomPanelText.textContent = 'اختر حسابًا من الشجرة أو أضف حسابًا جديدًا.';
        }
    }

    async function deleteAccount(accountId, accountName) {
        const fd = new FormData();
        fd.append('_csrf', '<?= h(csrf_token()) ?>');
        fd.append('id', accountId);

        let resp;
        try {
            resp = await fetch('<?= url('/accounts/delete.php') ?>', {
                method: 'POST',
                body: fd,
                credentials: 'same-origin',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                }
            });
        } catch (err) {
            alert('تعذر الاتصال بالخادم أثناء حذف الحساب');
            return;
        }

        const data = await resp.json().catch(() => ({ success: false, message: 'تعذر حذف الحساب' }));

        if (!resp.ok || !data.success) {
            alert(data.message || 'تعذر حذف الحساب');
            return;
        }

        removeAccountNode(accountId);
        if (typeof showErpToast === 'function') {
            showErpToast('تم حذف الحساب بنجاح');
        } else {
            alert('تم حذف الحساب بنجاح');
        }
    }

    function toggleNode(node) {
        if (!node) return;
        const hasChildren = node.classList.contains('has-children') || !!node.querySelector(':scope > ul');
        if (!hasChildren) return;
        node.classList.toggle('collapsed');
    }

    function setCollapsedAll(collapsed) {
        document.querySelectorAll('.coa-node').forEach(node => {
            if (node.querySelector(':scope > ul')) {
                node.classList.toggle('collapsed', collapsed);
            }
        });
    }

    document.getElementById('rootAccountBtn')?.addEventListener('click', () => openForCreate());
    document.getElementById('quickRootAdd')?.addEventListener('click', () => openForCreate());
    document.getElementById('collapseAllBtn')?.addEventListener('click', () => setCollapsedAll(true));
    document.getElementById('expandAllBtn')?.addEventListener('click', () => setCollapsedAll(false));

    parentEl?.addEventListener('change', loadPreview);
    typeEl?.addEventListener('change', loadPreview);

    document.addEventListener('click', async (e) => {
        const addBtn = e.target.closest('.account-add-child');
        if (addBtn) {
            e.preventDefault();
            e.stopPropagation();
            openForCreate(addBtn.dataset.id || '', addBtn.dataset.name || '', addBtn.dataset.type || '');
            return;
        }

        const editBtn = e.target.closest('.account-edit-btn');
        if (editBtn) {
            e.preventDefault();
            e.stopPropagation();
            openForEdit(editBtn);
            return;
        }

        const deleteBtn = e.target.closest('.account-delete-btn');
        if (deleteBtn) {
            e.preventDefault();
            e.stopPropagation();

            const id = deleteBtn.dataset.id || '';
            const name = deleteBtn.dataset.name || '';
            if (!id) return;

            const ok = confirm(`هل أنت متأكد من حذف الحساب: ${name} ؟
لن يتم الحذف إذا كان الحساب مرتبطًا بقيود أو حركات أو له حسابات فرعية.`);
            if (!ok) return;

            await deleteAccount(id, name);
            return;
        }

        const toggleBtn = e.target.closest('[data-toggle-children]');
        if (toggleBtn) {
            e.preventDefault();
            e.stopPropagation();
            toggleNode(toggleBtn.closest('.coa-node'));
            return;
        }

        const row = e.target.closest('[data-account-row]');
        if (row && !e.target.closest('.coa-actions')) {
            e.preventDefault();
            updateSelectedAccount(row);
            toggleNode(row.closest('.coa-node'));
            return;
        }
    });

    form?.addEventListener('submit', async (e) => {
        e.preventDefault();
        setError('');

        const isCreate = !idEl?.value;
        const fd = new FormData(form);
        if (activeEl && !activeEl.checked) fd.set('is_active', '0');

        const resp = await fetch('<?= url('/accounts/save.php') ?>', { method: 'POST', body: fd });
        const data = await resp.json().catch(() => ({ success: false, message: 'تعذر حفظ الحساب' }));

        if (!resp.ok || !data.success) {
            setError(data.message || 'تعذر حفظ الحساب');
            return;
        }

        if (typeof showErpToast === 'function') {
            showErpToast('تم حفظ الحساب بنجاح');
        }

        modal?.hide();

        if (isCreate && data.item) {
            insertNewAccount(data.item);
            form.reset();
            if (activeEl) activeEl.checked = true;
            setError('');
            loadPreview();
            return;
        }

        window.location.reload();
    });

    searchInput?.addEventListener('input', () => {
        const q = (searchInput.value || '').trim().toLowerCase();

        if (!q) {
            document.querySelectorAll('.coa-node').forEach(node => node.style.display = '');
            document.querySelectorAll('[data-account-row]').forEach(row => row.classList.remove('is-match'));
            setCollapsedAll(true);
            return;
        }

        document.querySelectorAll('.coa-node').forEach(node => node.style.display = 'none');

        document.querySelectorAll('[data-account-row]').forEach(row => {
            const text = (row.innerText || '').toLowerCase();
            const matched = text.includes(q);
            row.classList.toggle('is-match', matched);

            if (matched) {
                let current = row.closest('.coa-node');
                while (current) {
                    current.style.display = '';
                    current.classList.remove('collapsed');
                    current = current.parentElement ? current.parentElement.closest('.coa-node') : null;
                }
            }
        });
    });

    setCollapsedAll(true);
});
</script>
<?php
    }
);