@extends('layouts.app')

@section('title', 'Suppliers')
@section('header', 'Supplier 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;
    }
    
    /* Export dropdown styles */
    .btn-group-export {
        position: relative;
        display: inline-block;
    }
    .export-dropdown {
        display: none;
        position: absolute;
        right: 0;
        top: 100%;
        background: white;
        min-width: 160px;
        box-shadow: 0 8px 16px rgba(0,0,0,0.1);
        border-radius: 8px;
        z-index: 1000;
        margin-top: 5px;
    }
    .export-dropdown a {
        color: #333;
        padding: 10px 15px;
        text-decoration: none;
        display: block;
        transition: background 0.3s;
    }
    .export-dropdown a:hover {
        background: #f5f5f5;
    }
    .btn-group-export:hover .export-dropdown {
        display: block;
    }
</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-truck"></i>
            </div>
            <div class="stat-value">{{ $totalSuppliers ?? 0 }}</div>
            <div class="stat-label">Total Suppliers</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-check-circle"></i>
            </div>
            <div class="stat-value">{{ $activeSuppliers ?? 0 }}</div>
            <div class="stat-label">Active Suppliers</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-dollar-sign"></i>
            </div>
            <div class="stat-value">${{ number_format($totalPurchases ?? 0, 2) }}</div>
            <div class="stat-label">Total Purchases</div>
        </div>
    </div>
</div>

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="fas fa-list me-2"></i>All Suppliers
        </h5>
        <div>
            <!-- Export Dropdown Button -->
            <div class="btn-group-export" style="display: inline-block;">
                <button class="btn btn-success dropdown-toggle" type="button" id="exportDropdown">
                    <i class="fas fa-download"></i> Export
                </button>
                <div class="export-dropdown">
                    <a href="#" id="exportExcelBtn">
                        <i class="fas fa-file-excel text-success"></i> Export to Excel (XLSX)
                    </a>
                    <a href="#" id="exportCSVBtn">
                        <i class="fas fa-file-csv text-primary"></i> Export to CSV
                    </a>
                    <a href="#" id="exportPDFBtn">
                        <i class="fas fa-file-pdf text-danger"></i> Export to PDF
                    </a>
                </div>
            </div>
            
            <a href="{{ route('suppliers.create') }}" class="btn btn-primary ms-2">
                <i class="fas fa-plus"></i> Add Supplier
            </a>
        </div>
    </div>
    <div class="card-body">
        <!-- Filter Section -->
        <div class="row mb-3">
            <div class="col-md-3">
                <label>Status Filter</label>
                <select id="statusFilter" class="form-select">
                    <option value="">All</option>
                    <option value="active">Active</option>
                    <option value="inactive">Inactive</option>
                </select>
            </div>
            <div class="col-md-3">
                <label>Date From</label>
                <input type="date" id="dateFrom" class="form-control">
            </div>
            <div class="col-md-3">
                <label>Date To</label>
                <input type="date" id="dateTo" class="form-control">
            </div>
            <div class="col-md-3">
                <label>&nbsp;</label>
                <button id="resetFilters" class="btn btn-secondary form-control">Reset Filters</button>
            </div>
        </div>
        
        <div class="table-responsive">
            <table class="table table-bordered" id="suppliersTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Company</th>
                        <th>Email</th>
                        <th>Phone</th>
                        <th>Total Purchases</th>
                        <th>Orders</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($suppliers as $supplier)
                    <tr data-supplier-id="{{ $supplier->id }}" data-status="{{ $supplier->is_active ? 'active' : 'inactive' }}" data-created="{{ $supplier->created_at->format('Y-m-d') }}">
                        <td>{{ $supplier->id }}</td>
                        <td>
                            <i class="fas fa-building text-primary me-1"></i>
                            <strong>{{ $supplier->name }}</strong>
                        </td>
                        <td>{{ $supplier->company ?? 'N/A' }}</td>
                        <td>{{ $supplier->email }}</td>
                        <td>{{ $supplier->phone }}</td>
                        <td>${{ number_format($supplier->total_purchases, 2) }}</td>
                        <td>{{ $supplier->purchases_count }}</td>
                        <td>
                            @if($supplier->is_active)
                                <span class="badge bg-success">Active</span>
                            @else
                                <span class="badge bg-danger">Inactive</span>
                            @endif
                        </td>
                        <td>
                            <div class="btn-group" role="group">
                                <a href="{{ route('suppliers.show', $supplier) }}" class="btn btn-sm btn-info" title="View">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="{{ route('suppliers.edit', $supplier) }}" class="btn btn-sm btn-warning" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <a href="{{ route('purchases.create', ['supplier' => $supplier->id]) }}" class="btn btn-sm btn-primary" title="Create Purchase Order">
                                    <i class="fas fa-shopping-cart"></i>
                                </a>
                                <button type="button" class="btn btn-sm btn-secondary toggle-status" 
                                        data-id="{{ $supplier->id }}" data-name="{{ $supplier->name }}" title="Toggle Status">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                @if($supplier->purchases_count == 0)
                                <button type="button" class="btn btn-sm btn-danger delete-supplier" 
                                        data-id="{{ $supplier->id }}" data-name="{{ $supplier->name }}" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                                @endif
                            </div>
                            
                            <form id="toggle-form-{{ $supplier->id }}" action="{{ route('suppliers.toggle', $supplier) }}" method="POST" style="display: none;">
                                @csrf
                                @method('PUT')
                            </form>
                            <form id="delete-form-{{ $supplier->id }}" action="{{ route('suppliers.destroy', $supplier) }}" method="POST" style="display: none;">
                                @csrf
                                @method('DELETE')
                            </form>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="text-center">No suppliers found</td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
        {{ $suppliers->links() }}
    </div>
