<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Journal Entries - Accounting</title>
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Font Awesome 6 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- DataTables -->
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/dataTables.bootstrap5.min.css">
    <!-- SweetAlert2 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
            background: #f5f7fb;
        }

        /* Navbar */
        .navbar {
            background: white;
            padding: 0.75rem 2rem;
            box-shadow: 0 2px 10px rgba(0,0,0,0.03);
        }

        .navbar-brand {
            font-weight: 600;
            color: #2d3748;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .brand-icon {
            background: #4361ee;
            color: white;
            width: 35px;
            height: 35px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1rem;
        }

        .nav-link {
            color: #64748b !important;
            font-weight: 500;
            padding: 0.5rem 1.2rem !important;
            margin: 0 0.2rem;
            border-radius: 8px;
            transition: all 0.2s;
        }

        .nav-link:hover, .nav-link.active {
            background: #f1f5f9;
            color: #4361ee !important;
        }

        .nav-link i {
            margin-right: 8px;
            font-size: 0.9rem;
        }

        .user-avatar {
            width: 38px;
            height: 38px;
            background: #e2e8f0;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            color: #475569;
        }

        /* Main Container */
        .main-container {
            padding: 2rem;
            max-width: 1400px;
            margin: 0 auto;
        }

        /* Page Header */
        .page-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 2rem;
        }

        .page-header h1 {
            font-size: 1.8rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.3rem;
        }

        .page-header p {
            color: #64748b;
        }

        .btn-primary {
            background: #4361ee;
            border: none;
            padding: 0.6rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
        }

        .btn-primary:hover {
            background: #3651d4;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.2);
        }

        .btn-outline-primary {
            background: transparent;
            border: 1px solid #4361ee;
            color: #4361ee;
            padding: 0.6rem 1.5rem;
            border-radius: 10px;
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;
            transition: all 0.2s;
        }

        .btn-outline-primary:hover {
            background: #4361ee;
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.2);
        }

        /* Stats Cards */
        .stats-row {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 1.5rem;
            margin-bottom: 2rem;
        }

        .stat-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.02);
            transition: transform 0.2s;
            border: 1px solid rgba(0,0,0,0.02);
        }

        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.05);
        }

        .stat-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1rem;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9rem;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .stat-icon {
            width: 45px;
            height: 45px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
        }

        .stat-icon.purple { background: #e9efff; color: #4361ee; }
        .stat-icon.green { background: #e3f7ec; color: #10b981; }
        .stat-icon.orange { background: #fff2e0; color: #f97316; }
        .stat-icon.red { background: #fee9e9; color: #ef4444; }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 700;
            color: #1e293b;
            margin-bottom: 0.2rem;
        }

        /* Filter Card */
        .filter-card {
            background: white;
            border-radius: 16px;
            padding: 1.5rem;
            box-shadow: 0 4px 15px rgba(0,0,0,0.02);
            margin-bottom: 1.5rem;
        }

        .filter-card h5 {
            font-size: 1rem;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 1rem;
        }

        .filter-label {
            color: #64748b;
            font-size: 0.85rem;
            font-weight: 500;
            margin-bottom: 0.3rem;
        }

        .form-select, .form-control {
            border: 1px solid #e2e8f0;
            border-radius: 10px;
            padding: 0.6rem 1rem;
            transition: all 0.2s;
        }

        .form-select:focus, .form-control:focus {
            border-color: #4361ee;
            box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.1);
        }

        .btn-apply {
            background: #4361ee;
            color: white;
            border: none;
            border-radius: 10px;
            padding: 0.6rem 1.5rem;
            font-weight: 500;
            width: 100%;
            transition: all 0.2s;
        }

        .btn-apply:hover {
            background: #3651d4;
        }

        /* Table Card */
        .table-card {
            background: white;
            border-radius: 16px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.02);
            overflow: hidden;
        }

        .table-header {
            padding: 1.2rem 1.5rem;
            border-bottom: 1px solid #f1f5f9;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .table-header h5 {
            font-weight: 600;
            color: #1e293b;
            margin: 0;
        }

        .table-header i {
            color: #4361ee;
        }

        .table-responsive {
            padding: 0 1.5rem 1.5rem 1.5rem;
        }

        .table {
            margin: 0;
        }

        .table thead th {
            background: #f8fafc;
            border-bottom: 2px solid #e2e8f0;
            color: #475569;
            font-weight: 600;
            font-size: 0.85rem;
            padding: 1rem;
            white-space: nowrap;
        }

        .table tbody td {
            padding: 1rem;
            vertical-align: middle;
            border-bottom: 1px solid #f1f5f9;
            color: #1e293b;
        }

        .table tbody tr:hover {
            background: #f8fafc;
        }

        .entry-number {
            font-weight: 600;
            color: #4361ee;
            cursor: pointer;
        }

        .entry-number:hover {
            text-decoration: underline;
        }

        .badge-status {
            padding: 0.3rem 0.8rem;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .badge-status.posted { background: #e3f7ec; color: #10b981; }
        .badge-status.draft { background: #fff2e0; color: #f97316; }
        .badge-status.cancelled { background: #fee9e9; color: #ef4444; }

        .amount-debit {
            color: #4361ee;
            font-weight: 600;
        }

        .amount-credit {
            color: #10b981;
            font-weight: 600;
        }

        /* Action Buttons */
        .action-btns {
            display: flex;
            gap: 5px;
            flex-wrap: wrap;
        }

        .btn-icon {
            width: 32px;
            height: 32px;
            padding: 0;
            border-radius: 8px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #e2e8f0;
            background: white;
            color: #64748b;
            transition: all 0.2s;
            cursor: pointer;
        }

        .btn-icon:hover {
            background: #f1f5f9;
            border-color: #4361ee;
        }

        .btn-icon.info:hover { color: #4361ee; border-color: #4361ee; }
        .btn-icon.edit:hover { color: #f97316; border-color: #f97316; }
        .btn-icon.post:hover { color: #10b981; border-color: #10b981; }
        .btn-icon.reverse:hover { color: #f97316; border-color: #f97316; }
        .btn-icon.delete:hover { color: #ef4444; border-color: #ef4444; }

        /* Modal */
        .modal-content {
            border: none;
            border-radius: 16px;
            overflow: hidden;
        }

        .modal-header {
            background: #4361ee;
            color: white;
            border: none;
            padding: 1.2rem 1.5rem;
        }

        .modal-header .btn-close {
            filter: brightness(0) invert(1);
        }

        .modal-body {
            padding: 1.5rem;
        }

        .modal-footer {
            border-top: 1px solid #f1f5f9;
            padding: 1.2rem 1.5rem;
        }

        .form-label {
            font-weight: 500;
            color: #475569;
            margin-bottom: 0.3rem;
        }

        /* Detail View */
        .detail-item {
            background: #f8fafc;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 0.8rem;
        }

        .detail-label {
            color: #64748b;
            font-size: 0.85rem;
            margin-bottom: 0.3rem;
        }

        .detail-value {
            font-weight: 600;
            color: #1e293b;
            font-size: 1rem;
        }

        /* Journal Items Table */
        .journal-items-table {
            font-size: 0.9rem;
        }

        .journal-items-table th {
            background: #f8fafc;
            color: #475569;
            font-weight: 600;
            padding: 0.75rem;
        }

        .journal-items-table td {
            padding: 0.75rem;
            border-bottom: 1px solid #f1f5f9;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 4rem;
        }

        .empty-state i {
            font-size: 4rem;
            color: #cbd5e1;
            margin-bottom: 1rem;
        }

        .empty-state p {
            color: #64748b;
            margin-bottom: 1.5rem;
        }

        /* Template Cards */
        .template-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 1rem;
            max-height: 500px;
            overflow-y: auto;
            padding: 0.5rem;
        }

        .template-card {
            background: #f8fafc;
            border-radius: 12px;
            padding: 1.2rem;
            cursor: pointer;
            transition: all 0.2s;
            border: 2px solid transparent;
        }

        .template-card:hover {
            border-color: #4361ee;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(67, 97, 238, 0.1);
        }

        .template-icon {
            width: 45px;
            height: 45px;
            background: #e9efff;
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #4361ee;
            font-size: 1.2rem;
            margin-bottom: 0.8rem;
        }

        .template-card h6 {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.3rem;
        }

        .template-card small {
            color: #64748b;
        }

        /* Responsive */
        @media (max-width: 992px) {
            .stats-row {
                grid-template-columns: repeat(2, 1fr);
            }
        }

        @media (max-width: 768px) {
            .main-container {
                padding: 1rem;
            }
            
            .page-header {
                flex-direction: column;
                gap: 1rem;
                text-align: center;
            }
            
            .stats-row {
                grid-template-columns: 1fr;
            }
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar">
        <div class="container-fluid">
            <a class="navbar-brand" href="/accounting/dashboard">
                <div class="brand-icon">
                    <i class="fas fa-calculator"></i>
                </div>
                <span>{{ hotelName() }} ACCOUNTING</span>
            </a>

            <div class="d-flex align-items-center gap-4">
                <div class="d-flex">
                    <a href="/accounting/dashboard" class="nav-link {{ request()->is('accounting/dashboard') ? 'active' : '' }}">
                        <i class="fas fa-home"></i>Dashboard
                    </a>
                    <a href="/accounting/chart-of-accounts" class="nav-link {{ request()->is('accounting/chart-of-accounts') ? 'active' : '' }}">
                        <i class="fas fa-book"></i>Accounts
                    </a>
                    <a href="/accounting/journal-entries" class="nav-link {{ request()->is('accounting/journal-entries*') ? 'active' : '' }}">
                        <i class="fas fa-receipt"></i>Journal
                    </a>
                    <a href="/accounting/budgets" class="nav-link {{ request()->is('accounting/budgets') ? 'active' : '' }}">
                        <i class="fas fa-chart-pie"></i>Budgets
                    </a>
                    <a href="/contacts/vendors" class="nav-link {{ request()->is('contacts/vendors*') ? 'active' : '' }}">
                        <i class="fas fa-truck"></i>Vendors
                    </a>
                    <div class="dropdown d-inline">
                        <a href="#" class="nav-link dropdown-toggle" data-bs-toggle="dropdown">
                            <i class="fas fa-file-alt"></i>Reports
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/accounting/reports/trial-balance">Trial Balance</a></li>
                            <li><a class="dropdown-item" href="/accounting/reports/profit-loss">Profit & Loss</a></li>
                            <li><a class="dropdown-item" href="/accounting/reports/balance-sheet">Balance Sheet</a></li>
                            <li><a class="dropdown-item" href="/accounting/reports/general-ledger">General Ledger</a></li>
                        </ul>
                    </div>
                </div>
                <div class="user-avatar">
                    <span>{{ substr(Auth::user()->name ?? 'U', 0, 1) }}</span>
                </div>
            </div>
        </div>
    </nav>

    <!-- Main Container -->
    <div class="main-container">
        <!-- Page Header -->
        <div class="page-header">
            <div>
                <div class="d-flex align-items-center gap-3 mb-2">
                    <a href="{{ route('accounting.dashboard') }}" class="btn btn-sm btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i>
                    </a>
                    <h1 class="mb-0">Journal Entries</h1>
                </div>
                <p>Record and manage financial transactions</p>
            </div>
            <div class="d-flex gap-2">
                <button class="btn-outline-primary" onclick="openCreateModal()">
                    <i class="fas fa-plus"></i>
                    <span>Manual Entry</span>
                </button>
                <button class="btn-primary" onclick="openTemplateModal()">
                    <i class="fas fa-file-import"></i>
                    <span>From Template</span>
                </button>
            </div>
        </div>

        <!-- Stats Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Total Entries</span>
                    <div class="stat-icon purple">
                        <i class="fas fa-receipt"></i>
                    </div>
                </div>
                <div class="stat-value">{{ $journalEntries->total() ?? 0 }}</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Total Debits</span>
                    <div class="stat-icon green">
                        <i class="fas fa-arrow-up"></i>
                    </div>
                </div>
                <div class="stat-value">{{ number_format($totals['debit'] ?? 0) }}</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Total Credits</span>
                    <div class="stat-icon orange">
                        <i class="fas fa-arrow-down"></i>
                    </div>
                </div>
                <div class="stat-value">{{ number_format($totals['credit'] ?? 0) }}</div>
            </div>

            <div class="stat-card">
                <div class="stat-header">
                    <span class="stat-label">Balance</span>
                    <div class="stat-icon red">
                        <i class="fas fa-balance-scale"></i>
                    </div>
                </div>
                <div class="stat-value">{{ number_format(($totals['debit'] ?? 0) - ($totals['credit'] ?? 0)) }}</div>
            </div>
        </div>

        <!-- Filter Card -->
        <div class="filter-card">
            <h5><i class="fas fa-filter me-2" style="color: #4361ee;"></i>Filter Journal Entries</h5>
            <div class="row g-3">
                <div class="col-md-3">
                    <div class="filter-label">STATUS</div>
                    <select class="form-select" id="filterStatus">
                        <option value="">All Statuses</option>
                        <option value="draft">Draft</option>
                        <option value="posted">Posted</option>
                        <option value="cancelled">Cancelled</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <div class="filter-label">FROM DATE</div>
                    <input type="date" class="form-control" id="filterDateFrom">
                </div>
                <div class="col-md-2">
                    <div class="filter-label">TO DATE</div>
                    <input type="date" class="form-control" id="filterDateTo">
                </div>
                <div class="col-md-3">
                    <div class="filter-label">ACCOUNT</div>
                    <select class="form-select" id="filterAccount">
                        <option value="">All Accounts</option>
                        @foreach($accounts ?? [] as $account)
                            <option value="{{ $account->id }}">{{ $account->code }} - {{ $account->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="col-md-2 d-flex align-items-end">
                    <button class="btn-apply" onclick="applyFilters()">
                        <i class="fas fa-search me-2"></i>Apply
                    </button>
                </div>
            </div>
        </div>

        <!-- Journal Entries Table -->
        <div class="table-card">
            <div class="table-header">
                <h5><i class="fas fa-list me-2"></i>Journal Entries List</h5>
                <span class="text-muted">Total: {{ $journalEntries->total() ?? 0 }} entries</span>
            </div>
            <div class="table-responsive">
                <table class="table" id="journalTable">
                    <thead>
                        <tr>
                            <th>Entry #</th>
                            <th>Date</th>
                            <th>Description</th>
                            <th class="text-end">Debit Total</th>
                            <th class="text-end">Credit Total</th>
                            <th>Status</th>
                            <th>Created By</th>
                            <th class="text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        @forelse($journalEntries ?? [] as $entry)
                        <tr>
                            <td>
                                <span class="entry-number" onclick="viewJournalEntry({{ $entry->id }})">{{ $entry->entry_number }}</span>
                            </td>
                            <td>{{ $entry->date->format('M d, Y') }}</td>
                            <td>{{ Str::limit($entry->description, 40) }}</td>
                            <td class="text-end amount-debit">{{ number_format($entry->items->sum('debit')) }}</td>
                            <td class="text-end amount-credit">{{ number_format($entry->items->sum('credit')) }}</td>
                            <td>
                                <span class="badge-status {{ $entry->status }}">
                                    {{ ucfirst($entry->status) }}
                                </span>
                            </td>
                            <td>{{ $entry->createdBy?->name ?? 'N/A' }}</td>
                            <td>
                                <div class="action-btns justify-content-center">
                                    <button class="btn-icon info" onclick="viewJournalEntry({{ $entry->id }})" title="View Details">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    
                                    @if($entry->status === 'draft')
                                        <button class="btn-icon edit" onclick="editJournalEntry({{ $entry->id }})" title="Edit Entry">
                                            <i class="fas fa-edit"></i>
                                        </button>
                                        <button class="btn-icon post" onclick="postJournalEntry({{ $entry->id }})" title="Post Entry">
                                            <i class="fas fa-check-circle"></i>
                                        </button>
                                        <button class="btn-icon delete" onclick="deleteJournalEntry({{ $entry->id }})" title="Delete Entry">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    @endif
                                    
                                    @if($entry->status === 'posted')
                                        <button class="btn-icon reverse" onclick="reverseJournalEntry({{ $entry->id }})" title="Reverse Entry">
                                            <i class="fas fa-undo"></i>
                                        </button>
                                    @endif
                                </div>
                            </td>
                        </tr>
                        @empty
                        <tr>
                            <td colspan="8" class="text-center">
                                <div class="empty-state">
                                    <i class="fas fa-receipt"></i>
                                    <p>No journal entries found. Create your first entry to get started.</p>
                                    <button class="btn-primary" onclick="openCreateModal()">
                                        <i class="fas fa-plus me-2"></i>Create Entry
                                    </button>
                                </div>
                            </td>
                        </tr>
                        @endforelse
                    </tbody>
                </table>
            </div>
            
            <!-- Pagination -->
            @if(($journalEntries->total() ?? 0) > 0)
            <div class="px-4 pb-4">
                {{ $journalEntries->links() }}
            </div>
            @endif
        </div>
    </div>

    <!-- CREATE/EDIT JOURNAL ENTRY MODAL -->
    <div class="modal fade" id="journalModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="journalModalTitle">
                        <i class="fas fa-plus-circle me-2"></i>Create Journal Entry
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="journalForm" action="/accounting/journal-entries" method="POST">
                    @csrf
                    <input type="hidden" id="journalId" name="id">
                    <div class="modal-body">
                        <div class="row mb-3">
                            <div class="col-md-4">
                                <label class="form-label">Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" id="journalDate" name="date" value="{{ date('Y-m-d') }}" required>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Reference</label>
                                <input type="text" class="form-control" id="journalReference" name="reference" placeholder="e.g., INV-001">
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">Entry Number</label>
                                <input type="text" class="form-control" id="journalEntryNumber" readonly placeholder="Auto-generated">
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-12">
                                <label class="form-label">Description <span class="text-danger">*</span></label>
                                <textarea class="form-control" id="journalDescription" name="description" rows="2" placeholder="Enter description for this journal entry" required></textarea>
                            </div>
                        </div>

                        <div class="table-responsive mb-3">
                            <table class="table table-bordered journal-items-table">
                                <thead>
                                    <tr>
                                        <th style="width: 40%">Account</th>
                                        <th style="width: 25%">Description</th>
                                        <th style="width: 15%">Debit (UGX)</th>
                                        <th style="width: 15%">Credit (UGX)</th>
                                        <th style="width: 5%"></th>
                                    </tr>
                                </thead>
                                <tbody id="journalItems">
                                    <!-- Journal items will be added here dynamically -->
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="2" class="text-end">Totals:</th>
                                        <th class="text-end amount-debit" id="totalDebit">0.00</th>
                                        <th class="text-end amount-credit" id="totalCredit">0.00</th>
                                        <th></th>
                                    </tr>
                                    <tr>
                                        <td colspan="5">
                                            <div class="d-flex justify-content-between align-items-center">
                                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="addJournalItemRow()">
                                                    <i class="fas fa-plus me-2"></i>Add Line
                                                </button>
                                                <div id="balanceStatus" class="fw-bold text-success">
                                                    <span class="badge-status success">✓ Balanced</span>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save me-2"></i>Save Journal Entry
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- VIEW JOURNAL ENTRY MODAL -->
    <div class="modal fade" id="viewJournalModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-info-circle me-2"></i>Journal Entry Details
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="viewJournalContent">
                    <!-- Content loaded dynamically -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-outline-primary" onclick="printJournalEntry()">
                        <i class="fas fa-print me-2"></i>Print
                    </button>
                    <button type="button" class="btn btn-primary" id="editFromViewBtn" onclick="editFromView()">
                        <i class="fas fa-edit me-2"></i>Edit Entry
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- TEMPLATE SELECTION MODAL -->
    <div class="modal fade" id="templateModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        <i class="fas fa-file-import me-2"></i>Select Journal Template
                    </h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="template-grid">
                        <div class="template-card" onclick="useTemplate('JE-001')">
                            <div class="template-icon">
                                <i class="fas fa-user"></i>
                            </div>
                            <h6>Walk-in Cash Check-in</h6>
                            <small>Guest checks in with cash payment</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-002')">
                            <div class="template-icon">
                                <i class="fas fa-credit-card"></i>
                            </div>
                            <h6>Walk-in Credit Check-in</h6>
                            <small>Guest checks in on account</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-003')">
                            <div class="template-icon">
                                <i class="fas fa-globe"></i>
                            </div>
                            <h6>OTA Booking</h6>
                            <small>Booking.com / Expedia reservation</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-004')">
                            <div class="template-icon">
                                <i class="fas fa-building"></i>
                            </div>
                            <h6>Corporate Rate</h6>
                            <small>Corporate client booking</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-005')">
                            <div class="template-icon">
                                <i class="fas fa-hand-holding-usd"></i>
                            </div>
                            <h6>Advance Deposit</h6>
                            <small>Pre-payment received</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-012')">
                            <div class="template-icon">
                                <i class="fas fa-utensils"></i>
                            </div>
                            <h6>Restaurant Cash Sale</h6>
                            <small>F&B cash transaction</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-017')">
                            <div class="template-icon">
                                <i class="fas fa-truck"></i>
                            </div>
                            <h6>Purchase from Supplier</h6>
                            <small>Stock purchase on credit</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-021')">
                            <div class="template-icon">
                                <i class="fas fa-users"></i>
                            </div>
                            <h6>Monthly Payroll</h6>
                            <small>Staff salaries accrual</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-025')">
                            <div class="template-icon">
                                <i class="fas fa-box"></i>
                            </div>
                            <h6>Purchase of Goods</h6>
                            <small>General supplier purchase</small>
                        </div>
                        <div class="template-card" onclick="useTemplate('JE-036')">
                            <div class="template-icon">
                                <i class="fas fa-bolt"></i>
                            </div>
                            <h6>Utility Bill</h6>
                            <small>Electricity / water bill</small>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancel</button>
                </div>
            </div>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.bundle.min.js"></script>
    <!-- DataTables -->
    <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.4/js/dataTables.bootstrap5.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

    <script>
        let currentViewId = null;
        let itemIndex = 0;
        let accounts = @json($accounts ?? []);

        $(document).ready(function() {
            // Initialize DataTable if there's data
            if ($('#journalTable tbody tr').length > 0 && !$('#journalTable tbody tr td').hasClass('text-center')) {
                $('#journalTable').DataTable({
                    paging: false,
                    searching: true,
                    ordering: true,
                    info: false,
                    columnDefs: [
                        { orderable: false, targets: [6,7] }
                    ],
                    language: {
                        search: "Search entries:"
                    }
                });
            }

            // Initialize first row in create modal
            addJournalItemRow();

            // Form submission
            $('#journalForm').on('submit', function(e) {
                e.preventDefault();
                saveJournalEntry();
            });
        });

        function applyFilters() {
            const status = $('#filterStatus').val();
            const dateFrom = $('#filterDateFrom').val();
            const dateTo = $('#filterDateTo').val();
            const accountId = $('#filterAccount').val();

            let url = '/accounting/journal-entries?';
            let params = [];
            if (status) params.push('status=' + status);
            if (dateFrom) params.push('date_from=' + dateFrom);
            if (dateTo) params.push('date_to=' + dateTo);
            if (accountId) params.push('account_id=' + accountId);
            
            window.location.href = url + params.join('&');
        }

        function openCreateModal() {
            $('#journalForm')[0].reset();
            $('#journalId').val('');
            $('#journalDate').val(new Date().toISOString().split('T')[0]);
            $('#journalItems').empty();
            itemIndex = 0;
            addJournalItemRow();
            $('#journalModalTitle').html('<i class="fas fa-plus-circle me-2"></i>Create Journal Entry');
            $('#journalModal').modal('show');
            calculateTotals();
        }

        function addJournalItemRow(item = null, index = null) {
            const rowIndex = index !== null ? index : itemIndex++;
            const accountId = item ? item.account_id : '';
            const description = item ? (item.description || '') : '';
            const debit = item ? item.debit : '';
            const credit = item ? item.credit : '';
            
            let accountOptions = '<option value="">Select Account</option>';
            
            @foreach($accounts ?? [] as $account)
                accountOptions += `<option value="{{ $account->id }}" ${accountId == {{ $account->id }} ? 'selected' : ''}>{{ $account->code }} - {{ $account->name }}</option>`;
            @endforeach
            
            const row = `
                <tr>
                    <td>
                        <select class="form-select form-select-sm" name="items[${rowIndex}][account_id]" required>
                            ${accountOptions}
                        </select>
                    </td>
                    <td>
                        <input type="text" class="form-control form-control-sm" name="items[${rowIndex}][description]" value="${description}" placeholder="Line description">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm debit-input" name="items[${rowIndex}][debit]" value="${debit}" step="0.01" min="0" placeholder="0.00" oninput="calculateTotals(); checkLine(this)">
                    </td>
                    <td>
                        <input type="number" class="form-control form-control-sm credit-input" name="items[${rowIndex}][credit]" value="${credit}" step="0.01" min="0" placeholder="0.00" oninput="calculateTotals(); checkLine(this)">
                    </td>
                    <td>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeJournalItemRow(this)">
                            <i class="fas fa-times"></i>
                        </button>
                    </td>
                </tr>
            `;
            
            $('#journalItems').append(row);
        }

        function checkLine(input) {
            const row = $(input).closest('tr');
            const debitInput = row.find('.debit-input');
            const creditInput = row.find('.credit-input');
            
            if ($(input).hasClass('debit-input') && parseFloat(debitInput.val()) > 0) {
                creditInput.val('').prop('readonly', true);
            } else if ($(input).hasClass('credit-input') && parseFloat(creditInput.val()) > 0) {
                debitInput.val('').prop('readonly', true);
            } else {
                debitInput.prop('readonly', false);
                creditInput.prop('readonly', false);
            }
        }

        function removeJournalItemRow(button) {
            if ($('#journalItems tr').length > 1) {
                $(button).closest('tr').remove();
                calculateTotals();
            } else {
                showToast('At least one line is required', 'warning');
            }
        }

        function calculateTotals() {
            let totalDebit = 0;
            let totalCredit = 0;
            
            $('.debit-input').each(function() {
                totalDebit += parseFloat($(this).val()) || 0;
            });
            
            $('.credit-input').each(function() {
                totalCredit += parseFloat($(this).val()) || 0;
            });
            
            $('#totalDebit').text(totalDebit.toFixed(2));
            $('#totalCredit').text(totalCredit.toFixed(2));
            
            const difference = Math.abs(totalDebit - totalCredit);
            
            if (Math.abs(totalDebit - totalCredit) < 0.01) {
                $('#balanceStatus').html('<span class="badge-status success">✓ Balanced</span>');
                $('button[type="submit"]').prop('disabled', false);
            } else {
                $('#balanceStatus').html('<span class="badge-status draft">⚠ Unbalanced by ' + formatCurrency(difference) + '</span>');
                $('button[type="submit"]').prop('disabled', true);
            }
        }

        function viewJournalEntry(id) {
            currentViewId = id;
            
            Swal.fire({
                title: 'Loading...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => Swal.showLoading()
            });

            fetch(`/accounting/journal-entries/${id}`)
                .then(response => response.json())
                .then(data => {
                    Swal.close();
                    
                    let totalDebit = data.items.reduce((sum, i) => sum + i.debit, 0);
                    let totalCredit = data.items.reduce((sum, i) => sum + i.credit, 0);
                    
                    let html = `
                        <div class="journal-details">
                            <div class="text-center mb-4">
                                <div class="rounded-circle p-3 d-inline-block" style="background: #e9efff;">
                                    <i class="fas fa-receipt fa-2x" style="color: #4361ee;"></i>
                                </div>
                            </div>
                            
                            <div class="row g-3 mb-3">
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Entry Number</div>
                                        <div class="detail-value">${data.entry_number}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Date</div>
                                        <div class="detail-value">${new Date(data.date).toLocaleDateString()}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Reference</div>
                                        <div class="detail-value">${data.reference || 'N/A'}</div>
                                    </div>
                                </div>
                                <div class="col-6">
                                    <div class="detail-item">
                                        <div class="detail-label">Status</div>
                                        <div class="detail-value">
                                            <span class="badge-status ${data.status}">${data.status}</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-12">
                                    <div class="detail-item">
                                        <div class="detail-label">Description</div>
                                        <div class="detail-value">${data.description}</div>
                                    </div>
                                </div>
                            </div>
                            
                            <h6 class="mb-3">Journal Items</h6>
                            <div class="table-responsive">
                                <table class="table table-sm journal-items-table">
                                    <thead>
                                        <tr>
                                            <th>Account</th>
                                            <th>Description</th>
                                            <th class="text-end">Debit</th>
                                            <th class="text-end">Credit</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                    `;
                    
                    data.items.forEach(item => {
                        html += `
                            <tr>
                                <td><strong>${item.account.code}</strong><br><small>${item.account.name}</small></td>
                                <td>${item.description || '-'}</td>
                                <td class="text-end amount-debit">${item.debit > 0 ? formatCurrency(item.debit) : '-'}</td>
                                <td class="text-end amount-credit">${item.credit > 0 ? formatCurrency(item.credit) : '-'}</td>
                            </tr>
                        `;
                    });
                    
                    html += `
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <th colspan="2" class="text-end">Totals:</th>
                                            <th class="text-end amount-debit">${formatCurrency(totalDebit)}</th>
                                            <th class="text-end amount-credit">${formatCurrency(totalCredit)}</th>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                            
                            <div class="detail-item mt-3">
                                <div class="detail-label">Created By</div>
                                <div class="detail-value">${data.created_by || 'N/A'}</div>
                            </div>
                            
                            <div class="detail-item">
                                <div class="detail-label">Created At</div>
                                <div class="detail-value">${new Date(data.created_at).toLocaleString()}</div>
                            </div>
                        </div>
                    `;
                    
                    $('#viewJournalContent').html(html);
                    $('#viewJournalModal').modal('show');
                })
                .catch(error => {
                    Swal.close();
                    showToast('Error loading journal entry', 'error');
                });
        }

        function editJournalEntry(id) {
            currentViewId = id;
            
            Swal.fire({
                title: 'Loading...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => Swal.showLoading()
            });

            fetch(`/accounting/journal-entries/${id}/edit`)
                .then(response => response.json())
                .then(data => {
                    Swal.close();
                    
                    $('#journalId').val(data.id);
                    $('#journalDate').val(data.date);
                    $('#journalDescription').val(data.description);
                    $('#journalReference').val(data.reference);
                    $('#journalEntryNumber').val(data.entry_number);
                    
                    $('#journalItems').empty();
                    itemIndex = 0;
                    
                    data.items.forEach((item, index) => {
                        addJournalItemRow(item, index);
                        itemIndex = index + 1;
                    });
                    
                    calculateTotals();
                    
                    $('#journalModalTitle').html('<i class="fas fa-edit me-2"></i>Edit Journal Entry');
                    $('#journalModal').modal('show');
                })
                .catch(error => {
                    Swal.close();
                    showToast('Error loading journal entry', 'error');
                });
        }

        function editFromView() {
            if (currentViewId) {
                $('#viewJournalModal').modal('hide');
                setTimeout(() => {
                    editJournalEntry(currentViewId);
                }, 500);
            }
        }

        function saveJournalEntry() {
            const journalId = $('#journalId').val();
            const url = journalId ? `/accounting/journal-entries/${journalId}` : '/accounting/journal-entries';
            const method = journalId ? 'PUT' : 'POST';

            // Validate at least 2 lines
            if ($('#journalItems tr').length < 2) {
                showToast('At least two journal lines are required', 'warning');
                return;
            }

            $.ajax({
                url: url,
                type: method,
                data: $('#journalForm').serialize(),
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                },
                beforeSend: function() {
                    Swal.fire({
                        title: 'Saving...',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        willOpen: () => Swal.showLoading()
                    });
                },
                success: function(response) {
                    Swal.close();
                    $('#journalModal').modal('hide');
                    showToast(journalId ? 'Journal entry updated successfully' : 'Journal entry created successfully', 'success');
                    setTimeout(() => location.reload(), 1500);
                },
                error: function(xhr) {
                    Swal.close();
                    showToast(xhr.responseJSON?.message || 'Error saving journal entry', 'error');
                }
            });
        }

        function postJournalEntry(id) {
            Swal.fire({
                title: 'Post Journal Entry',
                text: 'Are you sure you want to post this entry? This action cannot be undone.',
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#10b981',
                confirmButtonText: 'Yes, post',
                cancelButtonText: 'Cancel',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `/accounting/journal-entries/${id}/post`,
                        type: 'POST',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function() {
                            Swal.fire({
                                title: 'Posting...',
                                allowOutsideClick: false,
                                showConfirmButton: false,
                                willOpen: () => Swal.showLoading()
                            });
                        },
                        success: function(response) {
                            Swal.close();
                            showToast('Journal entry posted successfully', 'success');
                            setTimeout(() => location.reload(), 1500);
                        },
                        error: function(xhr) {
                            Swal.close();
                            showToast(xhr.responseJSON?.message || 'Error posting entry', 'error');
                        }
                    });
                }
            });
        }

        function reverseJournalEntry(id) {
            Swal.fire({
                title: 'Reverse Journal Entry',
                text: 'Enter reversal date:',
                icon: 'question',
                input: 'date',
                inputValue: new Date().toISOString().split('T')[0],
                showCancelButton: true,
                confirmButtonColor: '#f97316',
                confirmButtonText: 'Yes, reverse',
                cancelButtonText: 'Cancel',
                reverseButtons: true,
                inputValidator: (value) => {
                    if (!value) {
                        return 'Please enter a reversal date';
                    }
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `/accounting/journal-entries/${id}/reverse`,
                        type: 'POST',
                        data: { reversal_date: result.value },
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function() {
                            Swal.fire({
                                title: 'Reversing...',
                                allowOutsideClick: false,
                                showConfirmButton: false,
                                willOpen: () => Swal.showLoading()
                            });
                        },
                        success: function(response) {
                            Swal.close();
                            showToast('Journal entry reversed successfully', 'success');
                            setTimeout(() => location.reload(), 1500);
                        },
                        error: function(xhr) {
                            Swal.close();
                            showToast(xhr.responseJSON?.message || 'Error reversing entry', 'error');
                        }
                    });
                }
            });
        }

        function deleteJournalEntry(id) {
            Swal.fire({
                title: 'Delete Journal Entry',
                text: 'Are you sure you want to delete this entry? This action cannot be undone.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#ef4444',
                confirmButtonText: 'Yes, delete',
                cancelButtonText: 'Cancel',
                reverseButtons: true
            }).then((result) => {
                if (result.isConfirmed) {
                    $.ajax({
                        url: `/accounting/journal-entries/${id}`,
                        type: 'DELETE',
                        headers: {
                            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                        },
                        beforeSend: function() {
                            Swal.fire({
                                title: 'Deleting...',
                                allowOutsideClick: false,
                                showConfirmButton: false,
                                willOpen: () => Swal.showLoading()
                            });
                        },
                        success: function(response) {
                            Swal.close();
                            showToast('Journal entry deleted successfully', 'success');
                            setTimeout(() => location.reload(), 1500);
                        },
                        error: function(xhr) {
                            Swal.close();
                            showToast(xhr.responseJSON?.message || 'Error deleting entry', 'error');
                        }
                    });
                }
            });
        }

        function openTemplateModal() {
            $('#templateModal').modal('show');
        }

        function useTemplate(templateId) {
            $('#templateModal').modal('hide');
            
            Swal.fire({
                title: 'Using Template',
                text: 'Creating journal entry from template...',
                allowOutsideClick: false,
                showConfirmButton: false,
                willOpen: () => Swal.showLoading()
            });

            // Simulate template loading - replace with actual API call
            setTimeout(() => {
                Swal.close();
                openCreateModal();
                showToast('Template loaded successfully', 'success');
            }, 1000);
        }

        function formatCurrency(amount) {
            return 'UGX ' + new Intl.NumberFormat('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }).format(amount || 0);
        }

        function showToast(message, type) {
            const Toast = Swal.mixin({
                toast: true,
                position: 'top-end',
                showConfirmButton: false,
                timer: 3000,
                timerProgressBar: true,
                didOpen: (toast) => {
                    toast.addEventListener('mouseenter', Swal.stopTimer);
                    toast.addEventListener('mouseleave', Swal.resumeTimer);
                }
            });

            Toast.fire({
                icon: type,
                title: message
            });
        }

        function printJournalEntry() {
            const printContent = $('#viewJournalContent').html();
            const originalContent = $('body').html();

            $('body').html(`
                <div class="container py-4">
                    <h2 class="text-center mb-4">Journal Entry</h2>
                    ${printContent}
                </div>
            `);

            window.print();
            location.reload();
        }
    </script>
</body>
</html>