<?php $__env->startSection('content'); ?>
<div class="container-fluid py-3">
    <div class="row">
        <!-- Form Section -->
        <div class="col-lg-4">
            <div class="card shadow-sm mb-4">
                <div class="card-header bg-success text-white py-3">
                    <h5 class="mb-0" id="formTitle"><i class="fas fa-cash-register me-2"></i> Process Cashbook Entry</h5>
                </div>
                <div class="card-body">
                    <form action="<?php echo e(route('accounts.cashbook.store')); ?>" method="POST" id="cashbookForm">
                        <?php echo csrf_field(); ?>
                        <input type="hidden" name="id" id="entryId" value="">

                        <div id="timeout">
                            <?php if(Session::has('success')): ?>
                                <p class="alert alert-info"><?php echo e(Session('success')); ?></p>
                            <?php endif; ?>
                            <?php if(Session::has('error')): ?>
                                <p class="alert alert-danger"><?php echo e(Session('error')); ?></p>
                            <?php endif; ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Cashbook:</strong></label>
                            <select name="cashbook_id" id="cashbook_id" class="form-control" required>
                                <option value="">Select Cashbook</option>
                                <?php $__currentLoopData = $cashbooks; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $cashbook): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($cashbook->id); ?>" <?php echo e(old('cashbook_id') == $cashbook->id ? 'selected' : ''); ?>>
                                        <?php echo e($cashbook->code); ?> - <?php echo e($cashbook->description); ?>

                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                            <?php $__errorArgs = ['cashbook_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Date:</strong></label>
                            <input type="date" name="date" class="form-control"
                                   value="<?php echo e(old('date', date('Y-m-d'))); ?>" id="date" required>
                            <?php $__errorArgs = ['date'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Module:</strong></label>
                            <select name="module" id="module" class="form-control" required>
                                <option value="">Select Module</option>
                                <option value="GL" <?php echo e(old('module') == 'GL' ? 'selected' : ''); ?>>General Ledger (GL)</option>
                                <option value="AR" <?php echo e(old('module') == 'AR' ? 'selected' : ''); ?>>Accounts Receivable (AR)</option>
                                <option value="AP" <?php echo e(old('module') == 'AP' ? 'selected' : ''); ?>>Accounts Payable (AP)</option>
                            </select>
                            <?php $__errorArgs = ['module'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Account:</strong></label>
                            <select name="account" id="account" class="form-control" required <?php echo e(old('module') ? '' : 'disabled'); ?>>
                                <option value="">Select Account</option>
                            </select>
                            <?php $__errorArgs = ['account'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Reference:</strong></label>
                            <select name="reference" id="reference" class="form-control" <?php echo e(old('module') == 'GL' || !old('module') ? 'disabled' : ''); ?>>
                                <option value="">Select Reference</option>
                            </select>
                            <small class="text-muted">Only available for AR/AP modules</small>
                            <?php $__errorArgs = ['reference'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Description:</strong></label>
                            <input type="text" name="description" class="form-control" id="description"
                                   placeholder="Enter description" value="<?php echo e(old('description')); ?>" required>
                            <?php $__errorArgs = ['description'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>TR Code:</strong></label>
                            <select name="tr_code" class="form-control" id="tr_code" required>
                                <option value="">Select TR Code</option>
                                <option value="Receipt" <?php echo e(old('tr_code') == 'Receipt' ? 'selected' : ''); ?>>Receipt</option>
                                <option value="Payment" <?php echo e(old('tr_code') == 'Payment' ? 'selected' : ''); ?>>Payment</option>
                            </select>
                            <?php $__errorArgs = ['tr_code'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Currency:</strong></label>
                            <select name="currency_id" class="form-control" id="currency_id" required>
                                <?php $__currentLoopData = $currencies; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $currency): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($currency->id); ?>" <?php echo e(old('currency_id') == $currency->id ? 'selected' : ''); ?>>
                                        <?php echo e($currency->code); ?> - <?php echo e($currency->name); ?>

                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                            <?php $__errorArgs = ['currency_id'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="mb-3">
                            <label class="form-label"><strong>Amount:</strong></label>
                            <input type="number" step="0.01" name="amount" class="form-control" id="amount"
                                   placeholder="00.00" value="<?php echo e(old('amount')); ?>" required>
                            <?php $__errorArgs = ['amount'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                <small class="text-danger"><?php echo e($message); ?></small>
                            <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                        </div>

                        <div class="d-flex justify-content-end mt-4">
                            <button type="submit" id="submitButton" class="btn btn-success me-2">Save</button>
                            <button type="reset" class="btn btn-outline-secondary" id="resetButton">Refresh</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Table Section -->
        <div class="col-lg-8 mt-4 mt-lg-0">
            <div class="card shadow-sm">
                <div class="card-header bg-success text-white py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-list me-2"></i> Cashbook Entries</h5>
                    <?php if($tempEntries->isNotEmpty()): ?>
                        <form action="<?php echo e(route('accounts.cashbook.process')); ?>" method="POST" class="m-0">
                            <?php echo csrf_field(); ?>
                            <button type="submit" id="processCashbookBtn" class="btn btn-success btn-sm">PROCESS ALL</button>
                        </form>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <?php if($tempEntries->isEmpty()): ?>
                        <p class="text-muted mb-0">No cashbook entries available.</p>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-bordered table-hover">
                                <thead class="table-light">
                                    <tr>
                                        <th>Cashbook</th>
                                        <th>Date</th>
                                        <th>Module</th>
                                        <th>Account</th>
                                        <th>Description</th>
                                        <th>Receipt</th>
                                        <th>Payment</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php $__currentLoopData = $tempEntries; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $entry): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <tr>
                                        <td>
                                            <?php
                                                $cashbook = \App\Models\Cashbook::find($entry->cashbook_id);
                                                echo $cashbook ? $cashbook->code : 'N/A';
                                            ?>
                                        </td>
                                        <td><?php echo e(date('d/m/Y', strtotime($entry->date))); ?></td>
                                        <td><?php echo e($entry->module); ?></td>
                                        <td>
                                            <?php if($entry->account_code && $entry->account_name): ?>
                                                <span class="badge"
                                                    style="background-color: #e9f5e9; color: #198754; font-size: 0.9rem; padding: 5px 10px;">
                                                    <?php echo e($entry->account_code); ?> - <?php echo e($entry->account_name); ?>

                                                </span>
                                                <small class="d-block text-muted ms-1"><?php echo e($entry->module); ?></small>
                                            <?php else: ?>
                                                <span class="badge bg-secondary">N/A</span>
                                            <?php endif; ?>
                                        </td>
                                        <td><?php echo e($entry->description); ?></td>
                                        <td class="text-end"><?php echo e($entry->tr_code === 'Receipt' ? number_format($entry->amount, 2) : '0.00'); ?></td>
                                        <td class="text-end"><?php echo e($entry->tr_code === 'Payment' ? number_format($entry->amount, 2) : '0.00'); ?></td>
                                        <td>
                                            <?php if($entry->status === 'Processed'): ?>
                                                <span class="badge bg-success">Processed</span>
                                            <?php else: ?>
                                                <span class="badge bg-warning text-dark">Pending</span>
                                            <?php endif; ?>
                                        </td>
                                        <td class="text-center">
                                            <a href="#" class="btn btn-sm btn-success" onclick="editEntry(<?php echo e($entry->id); ?>)">
                                                <i class="fas fa-edit"></i>
                                            </a>

                                            <!-- Process single entry -->
                                            <?php if($entry->status !== 'Processed'): ?>
                                            <form action="<?php echo e(route('accounts.cashbook.process-single', $entry->id)); ?>" method="POST" class="d-inline">
                                                <?php echo csrf_field(); ?>
                                                <button type="submit" class="btn btn-sm btn-success process-btn">
                                                    <i class="fas fa-check"></i>
                                                </button>
                                            </form>
                                            <?php endif; ?>

                                            <!-- Delete button triggers modal -->
                                            <button class="btn btn-sm btn-danger deleteBtn" data-id="<?php echo e($entry->id); ?>">
                                                <i class="fas fa-trash-alt"></i>
                                            </button>
                                        </td>
                                    </tr>
                                    <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Delete Modal -->
<div class="modal fade" id="deleteConfirmModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <form method="POST" id="deleteForm">
            <?php echo csrf_field(); ?>
            <?php echo method_field('DELETE'); ?>
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title">Confirm Deletion</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">Are you sure you want to delete this cashbook entry?</div>
                <div class="modal-footer">
                    <button id="cancelDeleteBtn" type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button id="confirmDeleteBtn" type="submit" class="btn btn-danger">Delete</button>
                </div>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const moduleSelect = document.getElementById('module');
    const accountSelect = document.getElementById('account');
    const referenceSelect = document.getElementById('reference');

    // Handle module change
    moduleSelect.addEventListener('change', function() {
        if (!this.value) {
            accountSelect.disabled = true;
            referenceSelect.disabled = true;
            accountSelect.innerHTML = '<option value="">Select Account</option>';
            referenceSelect.innerHTML = '<option value="">Select Reference</option>';
            return;
        }

        // Enable account dropdown and load accounts
        accountSelect.disabled = false;
        fetchAccounts(this.value);

        // Handle reference dropdown
        if (this.value === 'GL') {
            referenceSelect.disabled = true;
            referenceSelect.value = '';
        } else {
            referenceSelect.disabled = false;
        }
    });

    // Handle account change for AR/AP
    accountSelect.addEventListener('change', function() {
        if (moduleSelect.value !== 'GL' && this.value) {
            fetchReferences(moduleSelect.value, this.value);
        }
    });

    function fetchAccounts(module) {
fetch("<?php echo e(route('accounts.cashbook.accounts')); ?>", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({ module: module })
        })
        .then(response => {
            if (!response.ok) throw new Error('Failed to load accounts');
            return response.json();
        })
        .then(data => {
            accountSelect.innerHTML = '<option value="">Select Account</option>';
            data.forEach(account => {
                const option = document.createElement('option');
                option.value = account.id;
                option.textContent = account.text;
                if ("<?php echo e(old('account')); ?>" == account.id) {
                    option.selected = true;
                }
                accountSelect.appendChild(option);
            });
        })
        .catch(err => {
            alert(err.message);
        });
    }

    function fetchReferences(module, accountId) {
fetch("<?php echo e(route('accounts.cashbook.references')); ?>", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: JSON.stringify({
                module: module,
                account_id: accountId
            })
        })
        .then(response => {
            if (!response.ok) throw new Error('Failed to load references');
            return response.json();
        })
        .then(data => {
            referenceSelect.innerHTML = '<option value="">Select Reference</option>';
            data.forEach(ref => {
                const option = document.createElement('option');
                option.value = ref.id;
                option.textContent = ref.text;
                if ("<?php echo e(old('reference')); ?>" == ref.id) {
                    option.selected = true;
                }
                referenceSelect.appendChild(option);
            });
        })
        .catch(err => {
            alert(err.message);
        });
    }

    // Auto-fetch accounts on reload if old value exists
    if (moduleSelect.value) {
        fetchAccounts(moduleSelect.value);
    }

    // Delete modal functionality
    const bsModal = new bootstrap.Modal(document.getElementById('deleteConfirmModal'));
    const deleteForm = document.getElementById('deleteForm');

    document.querySelectorAll('.deleteBtn').forEach(btn => {
        btn.addEventListener('click', function (e) {
            e.preventDefault();
            const entryId = this.getAttribute('data-id');
            const url = '<?php echo e(url("accounts/cashbook/delete")); ?>/' + entryId;
            deleteForm.setAttribute('action', url);
            bsModal.show();
        });
    });

    // Auto-dismiss alerts after 5 seconds
    const alerts = document.querySelectorAll('.alert-dismissible, .alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            if (alert.classList.contains('alert-dismissible')) {
                let bsAlert = new bootstrap.Alert(alert);
                bsAlert.close();
            } else {
                alert.style.display = 'none';
            }
        }, 5000);
    });
});

