

<?php $__env->startSection('title', 'Account Transactions - ' . $account->name); ?>

<?php $__env->startPush('plugin-styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/sweetalert2/sweetalert2.min.css')); ?>">
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <div class="d-flex justify-content-between align-items-center">
                    <h5 class="card-title mb-0">Account: <?php echo e($account->name); ?></h5>
                    <a href="<?php echo e(route('accounts.index')); ?>" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left me-2"></i>Back to Accounts
                    </a>
                </div>
            </div>
            <div class="card-body">
                <!-- Account Summary -->
                <div class="row mb-4">
                    <div class="col-md-4">
                        <div class="card bg-light">
                            <div class="card-body text-center">
                                <h6 class="card-title">Account Type</h6>
                                <span class="badge bg-primary"><?php echo e(ucfirst($account->model_type)); ?></span>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-md-4">
                        <div class="card bg-light">
                            <div class="card-body text-center">
                                <h6 class="card-title">
                                    <?php if(in_array($account->model_type, ['supplier', 'employee', 'shop_employee', 'shop_manager'])): ?>
                                        Outstanding Payables
                                    <?php else: ?>
                                        Outstanding Receivables
                                    <?php endif; ?>
                                </h6>
                                <h4 class="
                                    <?php if($account->balance > 0): ?>
                                        <?php if(in_array($account->model_type, ['supplier', 'employee', 'shop_employee', 'shop_manager'])): ?>
                                            text-danger  
                                        <?php else: ?>
                                            text-success 
                                        <?php endif; ?>
                                    <?php elseif($account->balance < 0): ?>
                                        <?php if(in_array($account->model_type, ['supplier', 'employee', 'shop_employee', 'shop_manager'])): ?>
                                            text-success 
                                        <?php else: ?>
                                            text-danger  
                                        <?php endif; ?>
                                    <?php else: ?>
                                        text-muted 
                                    <?php endif; ?>
                                ">
                                    <?php if($account->balance != 0): ?>
                                        <?php echo e(format_currency(abs($account->balance))); ?>

                                    <?php else: ?>
                                        <?php echo e(format_currency(0)); ?>

                                    <?php endif; ?>
                                </h4>
                                <?php if(in_array($account->model_type, ['supplier', 'employee', 'shop_employee', 'shop_manager'])): ?>
                                    <small class="text-muted">
                                        <?php if($account->balance > 0): ?>
                                            You owe this amount
                                        <?php elseif($account->balance < 0): ?>
                                            They owe you <?php echo e(format_currency(abs($account->balance))); ?>

                                        <?php else: ?>
                                            No outstanding amounts
                                        <?php endif; ?>
                                    </small>
                                <?php else: ?>
                                    <small class="text-muted">
                                        <?php if($account->balance > 0): ?>
                                            Amount due from <?php echo e(ucfirst($account->model_type)); ?>

                                        <?php elseif($account->balance < 0): ?>
                                            You owe this <?php echo e(ucfirst($account->model_type)); ?> <?php echo e(format_currency(abs($account->balance))); ?>

                                        <?php else: ?>
                                            No outstanding amounts
                                        <?php endif; ?>
                                    </small>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Action Buttons -->
                <div class="d-flex gap-2 mb-3">
                    <?php if(in_array($account->model_type, ['supplier', 'employee', 'shop_employee', 'shop_manager'])): ?>
                        <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#paymentModal">
                            <i class="fas fa-money-bill-wave me-2"></i>Make Payment
                        </button>
                    <?php else: ?>
                        <button type="button" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#receiptModal">
                            <i class="fas fa-hand-holding-usd me-2"></i>Receive Payment
                        </button>
                    <?php endif; ?>
                </div>

                <!-- Filters -->
                <div class="accordion mb-3" id="transactionFilterAccordion">
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="transactionFilterHeading">
                            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#transactionFilterCollapse" aria-expanded="false" aria-controls="transactionFilterCollapse">
                                Filters
                            </button>
                        </h2>
                        <div id="transactionFilterCollapse" class="accordion-collapse collapse" aria-labelledby="transactionFilterHeading" data-bs-parent="#transactionFilterAccordion">
                            <div class="accordion-body">
                                <div class="row g-3 align-items-end">
                                    <div class="col-md-3">
                                        <label class="form-label">Transaction Type</label>
                                        <select id="filterTransactionType" class="form-select">
                                            <option value="">All Types</option>
                                            <option value="debit">Debit</option>
                                            <option value="credit">Credit</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Reference Type</label>
                                        <select id="filterReferenceType" class="form-select">
                                            <option value="">All References</option>
                                            <option value="FactoryInvoice">Factory Invoice</option>
                                            <option value="PurchaseOrder">Purchase Order</option>
                                            <option value="Qc">QC</option>
                                            <option value="Payroll">Payroll</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">Date Range</label>
                                        <input id="filterDateRange" class="form-control" placeholder="YYYY-MM-DD to YYYY-MM-DD">
                                    </div>
                                </div>
                                <div class="mt-3 d-flex gap-2">
                                    <button type="button" class="btn btn-primary" id="btnApplyFilters">
                                        <i class="fas fa-search me-2"></i>
                                        Apply Filters
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary" id="btnResetFilters">
                                        <i class="fas fa-times me-2"></i>
                                        Clear Filters
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Transactions Table -->
                <div class="table-responsive">
                        <table class="table table-hover" id="accountTransactionsTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Chart of Account</th>
                                    <th>Amount</th>
                                    <th>Type</th>
                                    <th>Reference</th>
                                </tr>
                            </thead>
                        </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Payment Modal -->
