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

<?php $__env->startPush('plugin-styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.css')); ?>">
<link rel="stylesheet" href="<?php echo e(asset('theme/vendors/select2/select2.min.css')); ?>">
<style>
.select2-container--bootstrap-5{
    width: 100% !important;
}
.dashboard-card {
    transition: transform 0.2s;
}
.dashboard-card:hover {
    transform: translateY(-2px);
}
.metric-value {
    font-size: 2rem;
    font-weight: bold;
}
.metric-label {
    font-size: 0.875rem;
    color: #6c757d;
    margin-bottom: 0.5rem;
}
.select2-container--bootstrap-5 .select2-selection{
    min-height: 34px !important;
    padding: 0 !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 Dashboard</h4>
    </div>
    <div class="d-flex align-items-center flex-wrap text-nowrap">
        <!-- Shop Filter -->
        <div class="me-2 mb-2 mb-md-0" style="width: 180px;">
            <select id="shopFilter" class="form-select form-select-sm">
                <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(request('shop_id') == $shop->id ? 'selected' : ''); ?>><?php echo e($shop->name); ?></option>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </select>
        </div>

        <!-- Start Date Filter -->
      <div class="input-group input-group-sm flatpickr me-2 mb-2 mb-md-0" style="width: 140px;">
        <input type="text" id="startDateInput" class="form-control" placeholder="Start Date" value="<?php echo e(request('start_date')); ?>">
        <span class="input-group-text" id="startDateIcon">
            <i data-feather="calendar"></i>
        </span>
    </div>

    <!-- End Date Filter -->
    <div class="input-group input-group-sm flatpickr me-2 mb-2 mb-md-0"style="width: 140px;">
        <input type="text" class="form-control" placeholder="End Date"  id="endDatePicker"  value="<?php echo e(request('end_date')); ?>">
        <span class="input-group-text"  id="endDateIcon">
            <i data-feather="calendar"></i>
        </span>
    </div>

    <!-- Apply Filters Button -->
    <button type="button" class="btn btn-sm btn-outline-primary me-2 mb-2 mb-md-0 p-1" id="applyFilters">
        <i class="btn-icon-prepend" data-feather="filter"></i>
        Apply
    </button>

    <!-- Clear Filters Button -->
    <button type="button" class="btn btn-sm btn-outline-secondary me-2 mb-2 mb-md-0 p-1" id="clearFilters">
        <i class="btn-icon-prepend" data-feather="x"></i>
        Clear
    </button>

    <!-- Print Button -->
    

    <!-- Download PDF Button -->
    <button type="button" class="btn btn-sm btn-primary mb-2 mb-md-0 pe-2 ps-2 py-1 px-2" id="downloadBtn" onclick="downloadDashboardPDF()">
        <i class="btn-icon-prepend" data-feather="download-cloud"></i>
        PDF
    </button>
    </div>
</div>

<!-- Business Metrics Cards -->
<div class="row">
    <!-- Total Sales -->
    <div class="col-xl-3 col-lg-4 col-md-6 grid-margin stretch-card">
        <div class="card dashboard-card" id="total-sales-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="color-card">
                        <p class="metric-label">Total Sales</p>
                        <h2 class="metric-value text-primary" id="total-sales-value"><?php echo e(number_format($initialData['totalSales'])); ?></h2>
                        <small class="text-muted">Number of invoices</small>
                    </div>
                    <div class="color-card-icon">
                        <i data-feather="shopping-cart" class="text-primary"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Total Earned Today -->
    <div class="col-xl-3 col-lg-4 col-md-6 grid-margin stretch-card">
        <div class="card dashboard-card" id="earned-today-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="color-card">
                        <p class="metric-label">Collected Today</p>
                        <h2 class="metric-value text-success" id="earned-today-value">Rs. <?php echo e(number_format($initialData['totalEarnedToday'], 2)); ?></h2>
                        <small class="text-muted">Payments received</small>
                    </div>
                    <div class="color-card-icon">
                        <i data-feather="trending-up" class="text-success"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Total Outstanding Payable -->
    <div class="col-xl-3 col-lg-4 col-md-6 grid-margin stretch-card">
        <div class="card dashboard-card" id="outstanding-payable-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="color-card">
                        <p class="metric-label">Outstanding Payable</p>
                        <h2 class="metric-value <?php echo e($initialData['totalOutstandingPayable'] > 0 ? 'text-danger' : 'text-success'); ?>" id="outstanding-payable-value">
                            Rs. <?php echo e(number_format(abs($initialData['totalOutstandingPayable']), 2)); ?>

                        </h2>
                        <small class="text-muted" id="outstanding-payable-desc"><?php echo e($initialData['totalOutstandingPayable'] > 0 ? 'Amount to pay' : 'Credit balance'); ?></small>
                    </div>
                    <div class="color-card-icon">
                        <i data-feather="credit-card" class="<?php echo e($initialData['totalOutstandingPayable'] > 0 ? 'text-danger' : 'text-success'); ?>" id="outstanding-payable-icon"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Return Invoices -->
    <div class="col-xl-3 col-lg-4 col-md-6 grid-margin stretch-card">
        <div class="card dashboard-card" id="return-invoices-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="color-card">
                        <p class="metric-label">Return Invoices</p>
                        <h2 class="metric-value text-warning" id="return-invoices-value"><?php echo e(number_format($initialData['totalReturnInvoices'])); ?></h2>
                        <small class="text-muted" id="return-amount-desc">Rs. <?php echo e(number_format($initialData['totalReturnAmount'], 2)); ?></small>
                    </div>
                    <div class="color-card-icon">
                        <i data-feather="rotate-ccw" class="text-warning"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Total Revenue -->
    <div class="col-xl-3 col-lg-4 col-md-6 grid-margin stretch-card">
        <div class="card dashboard-card" id="total-revenue-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="color-card">
                        <p class="metric-label">Total Revenue</p>
                        <h2 class="metric-value text-info" id="total-revenue-value">Rs. <?php echo e(number_format($initialData['totalRevenue'], 2)); ?></h2>
                        <small class="text-muted">All receipts</small>
                    </div>
                    <div class="color-card-icon">
                        <i data-feather="dollar-sign" class="text-info"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Net Profit -->
    

    <!-- Total Transactions -->
    <div class="col-xl-3 col-lg-4 col-md-6 grid-margin stretch-card">
        <div class="card dashboard-card" id="total-transactions-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="color-card">
                        <p class="metric-label">Total Transactions</p>
                        <h2 class="metric-value text-secondary" id="total-transactions-value"><?php echo e(number_format($initialData['totalTransactions'])); ?></h2>
                        <small class="text-muted">All activities</small>
                    </div>
                    <div class="color-card-icon">
                        <i data-feather="activity" class="text-secondary"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Legacy Stats -->
    <div class="col-xl-3 col-lg-4 col-md-6 grid-margin stretch-card">
        <div class="card dashboard-card" id="active-shops-card">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start">
                    <div class="color-card">
                        <p class="metric-label">Active Shops</p>
                        <h2 class="metric-value text-primary"><?php echo e($activeShops); ?></h2>
                        <small class="text-muted">of <?php echo e($totalShops); ?> total</small>
                    </div>
                    <div class="color-card-icon">
                        <i data-feather="check-circle" class="text-primary"></i>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Recent Transactions -->
<div class="row">
    <div class="col-lg-12 grid-margin stretch-card">
        <div class="card">
            <div class="card-body">
                <h4 class="card-title">Recent Transactions</h4>
                <div class="table-responsive">
                    <table class="table table-hover" id="recent-transactions-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Shop</th>
                                <th>Contact</th>
                                <th>Type</th>
                                <th>Reference</th>
                                <th>Amount</th>
                                <th>Transaction</th>
                            </tr>
                        </thead>
                        <tbody id="recent-transactions-tbody">
                            <?php $__empty_1 = true; $__currentLoopData = $initialData['recentTransactions']; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $transaction): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                            <tr>
                                <td><?php echo e($transaction->local_db_created_at->format('M d, Y H:i')); ?></td>
                                <td><?php echo e($transaction->shop->name ?? 'N/A'); ?></td>
                                <td><?php echo e($transaction->contact->name ?? 'N/A'); ?></td>
                                <td>
                                    <span class="badge bg-<?php echo e($transaction->reference_type === 'invoice' ? 'primary' : ($transaction->reference_type === 'goods_receipt' ? 'success' : ($transaction->reference_type === 'invoice_return' ? 'warning' : 'secondary'))); ?>">
                                        <?php echo e($transaction->reference_type_label); ?>

                                    </span>
                                </td>
                                <td><?php echo e($transaction->reference_code); ?></td>
                                <td class="<?php echo e($transaction->transaction_type === 'receipt' ? 'text-success' : 'text-danger'); ?>">
                                    <?php echo e($transaction->formatted_amount); ?>

                                </td>
                                <td>
                                    <span class="badge bg-<?php echo e($transaction->transaction_type === 'receipt' ? 'success' : 'danger'); ?>">
                                        <?php echo e($transaction->transaction_type_label); ?>

                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                            <tr id="no-transactions-row">
                                <td colspan="7" class="text-center">No transactions found</td>
                            </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>


