
<?php $__env->startSection('title', 'Contact Transactions - ' . $contact->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/select2/select2.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.css')); ?>">
<style>
.select2-container--bootstrap-5{
    width: 100% !important;
}
</style>
<?php $__env->stopPush(); ?>

<?php $__env->startSection('content'); ?>
<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
    <div>
        <h4 class="mb-3 mb-md-0">Contact Transactions</h4>
        <p class="text-muted mb-0">
            <strong><?php echo e($contact->name); ?></strong>
            <?php if($contact->phone): ?>
                <span class="ms-3"><i class="fas fa-phone text-primary me-1"></i><?php echo e($contact->phone); ?></span>
            <?php endif; ?>
            <span class="ms-3"><i class="fas fa-building text-info me-1"></i><?php echo e($contact->shop->name ?? 'N/A'); ?></span>
        </p>
        <div class="mt-2">
            <div class="row g-3">
                <?php if($financialSummary['outstanding_amount'] > 0): ?>
                    <div class="col-auto">
                        <?php if($financialSummary['outstanding_type'] === 'receive'): ?>
                            <div class="badge bg-success fs-6 px-3 py-2">
                                <i class="fas fa-arrow-up me-1"></i>
                                To Receive: Rs. <?php echo e(number_format($financialSummary['outstanding_amount'], 2)); ?>

                            </div>
                        <?php elseif($financialSummary['outstanding_type'] === 'pay'): ?>
                            <div class="badge bg-danger fs-6 px-3 py-2">
                                <i class="fas fa-arrow-down me-1"></i>
                                To Pay: Rs. <?php echo e(number_format($financialSummary['outstanding_amount'], 2)); ?>

                            </div>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <?php if($financialSummary['outstanding_amount'] > 0): ?>
                <div class="col-auto">
                    <small class="text-muted">
                        <strong><?php echo e($financialSummary['outstanding_label']); ?>: Rs. <?php echo e(number_format($financialSummary['outstanding_amount'], 2)); ?></strong>
                    </small>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <div class="d-flex align-items-center flex-wrap text-nowrap">
        
        <a href="<?php echo e(route('shop.dashboard')); ?>" class="btn btn-outline-secondary btn-icon-text mb-2 mb-md-0 me-2">
            <i class="btn-icon-prepend" data-feather="bar-chart"></i>
            Dashboard
        </a>
        
        
    </div>
</div>

<div class="accordion mb-3" id="contactTransactionFilterAccordion">
    <div class="accordion-item">
        <h2 class="accordion-header" id="contactTransactionFilterHeading">
            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#contactTransactionFilterCollapse" aria-expanded="false" aria-controls="contactTransactionFilterCollapse">
                Filters
            </button>
        </h2>
        <div id="contactTransactionFilterCollapse" class="accordion-collapse collapse" aria-labelledby="contactTransactionFilterHeading" data-bs-parent="#contactTransactionFilterAccordion">
            <div class="accordion-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Transaction Type</label>
                        <select id="filterTransactionType" class="form-select">
                            <option value="all">All Transactions</option>
                            <?php $__currentLoopData = $transactionTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($key); ?>"><?php echo e($label); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Reference Type</label>
                        <select id="filterReferenceType" class="form-select">
                            <option value="all">All Types</option>
                            <?php $__currentLoopData = $referenceTypes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $key => $label): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($key); ?>"><?php echo e($label); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select id="filterStatus" class="form-select">
                            <option value="">All Status</option>
                            <option value="paid">Paid (Payments Made)</option>
                            <option value="received">Received (Payments Received)</option>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Search</label>
                        <input type="text" class="form-control" id="filterSearch" placeholder="Search transactions...">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Start Date</label>
                        <input type="text" class="form-control" id="filterStartDate" placeholder="Start Date">
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">End Date</label>
                        <input type="text" class="form-control" id="filterEndDate" placeholder="End Date">
                    </div>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-primary" id="applyFilters">
                        <i class="fas fa-search me-2"></i>
                        Apply Filters
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="clearFilters">
                        <i class="fas fa-times me-2"></i>
                        Clear Filters
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="card-title mb-0">Transaction History</h6>
            <div class="text-muted small">
                Total transactions shown below
            </div>
        </div>

        <?php if(session('success')): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo e(session('success')); ?>

                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if(session('error')): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?php echo e(session('error')); ?>

                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="table-responsive">
            <table id="contact-transactions-table" class="table table-hover">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Transaction Code</th>
                        <th>Shop</th>
                        <th>Reference Type</th>
                        <th>Reference Code</th>
                        <th>Type</th>
                        <th>Amount</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Include modal partials -->
