<?php $__env->startSection('title', 'General Ledger'); ?>
<?php $__env->startSection('body-class', 'page-general-ledger'); ?>

<?php $__env->startSection('breadcrumb'); ?>
    <li class="breadcrumb-item"><a href="<?php echo e(route('dashboard')); ?>">Dashboard</a></li>
    <li class="breadcrumb-item active">General Ledger</li>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('styles'); ?>
<?php echo $__env->make('partials.report-datepicker-assets', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<?php
    $companyId = auth()->user()->company_id;
    $fmt = fn($amount) => abs((float) $amount) < 0.005 ? '—' : \App\Helpers\NumberHelper::formatAmount((float) abs($amount), $companyId);
    $ledgerData = $ledger ?? null;
    $isAllLedger = $ledgerData && ($ledgerData['mode'] ?? 'single') === 'all';
    $selectedAccount = $ledgerData['account'] ?? null;
    $entries = $ledgerData['entries'] ?? collect();
    $groups = $ledgerData['groups'] ?? [];
    $totals = $ledgerData['totals'] ?? [
        'opening_debit' => 0, 'opening_credit' => 0,
        'period_debit' => 0, 'period_credit' => 0,
        'closing_debit' => 0, 'closing_credit' => 0,
    ];
    $companyName = auth()->user()->company?->name ?? config('app.name');
    $periodLabel = \Carbon\Carbon::parse($dateFrom)->format('d M Y') . ' to ' . \Carbon\Carbon::parse($dateTo)->format('d M Y');
    $accountLabel = $selectedAccountsLabel ?? 'Select account(s)';
    $allLedger = $allLedger ?? false;
    $selectedAccountIds = $selectedAccountIds ?? [];
    $hasReport = (bool) $ledgerData;
    $exportQuery = $exportQuery ?? request()->query();
    $hasGroups = $isAllLedger && !empty($groups);
?>

<div class="pl-report-wrap gl-report-wrap">
    <div class="gl-report-top">
        <div class="gl-report-heading-centered">
            <div class="pl-report-company"><?php echo e($companyName); ?></div>
            <h2 class="pl-report-title">General Ledger</h2>
            <div class="pl-report-period"><?php echo e($periodLabel); ?></div>
        </div>

        <?php if($hasReport): ?>
        <div class="gl-report-toolbar-row no-print">
            <div class="pl-report-actions gl-report-actions-right">
                <button type="button" class="pl-report-action-btn" id="glPrintReport">
                    <i class="bi bi-printer"></i><span>Print</span>
                </button>
                <a href="<?php echo e(route('reports.general-ledger.export', $exportQuery)); ?>" class="pl-report-action-btn">
                    <i class="bi bi-download"></i><span>Export</span>
                </a>
                <button type="button" class="pl-report-action-btn" data-bs-toggle="modal" data-bs-target="#glEmailModal">
                    <i class="bi bi-envelope"></i><span>Email</span>
                </button>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <div class="pl-report-filters no-print">
        <form method="GET" action="<?php echo e(route('reports.general-ledger')); ?>" id="glReportFilterForm">
            <div class="pl-report-filter-row pl-report-filter-row-4">
                <div class="pl-report-filter-field">
                    <label class="form-label fw-semibold">Account</label>
                    <?php echo $__env->make('reports.general-ledger._account-picker', [
                        'accountTree' => $filterOptions['accountTree'] ?? [],
                        'selectedAccountIds' => $selectedAccountIds,
                        'allLedger' => $allLedger,
                        'selectedAccountsLabel' => $selectedAccountsLabel ?? 'Select account(s)',
                    ], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
                <div class="pl-report-filter-field">
                    <label class="form-label fw-semibold">Date From</label>
                    <div class="input-group axis-date-field">
                        <input type="text" name="date_from" class="form-control axis-report-datepicker" value="<?php echo e($dateFrom); ?>" autocomplete="off" placeholder="dd-mm-yyyy">
                        <button type="button" class="input-group-text axis-date-trigger" data-axis-date-open aria-label="Open calendar">
                            <i class="bi bi-calendar3"></i>
                        </button>
                    </div>
                </div>
                <div class="pl-report-filter-field">
                    <label class="form-label fw-semibold">Date To</label>
                    <div class="input-group axis-date-field">
                        <input type="text" name="date_to" class="form-control axis-report-datepicker" value="<?php echo e($dateTo); ?>" autocomplete="off" placeholder="dd-mm-yyyy">
                        <button type="button" class="input-group-text axis-date-trigger" data-axis-date-open aria-label="Open calendar">
                            <i class="bi bi-calendar3"></i>
                        </button>
                    </div>
                </div>
                <div class="pl-report-filter-field">
                    <label class="form-label fw-semibold">Search</label>
                    <input type="search" name="search" class="form-control" value="<?php echo e($filters['search'] ?? ''); ?>" placeholder="Voucher, memo, account...">
                </div>
            </div>
            <div class="pl-report-filter-row pl-report-filter-row-4">
                <div class="pl-report-filter-field">
                    <label class="form-label fw-semibold">Account Type</label>
                    <?php echo $__env->make('reports.profit-loss._multi-filter-picker', [
                        'pickerId' => 'glAccountTypePicker',
                        'emptyLabel' => 'All account types',
                        'searchPlaceholder' => 'Search account types...',
                        'inputName' => 'account_sections[]',
                        'selectedValues' => $filters['account_sections'] ?? [],
                        'options' => $filterOptions['accountTypes'],
                        'toggleLabel' => $selectedAccountTypesLabel ?? 'All account types',
                    ], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
                <div class="pl-report-filter-field">
                    <label class="form-label fw-semibold">Voucher Type</label>
                    <?php echo $__env->make('reports.profit-loss._multi-filter-picker', [
                        'pickerId' => 'glVoucherTypePicker',
                        'emptyLabel' => 'All voucher types',
                        'searchPlaceholder' => 'Search voucher types...',
                        'inputName' => 'voucher_types[]',
                        'selectedValues' => $filters['voucher_types'] ?? [],
                        'options' => $filterOptions['voucherTypes'],
                        'toggleLabel' => $selectedVoucherTypesLabel ?? 'All voucher types',
                    ], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
                <div class="pl-report-filter-field">
                    <label class="form-label fw-semibold">Dimension</label>
                    <?php echo $__env->make('reports.profit-loss._dimension-picker', [
                        'pickerId' => 'glDimensionPicker',
                        'dimensionTree' => $filterOptions['dimensionTree'] ?? [],
                        'selectedIds' => $filters['dimension_value_ids'] ?? [],
                        'emptyLabel' => 'All dimensions',
                        'toggleLabel' => $selectedDimensionsLabel ?? 'All dimensions',
                    ], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                </div>
                <div class="pl-report-filter-field d-flex align-items-end gap-2">
                    <button type="submit" class="btn btn-primary btn-sm flex-grow-1"><i class="bi bi-search me-1"></i>Apply</button>
                    <a href="<?php echo e(route('reports.general-ledger')); ?>" class="btn btn-outline-secondary btn-sm"><i class="bi bi-x-lg"></i></a>
                </div>
            </div>
        </form>
    </div>

    <?php if(!$hasReport): ?>
        <div class="gl-report-empty">
            <i class="bi bi-journal-text display-5 d-block mb-3 text-muted"></i>
            <p class="text-muted mb-0">Select All Ledger or one or more accounts, then apply your date range.</p>
        </div>
    <?php else: ?>
        <div class="gl-report-summary">
            <div>
                <div class="text-muted small">Account</div>
                <div class="fw-bold"><?php echo e($accountLabel); ?></div>
            </div>
            <?php if($hasReport): ?>
            <div class="ms-auto no-print">
                <a href="<?php echo e(route('reports.trial-balance', ['date_from' => $dateFrom, 'date_to' => $dateTo])); ?>" class="btn btn-outline-secondary btn-sm">
                    <i class="bi bi-arrow-left me-1"></i>Trial Balance
                </a>
            </div>
            <?php endif; ?>
            <?php if(!$isAllLedger): ?>
            <div>
                <div class="text-muted small">Closing Balance</div>
                <div class="fw-bold">
                    <?php echo e($totals['closing_debit'] > 0 ? $fmt($totals['closing_debit']) . ' Dr' : ($totals['closing_credit'] > 0 ? $fmt($totals['closing_credit']) . ' Cr' : '—')); ?>

                </div>
            </div>
            <?php elseif($hasGroups): ?>
            <div>
                <div class="text-muted small">Accounts Shown</div>
                <div class="fw-bold"><?php echo e(count($groups)); ?></div>
            </div>
            <?php endif; ?>
        </div>

        <div class="pl-report-body">
            <div class="table-responsive">
                <table class="table mb-0 pl-report-table gl-report-table" id="glReportTable">
                    <thead>
                        <tr>
                            <th style="width:110px">Date</th>
                            <th style="width:160px">Voucher</th>
                            <th>Reference / Narration</th>
                            <th style="width:140px">Name</th>
                            <th style="width:150px">Dimension</th>
                            <th style="width:180px">Split Accounts</th>
                            <th class="text-end" style="width:130px">Debit</th>
                            <th class="text-end" style="width:130px">Credit</th>
                            <th class="text-end" style="width:150px">Balance</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if($hasGroups): ?>
                            <?php $__empty_1 = true; $__currentLoopData = $groups; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $group): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <?php echo $__env->make('reports.general-ledger._account-group', [
                                    'group' => $group,
                                    'fmt' => $fmt,
                                    'dateFrom' => $dateFrom,
                                ], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr>
                                    <td colspan="9" class="text-center py-5 text-muted">
                                        No ledger movement found for the selected filters.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        <?php else: ?>
                            <?php if(!$isAllLedger): ?>
                            <tr class="gl-report-opening-row">
                                <td><?php echo e(\Carbon\Carbon::parse($dateFrom)->subDay()->format('d M Y')); ?></td>
                                <td></td>
                                <td class="fw-semibold">Opening Balance</td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td class="text-end"><?php echo e($fmt($totals['opening_debit'])); ?></td>
                                <td class="text-end"><?php echo e($fmt($totals['opening_credit'])); ?></td>
                                <td class="text-end fw-semibold">
                                    <?php echo e($totals['opening_debit'] > 0 ? $fmt($totals['opening_debit']) . ' Dr' : ($totals['opening_credit'] > 0 ? $fmt($totals['opening_credit']) . ' Cr' : '—')); ?>

                                </td>
                            </tr>
                            <?php endif; ?>
                            <?php $__empty_1 = true; $__currentLoopData = $entries; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $entry): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <?php echo $__env->make('reports.general-ledger._entry-row', ['entry' => $entry, 'fmt' => $fmt], array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr>
                                    <td colspan="9" class="text-center py-5 text-muted">
                                        No ledger movement found for the selected period.
                                    </td>
                                </tr>
                            <?php endif; ?>
                        <?php endif; ?>
                    </tbody>
                    <?php if($hasReport): ?>
                    <tfoot>
                        <tr class="gl-report-total-row">
                            <th colspan="6" class="text-end">Current Period Total</th>
                            <th class="text-end"><?php echo e($fmt($totals['period_debit'])); ?></th>
                            <th class="text-end"><?php echo e($fmt($totals['period_credit'])); ?></th>
                            <th></th>
                        </tr>
                    </tfoot>
                    <?php endif; ?>
                </table>
            </div>
        </div>
    <?php endif; ?>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('modals'); ?>
<?php if($hasReport ?? false): ?>
<?php
    $emailFormat = old('format', 'pdf');
    $defaultPaperSize = old('paper_size', 'a4');
    $defaultLayout = old('layout', 'landscape');
    $paperSizeOptions = ['a4' => 'A4', 'letter' => 'Letter', 'legal' => 'Legal'];
    $layoutOptions = ['portrait' => 'Portrait', 'landscape' => 'Landscape'];
?>
<div class="modal fade" id="glEmailModal" tabindex="-1" aria-labelledby="glEmailModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <form method="POST" action="<?php echo e(route('reports.general-ledger.email', $exportQuery)); ?>">
                <?php echo csrf_field(); ?>
                <div class="modal-header">
                    <h5 class="modal-title" id="glEmailModalLabel">Email General Ledger Report</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-semibold d-block">Attachment Format</label>
                        <div class="btn-group w-100 pl-email-format-group" role="group" aria-label="Attachment format">
                            <input type="radio" class="btn-check" name="format" id="glEmailFormatPdf" value="pdf" <?php echo e($emailFormat === 'pdf' ? 'checked' : ''); ?> required>
                            <label class="btn btn-outline-primary" for="glEmailFormatPdf">
                                <i class="bi bi-file-earmark-pdf me-1"></i>PDF (.pdf)
                            </label>
                            <input type="radio" class="btn-check" name="format" id="glEmailFormatXlsx" value="xlsx" <?php echo e($emailFormat === 'xlsx' ? 'checked' : ''); ?>>
                            <label class="btn btn-outline-primary" for="glEmailFormatXlsx">
                                <i class="bi bi-file-earmark-excel me-1"></i>Excel (.xlsx)
                            </label>
                        </div>
                    </div>
                    <div class="mb-3" id="glEmailPdfOptions">
                        <div class="row g-3">
                            <div class="col-sm-6">
                                <label class="form-label fw-semibold" for="glEmailPaperSize">Paper Size</label>
                                <select name="paper_size" id="glEmailPaperSize" class="form-select">
                                    <?php $__currentLoopData = $paperSizeOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($value); ?>" <?php echo e($defaultPaperSize === $value ? 'selected' : ''); ?>><?php echo e($label); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                            <div class="col-sm-6">
                                <label class="form-label fw-semibold" for="glEmailLayout">Layout</label>
                                <select name="layout" id="glEmailLayout" class="form-select">
                                    <?php $__currentLoopData = $layoutOptions; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $value => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                        <option value="<?php echo e($value); ?>" <?php echo e($defaultLayout === $value ? 'selected' : ''); ?>><?php echo e($label); ?></option>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Recipient Email</label>
                        <input type="email" name="recipient" class="form-control" value="<?php echo e(old('recipient', auth()->user()->email)); ?>" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-semibold">Subject</label>
                        <input type="text" name="subject" class="form-control" value="<?php echo e(old('subject', 'General Ledger — ' . $companyName . ' (' . ($accountLabel ?? 'All Ledger') . ', ' . $periodLabel . ')')); ?>">
                    </div>
                    <div class="mb-0">
                        <label class="form-label fw-semibold">Message</label>
                        <textarea name="message" class="form-control" rows="4"><?php echo e(old('message', "Please find the attached General Ledger report for {$companyName}.\n\nAccount: " . ($accountLabel ?? 'All Ledger') . "\nPeriod: {$periodLabel}")); ?></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-send me-1"></i>Send Email
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php endif; ?>
<?php $__env->stopPush(); ?>

<?php $__env->startPush('scripts'); ?>
<?php echo $__env->make('partials.report-datepicker-init', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php echo $__env->make('reports.general-ledger._account-picker-scripts', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php echo $__env->make('reports.general-ledger._filter-scripts', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /home/duiclick/public_html/test.duiclick.com/resources/views/reports/general-ledger/index.blade.php ENDPATH**/ ?>