<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script src="<?php echo e(asset('theme/vendors/flatpickr/flatpickr.min.js')); ?>"></script>
<script src="<?php echo e(asset('theme/vendors/select2/select2.min.js')); ?>"></script>
<script>
let currentFilters = {
    shop_id: '<?php echo e(request("shop_id")); ?>',
    start_date: '<?php echo e(request("start_date")); ?>',
    end_date: '<?php echo e(request("end_date")); ?>'
};
let transactionsTable = null;
document.addEventListener('DOMContentLoaded', function() {
    // Initialize feather icons
    feather.replace();

    // Initialize DataTables
    transactionsTable = $('#recent-transactions-table').DataTable({
        order: [[0, 'desc']],
        pageLength: 10,
        lengthMenu: [10, 25, 50, 100],
        language: {
            search: "_INPUT_",
            searchPlaceholder: "Search transactions..."
        }
    });

    loadDashboardData();

    // Initialize Select2 for shop filter
    $('#shopFilter').select2({
        theme: 'bootstrap-5',
        width: '100%',
        placeholder: 'Select Shop'
    }).on('change', function() {
        currentFilters.shop_id = $(this).val();
    });

    // Initialize Flatpickr for date filters
    // $('#startDatePicker').flatpickr({
    //     dateFormat: 'Y-m-d',
    //     allowInput: true,
    //     onChange: function(selectedDates, dateStr) {
    //         currentFilters.start_date = dateStr;
    //     }
    // });

      const startDatePicker = flatpickr('#startDateInput', {
        dateFormat: 'Y-m-d',
        allowInput: true,
        defaultDate: currentFilters.start_date || '<?php echo e(request('start_date')); ?>',
        clickOpens: false, // disable default input click, we'll handle manually if needed
        onChange: function(selectedDates, dateStr) {
            currentFilters.start_date = dateStr;
        }
    });

          const endDatePicker = flatpickr('#endDatePicker', {
        dateFormat: 'Y-m-d',
        allowInput: true,
        defaultDate: currentFilters.end_date || '<?php echo e(request('end_date')); ?>',
        clickOpens: false, // disable default input click, we'll handle manually if needed
        onChange: function(selectedDates, dateStr) {
            currentFilters.end_date = dateStr;
        }
    });
document.getElementById('startDateIcon').addEventListener('click', function() {
        startDatePicker.open();
    });
document.getElementById('endDateIcon').addEventListener('click', function() {
        endDatePicker.open();
    });


    // $('#endDatePicker').flatpickr({
    //     dateFormat: 'Y-m-d',
    //     allowInput: true,
    //     onChange: function(selectedDates, dateStr) {
    //         currentFilters.end_date = dateStr;
    //     }
    // });

    // Set initial filter values
    if (currentFilters.shop_id) {
        $('#shopFilter').val(currentFilters.shop_id).trigger('change');
    }
    if (currentFilters.start_date) {
        $('#startDatePicker input').val(currentFilters.start_date);
    }
    if (currentFilters.end_date) {
        $('#endDatePicker input').val(currentFilters.end_date);
    }

    // Apply filters button
    $('#applyFilters').on('click', function() {
        loadDashboardData();
    });

    // Clear filters button
    $('#clearFilters').on('click', function() {
        clearFilters();
    });

    // Auto-refresh every 5 minutes
    // setInterval(function() {
    //     if (!$('#applyFilters').prop('disabled')) {
    //         loadDashboardData(false); // Silent refresh
    //     }
    // }, 300000); // 5 minutes
});