<div class="modal fade" id="paymentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Make Payment to <?php echo e($account->name); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="paymentForm">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Payment Type</label>
                            <select class="form-select" id="paymentType" name="payment_type" required>
                                <option value="">Select Payment Type</option>
                                <?php if($account->model_type === 'supplier'): ?>
                                    <option value="purchase_order">Purchase Order</option>
                                    <option value="qc">QC</option>
                                <?php elseif(in_array($account->model_type, ['employee', 'shop_employee', 'shop_manager'])): ?>
                                    <option value="payroll">Payroll</option>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Reference</label>
                            <select class="form-select" id="paymentReference" name="reference_id" required disabled>
                                <option value="">Select Reference</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Amount</label>
                            <input type="number" class="form-control" id="paymentAmount" name="amount" step="0.01" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Payment Method</label>
                            <select class="form-select" id="paymentMethod" name="payment_method" required>
                                <option value="">Select Method</option>
                                <option value="cash">Cash</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="cheque">Cheque</option>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" id="paymentNotes" name="notes" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-success" id="submitPayment">Process Payment</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Receipt Modal -->
<div class="modal fade" id="receiptModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Receive Payment from <?php echo e($account->name); ?></h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="receiptForm">
                <div class="modal-body">
                    <div class="row g-3">
                        <div class="col-md-6">
                            <label class="form-label">Receipt Type</label>
                            <select class="form-select" id="receiptType" name="receipt_type" required>
                                <option value="">Select Receipt Type</option>
                                <?php if(in_array($account->model_type, ['customer', 'shop', 'distributor'])): ?>
                                    <option value="factory_invoice">Factory Invoice</option>
                                <?php endif; ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Reference</label>
                            <select class="form-select" id="receiptReference" name="reference_id" required disabled>
                                <option value="">Select Reference</option>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Amount</label>
                            <input type="number" class="form-control" id="receiptAmount" name="amount" step="0.01" required>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Payment Method</label>
                            <select class="form-select" id="receiptMethod" name="payment_method" required>
                                <option value="">Select Method</option>
                                <option value="cash">Cash</option>
                                <option value="bank_transfer">Bank Transfer</option>
                                <option value="cheque">Cheque</option>
                            </select>
                        </div>
                        <div class="col-12">
                            <label class="form-label">Notes</label>
                            <textarea class="form-control" id="receiptNotes" name="notes" rows="3"></textarea>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-info" id="submitReceipt">Process Receipt</button>
                </div>
            </form>
        </div>
    </div>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('plugin-scripts'); ?>
