
<?php $__env->startSection('title', 'Shop Contacts'); ?>

<?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')); ?>">
<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">Shop Contacts</h4>
    </div>
    <div class="d-flex align-items-center flex-wrap text-nowrap">
        <a href="<?php echo e(route('shop.dashboard')); ?>" class="btn btn-outline-primary 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="shopContactFilterAccordion">
    <div class="accordion-item">
        <h2 class="accordion-header" id="shopContactFilterHeading">
            <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#shopContactFilterCollapse" aria-expanded="false" aria-controls="shopContactFilterCollapse">
                Filters
            </button>
        </h2>
        <div id="shopContactFilterCollapse" class="accordion-collapse collapse" aria-labelledby="shopContactFilterHeading" data-bs-parent="#shopContactFilterAccordion">
            <div class="accordion-body">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Shop</label>
                        <select id="filterShop" class="form-select select2">
                            <option value="">All Shops</option>
                            <?php $__currentLoopData = $shops; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $shop): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($shop->id); ?>"><?php echo e($shop->name); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>

                    <div class="col-md-3">
                        <label class="form-label">Contact Type</label>
                        <select id="filterContactType" class="form-select">
                            <option value="">All Types</option>
                            <?php $__currentLoopData = $contactTypes; $__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">Search</label>
                        <input type="text" class="form-control" id="filterSearch" placeholder="Search contacts...">
                    </div>
                </div>
                <div class="mt-3">
                    <button type="button" class="btn btn-primary" id="applyFilters">
                        <i class="fas fa-search me-2"></i>
                        Apply
                    </button>
                    <button type="button" class="btn btn-outline-secondary" id="clearFilters">
                        <i class="fas fa-times me-2"></i>
                        Clear
                    </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">Shop Contacts</h6>
        </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($errors->any()): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <?php echo e($errors->first()); ?>

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

        <div class="table-responsive">
            <table id="shop-contacts-table" class="table table-hover">
                <thead class="table-light">
                    <tr>
                        <th>ID</th>
                        <th>Contact Code</th>
                        <th>Name</th>
                        <th>Phone</th>
                        <th>Type</th>
                        <th>Shop</th>
                        <th>Credit Limit</th>
                        <th>Total Paid</th>
                        <th>Total Received</th>
                        
                        <th>Outstanding Amount</th>
                        
                        <th>Actions</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
</div>