function editEntry(id) {
    fetch('<?php echo e(url("accounts/cashbook/edit")); ?>/' + id)
        .then(response => {
            if (!response.ok) throw new Error('Failed to fetch entry data');
            return response.json();
        })
        .then(entry => {
            document.getElementById('entryId').value = entry.id;
            document.getElementById('cashbook_id').value = entry.cashbook_id;
            document.getElementById('date').value = entry.date;
            document.getElementById('module').value = entry.module;

            // Trigger module change to load accounts
            document.getElementById('module').dispatchEvent(new Event('change'));

            // Set account after a delay to allow accounts to load
            setTimeout(() => {
                const accountPrefix = entry.module === 'GL' ? 'gl_' :
                                    (entry.module === 'AR' ? 'cust_' : 'supp_');
                document.getElementById('account').value = accountPrefix + entry.account_id;

                // Trigger account change for AR/AP to load references
                if (entry.module !== 'GL') {
                    document.getElementById('account').dispatchEvent(new Event('change'));

                    // Set reference after a delay to allow references to load
                    setTimeout(() => {
                        const refPrefix = entry.module === 'AR' ? 'inv_' : 'sup_inv_';
                        if (entry.reference_id) {
                            document.getElementById('reference').value = refPrefix + entry.reference_id;
                        }
                    }, 500);
                }
            }, 500);

            document.getElementById('description').value = entry.description;
            document.getElementById('tr_code').value = entry.tr_code;
            document.getElementById('currency_id').value = entry.currency_id;
            document.getElementById('project_id').value = entry.project_id;
            document.getElementById('amount').value = entry.amount;

            document.getElementById('formTitle').innerHTML = '<i class="fas fa-cash-register me-2"></i> Edit Cashbook Entry';
            document.getElementById('submitButton').textContent = 'Update';
            document.getElementById('cashbookForm').action = '<?php echo e(route("accounts.cashbook.update")); ?>';

            window.scrollTo({ top: 0, behavior: 'smooth' });
        })
        .catch(err => {
            alert('Error loading entry: ' + err.message);
        });
}