</div>

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.29/jspdf.plugin.autotable.min.js"></script>

<script>
$(document).ready(function() {
    let table = $('#suppliersTable').DataTable({
        pageLength: 15,
        responsive: true,
        order: [[0, 'desc']]
    });
    
    // Apply filters
    function applyFilters() {
        let status = $('#statusFilter').val();
        let dateFrom = $('#dateFrom').val();
        let dateTo = $('#dateTo').val();
        
        $('#suppliersTable tbody tr').each(function() {
            let show = true;
            let rowStatus = $(this).data('status');
            let rowDate = $(this).data('created');
            
            if (status && rowStatus !== status) {
                show = false;
            }
            
            if (dateFrom && rowDate < dateFrom) {
                show = false;
            }
            
            if (dateTo && rowDate > dateTo) {
                show = false;
            }
            
            $(this).toggle(show);
        });
    }
    
    $('#statusFilter, #dateFrom, #dateTo').on('change', applyFilters);
    
    $('#resetFilters').click(function() {
        $('#statusFilter').val('');
        $('#dateFrom').val('');
        $('#dateTo').val('');
        $('#suppliersTable tbody tr').show();
    });
    
    // Export to Excel
    function exportToExcel() {
        let data = [];
        let headers = [];
        
        // Get headers
        $('#suppliersTable thead th').each(function() {
            if ($(this).text() !== 'Actions') {
                headers.push($(this).text());
            }
        });
        data.push(headers);
        
        // Get visible rows
        $('#suppliersTable tbody tr:visible').each(function() {
            let row = [];
            $(this).find('td').each(function(index) {
                if (index !== 8) { // Skip Actions column (index 8)
                    let text = $(this).text().trim();
                    row.push(text);
                }
            });
            data.push(row);
        });
        
        // Create worksheet
        let ws = XLSX.utils.aoa_to_sheet(data);
        let wb = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(wb, ws, 'Suppliers');
        
        // Style the worksheet
        ws['!cols'] = [
            {wch:8},   // ID
            {wch:25},  // Name
            {wch:25},  // Company
            {wch:30},  // Email
            {wch:15},  // Phone
            {wch:15},  // Total Purchases
            {wch:10},  // Orders
            {wch:10}   // Status
        ];
        
        // Save file
        XLSX.writeFile(wb, 'suppliers_' + new Date().toISOString().slice(0,19) + '.xlsx');
        
        Swal.fire('Success!', 'Export completed successfully!', 'success');
    }
    
    // Export to CSV
    function exportToCSV() {
        let csv = [];
        let headers = [];
        
        // Get headers
        $('#suppliersTable thead th').each(function() {
            if ($(this).text() !== 'Actions') {
                headers.push('"' + $(this).text() + '"');
            }
        });
        csv.push(headers.join(','));
        
        // Get visible rows
        $('#suppliersTable tbody tr:visible').each(function() {
            let row = [];
            $(this).find('td').each(function(index) {
                if (index !== 8) { // Skip Actions column
                    let text = $(this).text().trim();
                    row.push('"' + text + '"');
                }
            });
            csv.push(row.join(','));
        });
        
        // Download
        let blob = new Blob(["\uFEFF" + csv.join('\n')], { type: 'text/csv;charset=utf-8;' });
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.href = url;
        link.setAttribute('download', 'suppliers_' + new Date().toISOString().slice(0,19) + '.csv');
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
        
        Swal.fire('Success!', 'Export completed successfully!', 'success');
    }
    
    // Export to PDF
    async function exportToPDF() {
        const { jsPDF } = window.jspdf;
        let doc = new jsPDF('landscape');
        
        let headers = [];
        let data = [];
        
        // Get headers
        $('#suppliersTable thead th').each(function() {
            if ($(this).text() !== 'Actions') {
                headers.push($(this).text());
            }
        });
        
        // Get visible rows
        $('#suppliersTable tbody tr:visible').each(function() {
            let row = [];
            $(this).find('td').each(function(index) {
                if (index !== 8) { // Skip Actions column
                    let text = $(this).text().trim();
                    row.push(text);
                }
            });
            data.push(row);
        });
        
        // Add title
        doc.setFontSize(18);
        doc.text('Suppliers Report', 14, 15);
        doc.setFontSize(10);
        doc.text('Generated on: ' + new Date().toLocaleString(), 14, 22);
        
        // Add table
        doc.autoTable({
            head: [headers],
            body: data,
            startY: 30,
            styles: { fontSize: 8, cellPadding: 2 },
            headStyles: { fillColor: [78, 115, 223], textColor: 255 },
            alternateRowStyles: { fillColor: [240, 240, 240] }
        });
        
        // Save PDF
        doc.save('suppliers_' + new Date().toISOString().slice(0,19) + '.pdf');
        
        Swal.fire('Success!', 'Export completed successfully!', 'success');
    }
    
    // Event handlers for export buttons
    $('#exportExcelBtn').click(function(e) {
        e.preventDefault();
        exportToExcel();
    });
    
    $('#exportCSVBtn').click(function(e) {
        e.preventDefault();
        exportToCSV();
    });
    
    $('#exportPDFBtn').click(function(e) {
        e.preventDefault();
        exportToPDF();
    });
    
    $('.toggle-status').click(function() {
        const id = $(this).data('id');
        const name = $(this).data('name');
        
        Swal.fire({
            title: 'Toggle Status?',
            html: `Change status of <strong>${name}</strong>?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, toggle!'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('toggle-form-' + id).submit();
            }
        });
    });
    
    $('.delete-supplier').click(function() {
        const id = $(this).data('id');
        const name = $(this).data('name');
        
        Swal.fire({
            title: 'Delete Supplier?',
            html: `Are you sure you want to delete <strong>${name}</strong>?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Yes, delete!'
        }).then((result) => {
            if (result.isConfirmed) {
                document.getElementById('delete-form-' + id).submit();
            }
        });
    });
});
</script>
@endpush
@endsection