<!-- Include Modal Components -->
<?php echo $__env->make('modals.contact-info', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?>
<?php echo $__env->make('modals.contact-transactions', 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>
document.addEventListener('DOMContentLoaded', function () {
    // Initialize Select2
    $('.select2').select2({
        theme: 'bootstrap-5',
        placeholder: function(){
            return $(this).data('placeholder') || 'Select...';
        },
        allowClear: true
    });

    // Initialize DataTable
    const table = new DataTable('#shop-contacts-table', {
        processing: true,
        serverSide: true,
        ajax: {
            url: '<?php echo e(route("shop.contacts.data")); ?>',
            data: function(d) {
                d.shop_id = $('#filterShop').val();
                d.contact_type = $('#filterContactType').val();
                // d.status = $('#filterStatus').val();
                d.search = $('#filterSearch').val();
            }
        },
        order: [[0, 'desc']],
        columns: [
            {
                data: 'id',
                name: 'id',
                className: 'text-center'
            },
            {
                data: 'code',
                name: 'code'
            },
            {
                data: 'name',
                name: 'name'
            },
            {
                data: 'phone',
                name: 'phone'
            },
            {
                data: 'contact_type_label',
                name: 'contact_type'
            },
            {
                data: 'shop_name',
                name: 'shop_name'
            },
            {
                data: 'credit_limit_formatted',
                name: 'credit_limit',
                className: 'text-right'
            },
            {
                data: 'total_paid',
                name: 'total_paid',
                className: 'text-right'
            },
            {
                data: 'total_received',
                name: 'total_received',
                className: 'text-right'
            },
            {
                data: 'outstanding_amount',
                name: 'outstanding_amount',
                className: 'text-center'
            },
            // {
            //     data: 'status_label',
            //     name: 'is_active',
            //     className: 'text-center'
            // },
            {
                data: 'actions',
                name: 'actions',
                orderable: false,
                searchable: false,
                className: 'text-center'
            }
        ],
        pageLength: 25,
        responsive: true
    });

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

    // Clear filters
    $('#clearFilters').on('click', function() {
        $('#filterShop').val('').trigger('change');
        $('#filterContactType').val('');
        // $('#filterStatus').val('');
        $('#filterSearch').val('');
        table.ajax.reload();
    });

    // Search on enter key
    $('#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);

    // Check if modal exists
    if ($('#contactInfoModal').length === 0) {
        console.error('Contact modal not found!');
        return;
    }

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

    // Show modal
    $('#contactInfoModal').modal('show');

    // Make AJAX request to get contact data
    $.ajax({
        url: '/api/shop/contact-info',
        method: 'GET',
        data: {
            contact_code: contactCode,
            shop_id: shopId
        },
        success: function(response) {
            if (response.success) {
                // Store contact data globally for PDF download
                window.currentContactData = response.data;
                window.currentContactData.type = 'contact';
                displayContactInfo(response.data);
            } else {
                $('#contactInfoContent').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        ${response.message || 'Failed to load contact information'}
                    </div>
                `);
            }
        },
        error: function(xhr, status, error) {
            $('#contactInfoContent').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Error loading contact information: ${error}
                </div>
            `);
        }
    });
}

function showContactTransactions(contactCode, shopId) {
    console.log('Show contact transactions:', contactCode, shopId);

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

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

    // Show modal
    $('#contactTransactionsModal').modal('show');

    // Make AJAX request to get contact transactions
    $.ajax({
        url: '/api/shop/contact-transactions',
        method: 'GET',
        data: {
            contact_code: contactCode,
            shop_id: shopId
        },
        success: function(response) {
            if (response.success) {
                displayContactTransactions(response.data);
            } else {
                $('#contactTransactionsContent').html(`
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-triangle me-2"></i>
                        ${response.message || 'Failed to load contact transactions'}
                    </div>
                `);
            }
        },
        error: function(xhr, status, error) {
            $('#contactTransactionsContent').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i>
                    Error loading contact transactions: ${error}
                </div>
            `);
        }
    });
}

function downloadContactPDF(contactCode, shopId) {
    // Redirect to PDF download URL
    window.location.href = `/api/shop/contact-pdf/${contactCode}/${shopId}`;
}

// Helper functions for displaying modal content
function displayContactInfo(contact) {
    const html = `
        <div class="row">
            <div class="col-md-12">
                <h6 class="mb-3">Contact Information</h6>
                <table class="table table-sm">
                    <tr>
                        <th class="bg-light" style="width: 150px;">Name:</th>
                        <td>${contact.name || 'N/A'}</td>
                    </tr>
                    <tr>
                        <th class="bg-light">Phone:</th>
                        <td>${contact.phone || 'N/A'}</td>
                    </tr>
                    <tr>
                        <th class="bg-light">Address:</th>
                        <td>${contact.address || 'N/A'}</td>
                    </tr>
                    <tr>
                        <th class="bg-light">Type:</th>
                        <td>${contact.contact_type ? contact.contact_type.charAt(0).toUpperCase() + contact.contact_type.slice(1) : 'N/A'}</td>
                    </tr>
                    <tr>
                        <th class="bg-light">Credit Limit:</th>
                        <td>${contact.credit_limit ? 'Rs. ' + parseFloat(contact.credit_limit).toLocaleString('en-US', {minimumFractionDigits: 2}) : 'N/A'}</td>
                    </tr>
                    <tr>
                        <th class="bg-light">Shop:</th>
                        <td>${contact.shop_name || contact.shop_id || 'N/A'}</td>
                    </tr>
                    <tr>
                        <th class="bg-light">Created:</th>
                        <td>${contact.created_at ? new Date(contact.created_at).toLocaleDateString() : 'N/A'}</td>
                    </tr>
                </table>
            </div>
        </div>
    `;

    $('#contactInfoContent').html(html);
}

function displayContactTransactions(data) {
    let html = `
        <div class="contact-transactions">
            <h6 class="mb-3">Transaction History</h6>
    `;

    if (data.transactions && data.transactions.length > 0) {
        html += `
            <div class="table-responsive">
                <table class="table table-sm table-striped">
                    <thead class="table-light">
                        <tr>
                            <th>Date</th>
                            <th>Type</th>
                            <th>Reference</th>
                            <th>Description</th>
                            <th>Amount</th>
                        </tr>
                    </thead>
                    <tbody>
        `;

        data.transactions.forEach(transaction => {
            const amountClass = transaction.transaction_type === 'payment' ? 'text-danger' : 'text-success';
            const amountPrefix = transaction.transaction_type === 'payment' ? '-' : '+';

            html += `
                <tr>
                    <td>${new Date(transaction.local_db_created_at).toLocaleDateString()}</td>
                    <td><span class="badge bg-secondary">${transaction.transaction_type_label}</span></td>
                    <td>${transaction.reference_code || 'N/A'}</td>
                    <td>${transaction.reference_type_label}</td>
                    <td class="${amountClass}">${amountPrefix}Rs. ${parseFloat(transaction.amount).toLocaleString('en-US', {minimumFractionDigits: 2})}</td>
                </tr>
            `;
        });

        html += `
                    </tbody>
                </table>
            </div>
        `;
    } else {
        html += '<p class="text-muted">No transactions found for this contact.</p>';
    }

    html += '</div>';

    $('#contactTransactionsContent').html(html);
}

function getStatusBadgeClass(status) {
    switch (status?.toLowerCase()) {
        case 'paid':
        case 'completed':
        case 'received':
            return 'bg-success';
        case 'pending':
            return 'bg-warning';
        case 'cancelled':
        case 'rejected':
            return 'bg-danger';
        default:
            return 'bg-secondary';
    }
}
</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\contacts\index.blade.php ENDPATH**/ ?>