@extends('layouts.app')

@section('title', 'Purchase Management')

@section('content')
<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-12">
            <h2 class="h3 mb-0">Purchase Management</h2>
            <p class="text-muted">Manage your purchase orders and receipts</p>
        </div>
    </div>

    <!-- Stats Cards -->
    <div class="row mb-4">
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                Total Purchases
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ number_format($stats['total_purchases'] ?? 0) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-shopping-cart fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-transparent border-0">
                    <a href="{{ route('purchases.index') }}" class="text-primary text-decoration-none">
                        View All <i class="fas fa-arrow-circle-right ml-1"></i>
                    </a>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                Total Amount
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                ৳{{ number_format($stats['total_amount'] ?? 0, 2) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-money-bill-wave fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-transparent border-0">
                    <a href="{{ route('purchases.index', ['payment_status' => 'paid']) }}" class="text-success text-decoration-none">
                        Paid Purchases <i class="fas fa-arrow-circle-right ml-1"></i>
                    </a>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                Total Due
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                ৳{{ number_format($stats['total_due'] ?? 0, 2) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-clock fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-transparent border-0">
                    <a href="{{ route('purchases.index', ['payment_status' => 'due']) }}" class="text-warning text-decoration-none">
                        Due Purchases <i class="fas fa-arrow-circle-right ml-1"></i>
                    </a>
                </div>
            </div>
        </div>
        
        <div class="col-lg-3 col-md-6 mb-3">
            <div class="card border-left-danger shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-danger text-uppercase mb-1">
                                Pending Purchases
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800">
                                {{ number_format($stats['pending_purchases'] ?? 0) }}
                            </div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-hourglass-half fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
                <div class="card-footer bg-transparent border-0">
                    <a href="{{ route('purchases.index', ['status' => 'pending']) }}" class="text-danger text-decoration-none">
                        View Pending <i class="fas fa-arrow-circle-right ml-1"></i>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Purchases List -->
    <div class="row">
        <div class="col-md-12">
            <div class="card shadow">
                <div class="card-header bg-white py-3">
                    <div class="d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">All Purchases</h5>
                        <div>
                            <a href="{{ route('purchases.create') }}" class="btn btn-primary btn-sm">
                                <i class="fas fa-plus"></i> New Purchase
                            </a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    @if(session('success'))
                    <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <i class="fas fa-check-circle"></i> {{ session('success') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    @endif
                    
                    @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <i class="fas fa-exclamation-circle"></i> {{ session('error') }}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    @endif

                    <!-- Filter Form -->
                    <form method="GET" action="{{ route('purchases.index') }}" class="row mb-4 g-2">
                        <div class="col-md-2 col-6 mb-2">
                            <input type="date" name="start_date" class="form-control form-control-sm" 
                                   value="{{ request('start_date') }}" placeholder="From Date">
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <input type="date" name="end_date" class="form-control form-control-sm" 
                                   value="{{ request('end_date') }}" placeholder="To Date">
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <select name="supplier_id" class="form-control form-control-sm">
                                <option value="">All Suppliers</option>
                                @if(isset($suppliers) && $suppliers->count() > 0)
                                    @foreach($suppliers as $supplier)
                                        <option value="{{ $supplier->id }}" {{ request('supplier_id') == $supplier->id ? 'selected' : '' }}>
                                            {{ $supplier->name }}
                                        </option>
                                    @endforeach
                                @endif
                            </select>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <select name="warehouse_id" class="form-control form-control-sm">
                                <option value="">All Warehouses</option>
                                @if(isset($warehouses) && $warehouses->count() > 0)
                                    @foreach($warehouses as $warehouse)
                                        <option value="{{ $warehouse->id }}" {{ request('warehouse_id') == $warehouse->id ? 'selected' : '' }}>
                                            {{ $warehouse->name }}
                                        </option>
                                    @endforeach
                                @endif
                            </select>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <select name="status" class="form-control form-control-sm">
                                <option value="">All Status</option>
                                <option value="pending" {{ request('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                <option value="ordered" {{ request('status') == 'ordered' ? 'selected' : '' }}>Ordered</option>
                                <option value="received" {{ request('status') == 'received' ? 'selected' : '' }}>Received</option>
                                <option value="partial" {{ request('status') == 'partial' ? 'selected' : '' }}>Partial</option>
                                <option value="cancelled" {{ request('status') == 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                            </select>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <select name="payment_status" class="form-control form-control-sm">
                                <option value="">All Payment Status</option>
                                <option value="paid" {{ request('payment_status') == 'paid' ? 'selected' : '' }}>Paid</option>
                                <option value="partial" {{ request('payment_status') == 'partial' ? 'selected' : '' }}>Partial</option>
                                <option value="due" {{ request('payment_status') == 'due' ? 'selected' : '' }}>Due</option>
                            </select>
                        </div>
                        <div class="col-md-3 col-9 mb-2">
                            <input type="text" name="search" class="form-control form-control-sm" 
                                   value="{{ request('search') }}" placeholder="Search purchase code, supplier...">
                        </div>
                        <div class="col-md-1 col-3 mb-2">
                            <button type="submit" class="btn btn-primary btn-sm btn-block">
                                <i class="fas fa-search"></i>
                            </button>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <button type="submit" class="btn btn-primary btn-sm btn-block">
                                <i class="fas fa-filter"></i> Filter
                            </button>
                        </div>
                        <div class="col-md-2 col-6 mb-2">
                            <a href="{{ route('purchases.index') }}" class="btn btn-secondary btn-sm btn-block">
                                <i class="fas fa-redo"></i> Clear
                            </a>
                        </div>
                    </form>

                    <!-- Purchases Table -->
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead class="thead-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Purchase Code</th>
                                    <th>Date</th>
                                    <th>Supplier</th>
                                    <th>Warehouse</th>
                                    <th>Items</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Payment</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @if(isset($purchases) && $purchases->count() > 0)
                                    @foreach($purchases as $purchase)
                                    <tr>
                                        <td>{{ $loop->iteration }}</td>
                                        <td>
                                            <a href="{{ route('purchases.show', $purchase->id) }}" class="text-primary font-weight-bold">
                                                {{ $purchase->purchase_code }}
                                            </a>
                                            @if($purchase->reference_no)
                                            <br><small class="text-muted">Ref: {{ $purchase->reference_no }}</small>
                                            @endif
                                        </td>
                                        <td>
                                            @if($purchase->purchase_date)
                                                {{ \Carbon\Carbon::parse($purchase->purchase_date)->format('d M, Y') }}
                                            @else
                                                N/A
                                            @endif
                                        </td>
                                        <td>
                                            @if($purchase->supplier)
                                                <a href="{{ route('suppliers.show', $purchase->supplier->id) }}" class="text-info">
                                                    {{ $purchase->supplier->name }}
                                                </a>
                                            @else
                                                <span class="text-muted">N/A</span>
                                            @endif
                                        </td>
                                        <td>
                                            @if($purchase->warehouse)
                                                <span class="badge badge-secondary">
                                                    {{ $purchase->warehouse->name }}
                                                </span>
                                            @else
                                                <span class="text-muted">N/A</span>
                                            @endif
                                        </td>
                                        <td>
                                            <span class="badge badge-info">{{ $purchase->total_items }}</span> items
                                            <br>
                                            <small class="text-muted">{{ $purchase->total_quantity }} qty</small>
                                        </td>
                                        <td>
                                            <strong class="text-success">৳{{ number_format($purchase->grand_total, 2) }}</strong>
                                            <br>
                                            <small class="text-muted">
                                                Paid: <span class="text-primary">৳{{ number_format($purchase->paid_amount, 2) }}</span>
                                                @if($purchase->due_amount > 0)
                                                <br>
                                                Due: <span class="text-danger">৳{{ number_format($purchase->due_amount, 2) }}</span>
                                                @endif
                                            </small>
                                        </td>
                                        <td>
                                            @php
                                                $statusColors = [
                                                    'pending' => 'warning',
                                                    'ordered' => 'info',
                                                    'received' => 'success',
                                                    'partial' => 'primary',
                                                    'cancelled' => 'danger'
                                                ];
                                                $statusIcons = [
                                                    'pending' => 'clock',
                                                    'ordered' => 'truck',
                                                    'received' => 'check-circle',
                                                    'partial' => 'exchange-alt',
                                                    'cancelled' => 'times-circle'
                                                ];
                                            @endphp
                                            <span class="badge badge-{{ $statusColors[$purchase->status] ?? 'secondary' }}">
                                                <i class="fas fa-{{ $statusIcons[$purchase->status] ?? 'question' }} mr-1"></i>
                                                {{ ucfirst($purchase->status) }}
                                            </span>
                                        </td>
                                        <td>
                                            @php
                                                $paymentColors = [
                                                    'paid' => 'success',
                                                    'partial' => 'warning',
                                                    'due' => 'danger'
                                                ];
                                                $paymentIcons = [
                                                    'paid' => 'check',
                                                    'partial' => 'exclamation',
                                                    'due' => 'times'
                                                ];
                                            @endphp
                                            <span class="badge badge-{{ $paymentColors[$purchase->payment_status] ?? 'secondary' }}">
                                                <i class="fas fa-{{ $paymentIcons[$purchase->payment_status] ?? 'question' }} mr-1"></i>
                                                {{ ucfirst($purchase->payment_status) }}
                                            </span>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <a href="{{ route('purchases.show', $purchase->id) }}" 
                                                   class="btn btn-info" title="View" data-toggle="tooltip">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                
                                                @if(in_array($purchase->status, ['pending', 'ordered']))
                                                <a href="{{ route('purchases.edit', $purchase->id) }}" 
                                                   class="btn btn-warning" title="Edit" data-toggle="tooltip">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                @endif
                                                
                                                @if(in_array($purchase->status, ['pending', 'ordered', 'partial']))
                                                <form action="{{ route('purchases.receive', $purchase->id) }}" 
                                                      method="POST" class="d-inline">
                                                    @csrf
                                                    <button type="submit" class="btn btn-primary" 
                                                            onclick="return confirm('Mark this purchase as received?')"
                                                            title="Receive" data-toggle="tooltip">
                                                        <i class="fas fa-truck-loading"></i>
                                                    </button>
                                                </form>
                                                @endif
                                                
                                                @if($purchase->status != 'cancelled')
                                                <form action="{{ route('purchases.cancel', $purchase->id) }}" 
                                                      method="POST" class="d-inline">
                                                    @csrf
                                                    @method('PATCH')
                                                    <button type="submit" class="btn btn-danger" 
                                                            onclick="return confirm('Are you sure to cancel this purchase?')"
                                                            title="Cancel" data-toggle="tooltip">
                                                        <i class="fas fa-times"></i>
                                                    </button>
                                                </form>
                                                @endif
                                                
                                                <a href="{{ route('purchases.invoice', $purchase->id) }}" 
                                                   class="btn btn-secondary" title="Print Invoice" data-toggle="tooltip" target="_blank">
                                                    <i class="fas fa-print"></i>
                                                </a>
                                            </div>
                                        </td>
                                    </tr>
                                    @endforeach
                                @else
                                <tr>
                                    <td colspan="10" class="text-center py-5">
                                        <div class="text-muted">
                                            <i class="fas fa-shopping-cart fa-3x mb-3"></i>
                                            <h5>No purchases found</h5>
                                            <p>Start by creating your first purchase order</p>
                                            <a href="{{ route('purchases.create') }}" class="btn btn-primary">
                                                <i class="fas fa-plus"></i> Create Purchase
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                @endif
                            </tbody>
                        </table>
                    </div>

                    <!-- Pagination -->
                    @if(isset($purchases) && $purchases->hasPages())
                    <div class="d-flex justify-content-between align-items-center mt-3">
                        <div class="text-muted">
                            Showing {{ $purchases->firstItem() ?? 0 }} to {{ $purchases->lastItem() ?? 0 }} of {{ $purchases->total() }} entries
                        </div>
                        <div>
                            {{ $purchases->links() }}
                        </div>
                    </div>
                    @endif
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .card {
        border-radius: 0.5rem;
    }
    
    .card-header {
        border-bottom: 1px solid #e3e6f0;
    }
    
    .border-left-primary {
        border-left: 4px solid #4e73df !important;
    }
    
    .border-left-success {
        border-left: 4px solid #1cc88a !important;
    }
    
    .border-left-warning {
        border-left: 4px solid #f6c23e !important;
    }
    
    .border-left-danger {
        border-left: 4px solid #e74a3b !important;
    }
    
    .table th {
        border-top: none;
        font-weight: 600;
        font-size: 0.85rem;
        text-transform: uppercase;
        color: #6c757d;
    }
    
    .badge {
        font-size: 0.75rem;
        padding: 0.35em 0.65em;
    }
    
    .btn-group-sm > .btn {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
        border-radius: 0.2rem;
    }
    
    .table-hover tbody tr:hover {
        background-color: rgba(0, 123, 255, 0.05);
    }
    
    .text-gray-800 {
        color: #5a5c69 !important;
    }
    
    .text-gray-300 {
        color: #dddfeb !important;
    }
    
    .shadow {
        box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.15) !important;
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    $(document).ready(function() {
        // Initialize tooltips
        $('[data-toggle="tooltip"]').tooltip();
        
        // Auto-submit form on date change
        $('input[name="start_date"], input[name="end_date"]').change(function() {
            if ($(this).val()) {
                $(this).closest('form').submit();
            }
        });
        
        // Confirm receive
        $('form[action*="receive"]').submit(function(e) {
            e.preventDefault();
            var form = $(this);
            
            Swal.fire({
                title: 'Confirm Receipt',
                text: "Are you sure you want to mark this purchase as received? This will update stock quantities.",
                icon: 'question',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, mark as received',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    form.unbind('submit').submit();
                }
            });
        });
        
        // Confirm cancel
        $('form[action*="cancel"]').submit(function(e) {
            e.preventDefault();
            var form = $(this);
            
            Swal.fire({
                title: 'Confirm Cancellation',
                text: "Are you sure you want to cancel this purchase? This action cannot be undone.",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#6c757d',
                confirmButtonText: 'Yes, cancel it',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    form.unbind('submit').submit();
                }
            });
        });
        
        // Filter form submit on select change
        $('select[name="status"], select[name="payment_status"], select[name="supplier_id"], select[name="warehouse_id"]').change(function() {
            if ($(this).val()) {
                $(this).closest('form').submit();
            }
        });
    });
</script>
@endpush