<script src="<?php echo e(asset('theme/vendors/jquery/jquery.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net/dataTables.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/datatables.net-bs5/dataTables.bootstrap5.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/sweetalert2/sweetalert2.min.js')); ?>"></script>
<script>
$(document).ready(function() {
    // Initialize date range picker
    flatpickr('#filterDateRange', { mode: 'range', dateFormat: 'Y-m-d' });

    // Initialize DataTable
    var table = $('#accountTransactionsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?php echo e(route("accounts.transactions", $account)); ?>',
            data: function(d) {
                d.transaction_type = $('#filterTransactionType').val();
                d.reference_type = $('#filterReferenceType').val();

                const dr = document.getElementById('filterDateRange').value;
                if (dr && dr.includes(' to ')) {
                    const parts = dr.split(' to ');
                    d.date_from = parts[0];
                    d.date_to = parts[1];
                }
            }
        },
        columns: [
            {data: 'created_at', name: 'created_at'},
            {data: 'chart_of_account_name', name: 'chart_of_account_name'},
            {data: 'amount', name: 'amount'},
            {data: 'transaction_type', name: 'transaction_type'},
            {data: 'reference_name', name: 'reference_name'}
        ],
        order: [[0, 'desc']],
        pageLength: 25
    });

    // Filter event handlers
    $('#btnApplyFilters, #filterTransactionType, #filterReferenceType').on('click change', function(){
        table.draw();
    });

    $('#btnResetFilters').on('click', function(){
        $('#filterTransactionType').val('');
        $('#filterReferenceType').val('');
        document.getElementById('filterDateRange').value = '';
        table.draw();
    });

    // Payment Modal Logic
    $('#paymentType').on('change', function() {
        const paymentType = $(this).val();
        const referenceSelect = $('#paymentReference');

        if (paymentType) {
            referenceSelect.prop('disabled', false);
            loadReferences(paymentType, referenceSelect, '<?php echo e($account->id); ?>');
        } else {
            referenceSelect.prop('disabled', true).html('<option value="">Select Reference</option>');
        }
    });

    $('#receiptType').on('change', function() {
        const receiptType = $(this).val();
        const referenceSelect = $('#receiptReference');

        if (receiptType) {
            referenceSelect.prop('disabled', false);
            loadReferences(receiptType, referenceSelect, '<?php echo e($account->id); ?>');
        } else {
            referenceSelect.prop('disabled', true).html('<option value="">Select Reference</option>');
        }
    });

    function loadReferences(type, selectElement, accountId) {
        selectElement.html('<option value="">Loading...</option>');

        $.ajax({
            url: '/api/get-references',
            method: 'GET',
            data: { type: type, account_id: accountId },
            success: function(data) {
                let options = '<option value="">Select Reference</option>';
                data.forEach(function(item) {
                    options += `<option value="${item.id}">${item.name}</option>`;
                });
                selectElement.html(options);
            },
            error: function() {
                selectElement.html('<option value="">Error loading references</option>');
            }
        });
    }

    // Payment Form Submission
    $('#paymentForm').on('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        formData.append('account_id', '<?php echo e($account->id); ?>');

        $.ajax({
            url: '/api/process-payment',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                $('#paymentModal').modal('hide');
                table.draw();
                Swal.fire('Success', 'Payment processed successfully', 'success');
                location.reload(); // Reload to update balance
            },
            error: function(xhr) {
                Swal.fire('Error', xhr.responseJSON?.message || 'Failed to process payment', 'error');
            }
        });
    });

    // Receipt Form Submission
    $('#receiptForm').on('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        formData.append('account_id', '<?php echo e($account->id); ?>');

        $.ajax({
            url: '/api/process-receipt',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                $('#receiptModal').modal('hide');
                table.draw();
                Swal.fire('Success', 'Receipt processed successfully', 'success');
                location.reload(); // Reload to update balance
            },
            error: function(xhr) {
                Swal.fire('Error', xhr.responseJSON?.message || 'Failed to process receipt', 'error');
            }
        });
    });
});
</script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\laragon\www\habibcables-ERP\resources\views\account_transactions\for_account.blade.php ENDPATH**/ ?>