@extends('layouts.admin')

@section('content')
<div class="container-fluid py-4">
    <div class="row">
        <div class="col-12">
            <div class="card shadow-sm">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0">Transaction Report</h5>
                    <button type="button" class="btn btn-danger btn-sm" onclick="window.print()">
                        <i class="fas fa-print me-1"></i> Print
                    </button>
                </div>
                <div class="card-body">
                    <div class="row g-3 mb-4 no-print">
                        <div class="col-md-4">
                            <label class="form-label">Start Date</label>
                            <input type="date" id="start_date" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">End Date</label>
                            <input type="date" id="end_date" class="form-control">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Transaction Type</label>
                            <select id="transaction_type" class="form-select">
                                <option value="all">All Transactions</option>
                                <option value="purchase">Purchases</option>
                                <option value="sale">Sales</option>
                                <option value="refund">Refunds</option>
                            </select>
                        </div>
                    </div>

                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="card bg-primary text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Total Transactions</h6>
                                    <h2 class="mb-0" id="total_transactions">0</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-success text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Total Amount</h6>
                                    <h2 class="mb-0" id="total_amount">$0.00</h2>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card bg-info text-white">
                                <div class="card-body">
                                    <h6 class="text-white">Average Transaction</h6>
                                    <h2 class="mb-0" id="avg_transaction">$0.00</h2>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="bg-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Reference</th>
                                    <th>Type</th>
                                    <th>Description</th>
                                    <th class="text-end">Amount</th>
                                    <th>Status</th>
                                </tr>
                            </thead>
                            <tbody id="transaction_data">
                                <tr>
                                    <td colspan="6" class="text-center">Select date range to view transaction data</td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    // Initialize with current month data
    function initializeDates() {
        const today = new Date();
        const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
        const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
        
        $('#start_date').val(firstDay.toISOString().split('T')[0]);
        $('#end_date').val(lastDay.toISOString().split('T')[0]);
        
        loadTransactionData();
    }

    function loadTransactionData() {
        const startDate = $('#start_date').val();
        const endDate = $('#end_date').val();
        const type = $('#transaction_type').val();

        if (!startDate || !endDate) {
            alert('Please select both start and end dates');
            return;
        }

        $.ajax({
            url: '{{ route("admin.reports.transactions.data") }}',
            method: 'GET',
            data: { 
                start_date: startDate, 
                end_date: endDate, 
                type: type 
            },
            beforeSend: function() {
                $('#transaction_data').html('<tr><td colspan="6" class="text-center">Loading data...</td></tr>');
            },
            success: function(response) {
                let html = '';
                let totalAmount = 0;

                if (response && response.length > 0) {
                    response.forEach(transaction => {
                        const amount = parseFloat(transaction.amount || 0);
                        totalAmount += amount;
                        
                        const date = new Date(transaction.created_at).toLocaleDateString('en-NG', {
                            year: 'numeric',
                            month: 'short',
                            day: 'numeric'
                        });
                        
                        html += `
                            <tr>
                                <td>${date}</td>
                                <td>${transaction.reference || 'N/A'}</td>
                                <td>
                                    <span class="badge bg-${getTypeColor(transaction.type)}">
                                        ${transaction.type}
                                    </span>
                                </td>
                                <td>${transaction.description || 'N/A'}</td>
                                <td class="text-end">$${amount.toFixed(2)}</td>
                                <td>
                                    <span class="badge bg-${getStatusColor(transaction.status)}">
                                        ${transaction.status}
                                    </span>
                                </td>
                            </tr>
                        `;
                    });
                }

                $('#transaction_data').html(html || '<tr><td colspan="6" class="text-center">No transactions found for the selected period</td></tr>');
                $('#total_transactions').text(response.length || 0);
                $('#total_amount').text('$' + totalAmount.toFixed(2));
                $('#avg_transaction').text('$' + (response.length ? (totalAmount / response.length).toFixed(2) : '0.00'));
            },
            error: function(xhr, status, error) {
                let errorMessage = 'Error loading data';
                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage += ': ' + xhr.responseJSON.message;
                }
                alert(errorMessage);
                $('#transaction_data').html('<tr><td colspan="6" class="text-center text-danger">Error loading data</td></tr>');
            }
        });
    }

    function getTypeColor(type) {
        const colors = {
            'purchase': 'primary',
            'sale': 'success',
            'refund': 'warning'
        };
        return colors[type.toLowerCase()] || 'secondary';
    }

    function getStatusColor(status) {
        const colors = {
            'completed': 'success',
            'pending': 'warning',
            'failed': 'danger'
        };
        return colors[status.toLowerCase()] || 'secondary';
    }

    // Event Handlers
    $('#start_date, #end_date, #transaction_type').on('change', loadTransactionData);

    // Initialize with current month data
    initializeDates();
});
</script>
@endsection