function clearFilters() {
    // Reset filter values
    currentFilters = {
        shop_id: '',
        start_date: '',
        end_date: ''
    };

    // Reset form elements
    $('#shopFilter').val('').trigger('change');
    // $('#startDatePicker input').val('');
    $('#endDatePicker input').val('');
        startDatePicker.clear();
        endDatePicker.clear();

    // Clear Flatpickr values
    // $('#startDatePicker')[0]._flatpickr.clear();
    // $('#endDatePicker')[0]._flatpickr.clear();

    // Reload data
    loadDashboardData();
}

function loadDashboardData(showLoading = true) {
    if (showLoading) {
        // Show loading state
        $('#applyFilters').prop('disabled', true).html('<i class="btn-icon-prepend" data-feather="loader"></i>Loading...');
        feather.replace();
    }

    // Prepare data for API call
    const data = {};
    if (currentFilters.shop_id) data.shop_id = currentFilters.shop_id;
    if (currentFilters.start_date) data.start_date = currentFilters.start_date;
    if (currentFilters.end_date) data.end_date = currentFilters.end_date;

    // Make API call
    $.ajax({
        url: '<?php echo e(url("api/v1/shop/dashboard")); ?>',
        method: 'GET',
        data: data,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'application/json'
        },
        success: function(response) {
            if (response.success) {
                updateDashboardUI(response.data);
            } else {
                console.error('API Error:', response.message);
                showError('Failed to load dashboard data');
            }
        },
        error: function(xhr, status, error) {
            console.error('AJAX Error:', error);
            showError('Failed to load dashboard data. Please try again.');
        },
        complete: function() {
            if (showLoading) {
                $('#applyFilters').prop('disabled', false).html('<i class="btn-icon-prepend" data-feather="filter"></i>Apply');
                feather.replace();
            }
        }
    });
}