document.getElementById('resetButton').addEventListener('click', function() {
    document.getElementById('entryId').value = '';
    document.getElementById('formTitle').innerHTML = '<i class="fas fa-cash-register me-2"></i> Process Cashbook Entry';
    document.getElementById('submitButton').textContent = 'Save';
    document.getElementById('cashbookForm').action = '<?php echo e(route("accounts.cashbook.store")); ?>';
});
</script>

<style>
.btn-back {
    text-decoration: none;
color: #198754;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    padding: 5px 15px;
    border-radius: 4px;
    transition: all 0.3s;
}
.btn-back:hover {
background-color: rgba(25, 135, 84, 0.1);
    text-decoration: none;
}
.card {
    border-radius: 8px;
    overflow: hidden;
    border: none;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.1);
}
.card-header {
    border-bottom: 1px solid rgba(0,0,0,0.1);
    padding: 12px 20px;
}
.table th {
    background-color: #f8f9fa;
}

#processCashbookBtn {
    background-color: #ffffff !important;
    color: #198754 !important;
    border: 1px solid rgba(25,135,84,0.35) !important;
    font-weight: 600 !important;
    padding: 7px 14px !important;
    box-shadow: none !important;
    line-height: 1 !important;
}

#processCashbookBtn:hover {
    background-color: #f5fbfc !important;
    color: #166534 !important;
    border-color: rgba(16,101,52,0.45) !important;
}

.table .process-btn {
    background-color: #198754 !important;
    border: 1px solid rgba(25,135,84,0.35) !important;
    color: #fff !important;
}

.table .process-btn:hover {
    background-color: #166534 !important;
    border-color: rgba(16,101,52,0.45) !important;
}
.table-responsive {
    overflow-x: auto;
    -webkit-overflow-scrolling: touch;
}

@media (max-width: 768px) {
    table.table {
        font-size: 0.85rem;
    }
    table.table th,
    table.table td {
        white-space: nowrap;
    }
}

.text-danger.small {
    font-size: 0.85rem;
}
</style>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\odza\one\melcredora\resources\views/accounts/cashbook/index.blade.php ENDPATH**/ ?>