@extends('layouts.app')

@section('title', 'Purchases Report')
@section('header', 'Purchases Report')

@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-4">
        <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($totalPurchases ?? 0, 2) }}</div>
            <div class="stat-label">Total Purchases</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); color: white;">
                <i class="fas fa-shopping-cart"></i>
            </div>
            <div class="stat-value">{{ $purchases->count() ?? 0 }}</div>
            <div class="stat-label">Total Orders</div>
        </div>
    </div>
    <div class="col-md-4">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%); color: white;">
                <i class="fas fa-truck"></i>
            </div>
            <div class="stat-value">{{ $supplierCount ?? 0 }}</div>
            <div class="stat-label">Suppliers</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>Purchases Report
            </h5>
            <div>
                <button id="exportExcelBtn" class="btn btn-success">
                    <i class="fas fa-file-excel"></i> Export to Excel
                </button>
            </div>
        </div>
        <hr>
        <form method="GET" action="{{ route('reports.purchases') }}" class="row mt-3" id="reportForm">
            <div class="col-md-3">
                <label>Start Date</label>
                <input type="date" name="start_date" id="start_date" class="form-control" value="{{ request('start_date', $startDate ?? date('Y-m-d', strtotime('first day of this month'))) }}">
            </div>
            <div class="col-md-3">
                <label>End Date</label>
                <input type="date" name="end_date" id="end_date" class="form-control" value="{{ request('end_date', $endDate ?? date('Y-m-d')) }}">
            </div>
            <div class="col-md-3">
                <label>Supplier</label>
                <select name="supplier_id" id="supplier_id" class="form-control">
                    <option value="">All Suppliers</option>
                    @foreach($suppliers ?? [] as $supplier)
                    <option value="{{ $supplier->id }}" {{ request('supplier_id') == $supplier->id ? 'selected' : '' }}>
                        {{ $supplier->name }}
                    </option>
                    @endforeach
                </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> Generate Report
                    </button>
                    <a href="{{ route('reports.purchases') }}" class="btn btn-secondary form-control">
                        <i class="fas fa-undo"></i> Reset
                    </a>
                </div>
            </div>
        </form>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-bordered table-striped table-hover" id="purchasesTable">
                <thead class="table-dark">
                    <tr>
                        <th>PO Number</th>
                        <th>Supplier</th>
                        <th>Date</th>
                        <th>Subtotal</th>
                        <th>Discount</th>
                        <th>Tax</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Created By</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($purchases ?? [] as $purchase)
                    <tr>
                        <td>{{ $purchase->purchase_no ?? 'N/A' }}</a>
                        <td>{{ $purchase->supplier->name ?? 'N/A' }}</a>
                        <td>{{ $purchase->purchase_date instanceof \DateTime ? $purchase->purchase_date->format('Y-m-d') : $purchase->purchase_date }}</a>
                        <td class="text-end">${{ number_format($purchase->subtotal ?? 0, 2) }}</a>
                        <td class="text-end">${{ number_format($purchase->discount ?? 0, 2) }}</a>
                        <td class="text-end">${{ number_format($purchase->tax ?? 0, 2) }}</a>
                        <td class="text-end"><strong>${{ number_format($purchase->total ?? 0, 2) }}</strong></a>
                        <td>
                            @if(($purchase->payment_status ?? 'pending') == 'completed')
                                <span class="badge bg-success">Completed</span>
                            @elseif(($purchase->payment_status ?? 'pending') == 'cancelled')
                                <span class="badge bg-danger">Cancelled</span>
                            @else
                                <span class="badge bg-warning">Pending</span>
                            @endif
                         </a>
                        <td>{{ $purchase->user->name ?? 'N/A' }}</a>
                     </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="text-center">No purchases found</a>
                    </tr>
                    @endforelse
                </tbody>
                <tfoot class="table-secondary">
                    <tr>
                        <th colspan="3" class="text-end">Total:</th>
                        <th class="text-end" id="footerSubtotal">${{ number_format($totalSubtotal ?? 0, 2) }}</th>
                        <th class="text-end" id="footerDiscount">${{ number_format($totalDiscount ?? 0, 2) }}</th>
                        <th class="text-end" id="footerTax">${{ number_format($totalTax ?? 0, 2) }}</th>
                        <th class="text-end" id="footerTotal">${{ number_format($totalPurchases ?? 0, 2) }}</th>
                        <th></th>
                        <th></th>
                    </tr>
                </tfoot>
            </table>
        </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 = $('#purchasesTable').DataTable({
        pageLength: 25,
        responsive: true,
        order: [[2, 'desc']],
        language: {
            search: "Search:",
            lengthMenu: "Show _MENU_ entries",
            info: "Showing _START_ to _END_ of _TOTAL_ entries",
            paginate: {
                first: "First",
                last: "Last",
                next: "Next",
                previous: "Previous"
            }
        }
    });
    
    // Export to Excel
    $('#exportExcelBtn').click(function(e) {
        e.preventDefault();
        
        try {
            // Get totals from footer elements
            let totalSubtotal = parseFloat($('#footerSubtotal').text().replace('$', '').replace(/,/g, '')) || 0;
            let totalDiscount = parseFloat($('#footerDiscount').text().replace('$', '').replace(/,/g, '')) || 0;
            let totalTax = parseFloat($('#footerTax').text().replace('$', '').replace(/,/g, '')) || 0;
            let totalPurchases = parseFloat($('#footerTotal').text().replace('$', '').replace(/,/g, '')) || 0;
            let rowCount = $('#purchasesTable tbody tr:visible').length;
            
            // Get table data
            let data = [];
            let headers = [];
            
            // Get headers (all columns)
            $('#purchasesTable thead th').each(function() {
                headers.push($(this).text().trim());
            });
            data.push(headers);
            
            // Get visible rows data
            $('#purchasesTable tbody tr:visible').each(function() {
                let row = [];
                $(this).find('td').each(function() {
                    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(['PURCHASE REPORT SUMMARY']);
            data.push(['Total Orders:', 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 Purchases:', '$' + totalPurchases.toFixed(2)]);
            data.push(['Average Purchase:', '$' + (rowCount > 0 ? (totalPurchases / 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, 'Purchases Report');
            
            // Set column widths
            ws['!cols'] = [
                {wch:15},  // PO Number
                {wch:30},  // Supplier
                {wch:15},  // Date
                {wch:15},  // Subtotal
                {wch:15},  // Discount
                {wch:15},  // Tax
                {wch:15},  // Total
                {wch:12},  // Status
                {wch:20}   // Created By
            ];
            
            // Save file
            let fileName = 'purchases_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