function updateDashboardUI(data) {
    const metrics = data.metrics;

    // Update metric cards
    $('#total-sales-value').text(formatNumber(metrics.total_sales));
    $('#earned-today-value').text('Rs. ' + formatCurrency(metrics.total_earned_today));

    // Update outstanding payable
    const outstandingPayable = metrics.total_outstanding_payable;
    const payableClass = outstandingPayable > 0 ? 'text-danger' : 'text-success';
    const payableIconClass = outstandingPayable > 0 ? 'text-danger' : 'text-success';
    const payableDesc = outstandingPayable > 0 ? 'Amount to pay' : 'Credit balance';

    $('#outstanding-payable-value').removeClass('text-danger text-success').addClass(payableClass)
        .text('Rs. ' + formatCurrency(Math.abs(outstandingPayable)));
    $('#outstanding-payable-desc').text(payableDesc);
    $('#outstanding-payable-icon').removeClass('text-danger text-success').addClass(payableIconClass);

    // Update return invoices
    $('#return-invoices-value').text(formatNumber(metrics.total_return_invoices));
    $('#return-amount-desc').text('Rs. ' + formatCurrency(metrics.total_return_amount));

    // Update revenue
    $('#total-revenue-value').text('Rs. ' + formatCurrency(metrics.total_revenue));

    // Update net profit
    // const netProfit = metrics.net_profit;
    // const profitClass = netProfit >= 0 ? 'text-success' : 'text-danger';
    // const profitIconClass = netProfit >= 0 ? 'text-success' : 'text-danger';

    // $('#net-profit-value').removeClass('text-danger text-success').addClass(profitClass)
    //     .text('Rs. ' + formatCurrency(netProfit));
    // $('#net-profit-icon').removeClass('text-danger text-success').addClass(profitIconClass);

    // Update total transactions
    $('#total-transactions-value').text(formatNumber(metrics.total_transactions));

    // Update recent transactions table
    updateTransactionsTable(data.recent_transactions);
}

function updateTransactionsTable(transactions) {
    if (!transactionsTable) return;

    transactionsTable.clear();

    transactions.forEach(function(transaction) {
        const typeBadgeClass = getTypeBadgeClass(transaction.reference_type);
        const transactionBadgeClass = transaction.transaction_type === 'credit' ? 'success' : 'danger';
        const amountClass = transaction.transaction_type === 'credit' ? 'text-success' : 'text-danger';

        transactionsTable.row.add([
            transaction.date,
            transaction.shop,
            transaction.contact,
            `<span class="badge bg-${typeBadgeClass}">${transaction.reference_type_label}</span>`,
            transaction.reference_code,
            `<span class="${amountClass}">${transaction.formatted_amount}</span>`,
            `<span class="badge bg-${transactionBadgeClass}">${transaction.transaction_type_label}</span>`
        ]);
    });

    transactionsTable.draw();
    feather.replace(); // Re-initialize feather icons for any new elements
}

function getTypeBadgeClass(referenceType) {
    switch(referenceType) {
        case 'invoice': return 'primary';
        case 'goods_receipt': return 'success';
        case 'invoice_return': return 'warning';
        default: return 'secondary';
    }
}

function formatNumber(num) {
    return new Intl.NumberFormat().format(num);
}

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

function showError(message) {
    // You can implement a toast notification here
    alert(message);
}

function printDashboard() {
    // Hide filter controls for printing
    $('.grid-margin:first .d-flex').hide();

    window.print();

    // Show filter controls again
    $('.grid-margin:first .d-flex').show();
}

function downloadDashboardPDF() {
    let url = '<?php echo e(route("shop.dashboard.pdf")); ?>';
    const params = [];

    if (currentFilters.shop_id) params.push('shop_id=' + currentFilters.shop_id);
    if (currentFilters.start_date) params.push('start_date=' + currentFilters.start_date);
    if (currentFilters.end_date) params.push('end_date=' + currentFilters.end_date);

    if (params.length > 0) url += '?' + params.join('&');

    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/dashboard.blade.php ENDPATH**/ ?>