@extends('layouts.app')

@section('title', 'Sales')
@section('header', 'Sales Management')

@section('content')
<style>
    .stat-card {
        background: white;
        border-radius: 12px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        transition: transform 0.3s;
    }
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 20px rgba(0,0,0,0.1);
    }
    .stat-icon {
        width: 50px;
        height: 50px;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24px;
        margin-bottom: 15px;
    }
    .stat-value {
        font-size: 28px;
        font-weight: bold;
        margin-bottom: 5px;
    }
    .stat-label {
        color: #6c757d;
        font-size: 14px;
    }
</style>

<div class="row mb-4">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white;">
                <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-value">${{ number_format($totalSales ?? 0, 2) }}</div>
            <div class="stat-label">Total Sales</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
                <i class="fas fa-tag"></i>
            </div>
            <div class="stat-value">${{ number_format($totalDiscount ?? 0, 2) }}</div>
            <div class="stat-label">Total Discount</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white;">
                <i class="fas fa-receipt"></i>
            </div>
            <div class="stat-value">${{ number_format($totalTax ?? 0, 2) }}</div>
            <div class="stat-label">Total Tax</div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%); color: white;">
                <i class="fas fa-hourglass-half"></i>
            </div>
            <div class="stat-value">${{ number_format($totalDue ?? 0, 2) }}</div>
            <div class="stat-label">Total Due</div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <div class="d-flex justify-content-between align-items-center">
            <h5 class="mb-0">
                <i class="fas fa-list me-2"></i>All Sales
            </h5>
            <div>
                <button id="exportExcelBtn" class="btn btn-success">
                    <i class="fas fa-file-excel"></i> Export to Excel
                </button>
                <a href="{{ route('pos.index') }}" class="btn btn-primary ms-2">
                    <i class="fas fa-plus"></i> New Sale
                </a>
            </div>
        </div>
        <hr>
        <form method="GET" class="row mt-3" id="filterForm">
            <div class="col-md-3">
                <label>Start Date</label>
                <input type="date" name="start_date" id="start_date" class="form-control" value="{{ $startDate ?? '' }}">
            </div>
            <div class="col-md-3">
                <label>End Date</label>
                <input type="date" name="end_date" id="end_date" class="form-control" value="{{ $endDate ?? '' }}">
            </div>
            <div class="col-md-3">
                <label>Payment Status</label>
                <select name="payment_status" id="payment_status" class="form-control">
                    <option value="">All Status</option>
                    <option value="paid" {{ request('payment_status') == 'paid' ? 'selected' : '' }}>Paid</option>
                    <option value="pending" {{ request('payment_status') == 'pending' ? 'selected' : '' }}>Pending</option>
                    <option value="cancelled" {{ request('payment_status') == 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                </select>
            </div>
            <div class="col-md-3">
                <label>&nbsp;</label>
                <div class="d-flex gap-2">
                    <button type="submit" class="btn btn-primary form-control">
                        <i class="fas fa-search"></i> Filter
                    </button>
                    <button type="button" id="resetBtn" class="btn btn-secondary form-control">
                        <i class="fas fa-undo"></i> Reset
                    </button>
                </div>
            </div>
        </form>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover" id="salesTable">
                <thead class="table-dark">
                    <tr>
                        <th>Invoice No</th>
                        <th>Customer</th>
                        <th>Date</th>
                        <th>Subtotal</th>
                        <th>Discount</th>
                        <th>Tax</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($sales ?? [] as $sale)
                    <tr>
                        <td>
                            <a href="{{ route('sales.show', $sale->id) }}" target="_blank">
                                {{ $sale->invoice_no }}
                            </a>
                         </a>
                        <td>{{ $sale->customer->name ?? 'Walk-in Customer' }}</a>
                        <td>{{ $sale->created_at->format('Y-m-d H:i') }}</a>
                        <td class="text-end">${{ number_format($sale->subtotal, 2) }}</a>
                        <td class="text-end">${{ number_format($sale->discount, 2) }}</a>
                        <td class="text-end">${{ number_format($sale->tax_amount, 2) }}</a>
                        <td class="text-end"><strong>${{ number_format($sale->total, 2) }}</strong></a>
                        <td>
                            @if($sale->payment_status == 'paid')
                                <span class="badge bg-success">Paid</span>
                            @elseif($sale->payment_status == 'pending')
                                <span class="badge bg-warning">Pending</span>
                            @else
                                <span class="badge bg-danger">Cancelled</span>
                            @endif
                         </a>
                        <td>
                            <div class="btn-group" role="group">
                                <a href="{{ route('sales.show', $sale->id) }}" class="btn btn-sm btn-info" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="{{ route('sales.invoice', $sale->id) }}" class="btn btn-sm btn-secondary" title="Print Invoice" target="_blank">
                                    <i class="fas fa-print"></i>
                                </a>
                            </div>
                         </a>
                     </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="text-center">No sales found</a>
                    </tr>
                    @endforelse
                </tbody>
                <tfoot class="table-secondary">
                    <tr>
                        <th colspan="3" class="text-end">Total:</th>
                        <th class="text-end">${{ number_format($totalSubtotal ?? 0, 2) }}</th>
                        <th class="text-end">${{ number_format($totalDiscount ?? 0, 2) }}</th>
                        <th class="text-end">${{ number_format($totalTax ?? 0, 2) }}</th>
                        <th class="text-end">${{ number_format($totalSales ?? 0, 2) }}</th>
                        <th></th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </div>
        <div class="mt-3">
            {{ $sales->links() }}
        </div>
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>

<script>
$(document).ready(function() {
    // Initialize DataTable
    var table = $('#salesTable').DataTable({
        pageLength: 25,
        responsive: true,
        order: [[2, 'desc']],
        searching: true,
        paging: false,
        info: false,
        language: {
            search: "Search:",
            lengthMenu: "Show _MENU_ entries",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            paginate: {
                first: "First",
                last: "Last",
                next: "Next",
                previous: "Previous"
            }
        }
    });
    
    // Reset button
    $('#resetBtn').click(function() {
        $('#start_date').val('');
        $('#end_date').val('');
        $('#payment_status').val('');
        $('#filterForm').submit();
    });
    
    // Export to Excel
    $('#exportExcelBtn').click(function(e) {
        e.preventDefault();
        
        try {
            // Get totals from the footer
            let totalSubtotal = parseFloat($('#salesTable tfoot th:eq(3)').text().replace('$', '').replace(/,/g, '')) || 0;
            let totalDiscount = parseFloat($('#salesTable tfoot th:eq(4)').text().replace('$', '').replace(/,/g, '')) || 0;
            let totalTax = parseFloat($('#salesTable tfoot th:eq(5)').text().replace('$', '').replace(/,/g, '')) || 0;
            let totalSales = parseFloat($('#salesTable tfoot th:eq(6)').text().replace('$', '').replace(/,/g, '')) || 0;
            let rowCount = $('#salesTable tbody tr:visible').length;
            
            // Get table data
            let data = [];
            let headers = [];
            
            // Get headers (skip Actions column)
            $('#salesTable thead th').each(function(index) {
                if (index < 8) { // Only first 8 columns (skip Actions)
                    headers.push($(this).text().trim());
                }
            });
            data.push(headers);
            
            // Get visible rows data
            $('#salesTable tbody tr:visible').each(function() {
                let row = [];
                $(this).find('td').each(function(index) {
                    if (index < 8) { // Only first 8 columns
                        let text = $(this).text().trim();
                        // Remove any HTML tags
                        text = text.replace(/<[^>]*>/g, '');
                        row.push(text);
                    }
                });
                if (row.length > 0) {
                    data.push(row);
                }
            });
            
            // Add empty row for spacing
            data.push(['']);
            
            // Add summary section
            data.push(['REPORT SUMMARY']);
            data.push(['Total Transactions:', rowCount.toString()]);
            data.push(['Total Subtotal:', '$' + totalSubtotal.toFixed(2)]);
            data.push(['Total Discount:', '$' + totalDiscount.toFixed(2)]);
            data.push(['Total Tax:', '$' + totalTax.toFixed(2)]);
            data.push(['Total Sales:', '$' + totalSales.toFixed(2)]);
            data.push(['Average Sale:', '$' + (rowCount > 0 ? (totalSales / rowCount).toFixed(2) : '0.00')]);
            data.push(['Report Period:', $('#start_date').val() || 'All Time', $('#end_date').val() ? ' to ' + $('#end_date').val() : '']);
            data.push(['Generated On:', new Date().toLocaleString()]);
            
            // Create worksheet
            let ws = XLSX.utils.aoa_to_sheet(data);
            let wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, 'Sales Report');
            
            // Set column widths
            ws['!cols'] = [
                {wch:18},  // Invoice No
                {wch:30},  // Customer
                {wch:20},  // Date
                {wch:15},  // Subtotal
                {wch:15},  // Discount
                {wch:15},  // Tax
                {wch:15},  // Total
                {wch:15}   // Status
            ];
            
            // Save file
            let fileName = 'sales_report_' + new Date().toISOString().slice(0,19).replace(/:/g, '-') + '.xlsx';
            XLSX.writeFile(wb, fileName);
            
            Swal.fire({
                icon: 'success',
                title: 'Success!',
                text: 'Export completed successfully!',
                timer: 2000,
                showConfirmButton: false
            });
        } catch (error) {
            console.error('Export error:', error);
            Swal.fire('Error!', 'Failed to export: ' + error.message, 'error');
        }
    });
});
</script>
@endpush
@endsection