<?php echo $__env->make('modals.contact-info', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php echo $__env->make('modals.invoice-info', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php echo $__env->make('modals.goods-receipt-info', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php echo $__env->make('modals.invoice-return-info', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>

<?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>

<!-- Bootstrap JS for modals -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize feather icons
    feather.replace();

    // Check if table exists
    if ($('#contact-transactions-table').length === 0) {
        console.error('Contact transactions table not found!');
        return;
    }

    // Initialize DataTable
    const table = new DataTable('#contact-transactions-table', {
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?php echo e(route("shop.contact.transactions.data", $contactCode)); ?>',
            type: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            },
            data: function(d) {
                d.transaction_type = $('#filterTransactionType').val();
                d.reference_type = $('#filterReferenceType').val();
                d.status = $('#filterStatus').val();
                d.search = $('#filterSearch').val();
                d.start_date = $('#filterStartDate').val();
                d.end_date = $('#filterEndDate').val();
            },
            error: function(xhr, error, thrown) {
                console.error('DataTable AJAX Error:', xhr.status, xhr.responseText);
                // Show user-friendly error message
                $('#contact-transactions-table tbody').html('<tr><td colspan="6" class="text-center text-danger">Error loading data. Please try again.</td></tr>');
            }
        },
        columns: [
            { data: 'id', orderable: true },
            { data: 'code', orderable: true },
            { data: 'shop_name', orderable: false },
            { data: 'reference_type_label', orderable: false },
            { data: 'reference_code_link', orderable: false },
            { data: 'transaction_type_label', orderable: false },
            { data: 'formatted_amount', orderable: false, className: 'text-right' },
            {
                data: 'local_db_created_at',
                name: 'local_db_created_at',
                render: function(data, type, row) {
                    if (type === 'display' && data) {
                        return new Date(data).toLocaleDateString('en-US', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit'
                        });
                    }
                    return data;
                }
            },
            { data: 'actions', orderable: false, searchable: false, className: 'text-center' }
        ],
        order: [[0, 'desc']],
        pageLength: 25,
        responsive: true,
        language: {
            processing: '<div class="text-center"><div class="spinner-border" role="status"><span class="visually-hidden">Loading...</span></div></div>'
        }
    });

    // Initialize date pickers
    $('#filterStartDate').flatpickr({
        dateFormat: 'Y-m-d',
        allowInput: true
    });

    $('#filterEndDate').flatpickr({
        dateFormat: 'Y-m-d',
        allowInput: true
    });

    // Apply filters
    $('#applyFilters').on('click', function() {
        table.ajax.reload();
    });

    // Clear filters
    $('#clearFilters').on('click', function() {
        $('#filterTransactionType').val('all');
        $('#filterReferenceType').val('all');
        $('#filterStatus').val('');
        $('#filterSearch').val('');
        $('#filterStartDate').val('');
        $('#filterEndDate').val('');

        // Clear Flatpickr
        $('#filterStartDate')[0]._flatpickr.clear();
        $('#filterEndDate')[0]._flatpickr.clear();

        table.ajax.reload();
    });

    // Auto-apply search on enter
    $('#filterSearch').on('keypress', function(e) {
        if (e.which === 13) {
            table.ajax.reload();
        }
    });
});

// Modal functions
function showContactModal(contactCode, shopId) {
    console.log('Show contact modal:', contactCode, shopId);

    // Show loading state
    $('#contactModalContent').html(`
        <div class="text-center">
            <div class="spinner-border text-primary" role="status">
                <span class="visually-hidden">Loading...</span>
            </div>
            <p>Loading contact details...</p>
        </div>
    `);

    // Fetch contact data
    $.ajax({
        url: '<?php echo e(url("api/shop/contact-info")); ?>',
        method: 'GET',
        data: { contact_code: contactCode, shop_id: shopId },
        success: function(response) {
            if (response.success) {
                displayContactInfo(response.data);
            } else {
                $('#contactModalContent').html('<div class="alert alert-danger">Error loading contact information.</div>');
            }
        },
        error: function() {
            $('#contactModalContent').html('<div class="alert alert-danger">Error loading contact information.</div>');
        }
    });

    // Show modal
    const modal = new bootstrap.Modal(document.getElementById('contactModal'));
    modal.show();
}

function displayContactInfo(data) {
    const contact = data.contact;
    const financial = data.financial;

    $('#contactModalContent').html(`
        <div class="row">
            <div class="col-md-6">
                <h5>Contact Information</h5>
                <table class="table table-sm">
                    <tr><th>Name:</th><td>${contact.name || 'N/A'}</td></tr>
                    <tr><th>Phone:</th><td>${contact.phone || 'N/A'}</td></tr>
                    <tr><th>Address:</th><td>${contact.address || 'N/A'}</td></tr>
                    <tr><th>Type:</th><td><span class="badge bg-primary">${contact.contact_type || 'N/A'}</span></td></tr>
                    <tr><th>Credit Limit:</th><td>Rs. ${contact.credit_limit || '0'}</td></tr>
                    <tr><th>Shop:</th><td>${contact.shop_name || 'N/A'}</td></tr>
                    <tr><th>Created:</th><td>${new Date(contact.created_at).toLocaleDateString()}</td></tr>
                </table>
            </div>
            <div class="col-md-6">
                <h5>Financial Summary</h5>
                <table class="table table-sm">
                    <tr><th>Total Paid:</th><td class="text-danger">Rs. ${financial.total_paid || '0'}</td></tr>
                    <tr><th>Total Received:</th><td class="text-success">Rs. ${financial.total_received || '0'}</td></tr>
                    <tr><th>Balance:</th><td class="${financial.balance >= 0 ? 'text-success' : 'text-danger'}">Rs. ${Math.abs(financial.balance || 0)}</td></tr>
                </table>
            </div>
        </div>
    `);
}

function showInvoiceModal(invoiceCode, shopId) {
    // Similar to shop transactions page
    console.log('Show invoice modal:', invoiceCode, shopId);
    // Implementation would be similar to the main transactions page
}

function showGoodsReceiptModal(receiptCode, shopId) {
    // Similar to shop transactions page
    console.log('Show goods receipt modal:', receiptCode, shopId);
    // Implementation would be similar to the main transactions page
}

function showInvoiceReturnModal(returnCode, shopId) {
    // Similar to shop transactions page
    console.log('Show invoice return modal:', returnCode, shopId);
    // Implementation would be similar to the main transactions page
}

function downloadContactPDF(contactCode, shopId) {
    const url = '<?php echo e(url("api/shop/contact-pdf")); ?>/' + contactCode + '/' + shopId;
    window.open(url, '_blank');
}
</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\shop\contact-transactions\index.blade.php ENDPATH**/ ?>