@extends('layouts.business')

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

@section('content')
<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h2 class="fw-bold mb-1">Redemptions Management</h2>
        <p class="text-muted mb-0">Track and manage offer redemptions</p>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#scanQRModal">
        <i class="bi bi-qr-code-scan me-2"></i>Scan QR Code
    </button>
</div>

<!-- Stats Cards -->
<div class="row g-4 mb-4">
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                <i class="bi bi-qr-code text-white"></i>
            </div>
            <div class="stat-label">Total Redemptions</div>
            <div class="stat-value">{{ number_format($stats['total'] ?? 0) }}</div>
            <div class="stat-change positive">
                <i class="bi bi-arrow-up"></i> 15% vs last week
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
                <i class="bi bi-check-circle text-white"></i>
            </div>
            <div class="stat-label">Today</div>
            <div class="stat-value">{{ $stats['today'] ?? 0 }}</div>
            <small class="text-muted">{{ $stats['today_percentage'] ?? 0 }}% of total</small>
        </div>
    </div>
    <div class="col-md-3">
        <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <i class="bi bi-clock-history text-white"></i>
            </div>
            <div class="stat-label">This Week</div>
            <div class="stat-value">{{ number_format($stats['week'] ?? 0) }}</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%);">
                <i class="bi bi-calendar-month text-white"></i>
            </div>
            <div class="stat-label">This Month</div>
            <div class="stat-value">{{ number_format($stats['month'] ?? 0) }}</div>
        </div>
    </div>
</div>

<!-- Filters -->
<div class="table-card mb-4">
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-2">
                <input type="date" class="form-control" name="date_from" value="{{ request('date_from') }}" placeholder="From Date">
            </div>
            <div class="col-md-2">
                <input type="date" class="form-control" name="date_to" value="{{ request('date_to') }}" placeholder="To Date">
            </div>
            <div class="col-md-2">
                <select class="form-select" name="venue_id">
                    <option value="">All Venues</option>
                    @foreach($venues ?? [] as $venue)
                        <option value="{{ $venue->id }}" {{ request('venue_id') == $venue->id ? 'selected' : '' }}>
                            {{ $venue->name }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-2">
                <select class="form-select" name="offer_id">
                    <option value="">All Offers</option>
                    @foreach($offers ?? [] as $offer)
                        <option value="{{ $offer->id }}" {{ request('offer_id') == $offer->id ? 'selected' : '' }}>
                            {{ $offer->title }}
                        </option>
                    @endforeach
                </select>
            </div>
            <div class="col-md-2">
                <select class="form-select" name="status">
                    <option value="">All Status</option>
                    <option value="redeemed" {{ request('status') === 'redeemed' ? 'selected' : '' }}>Redeemed</option>
                    <option value="cancelled" {{ request('status') === 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                    <option value="expired" {{ request('status') === 'expired' ? 'selected' : '' }}>Expired</option>
                </select>
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="bi bi-search me-2"></i>Filter
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Redemptions Table -->
<div class="table-card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0 fw-bold">Recent Redemptions</h5>
        <div class="btn-group btn-group-sm">
            <button class="btn btn-outline-primary" onclick="exportData('csv')">
                <i class="bi bi-file-earmark-spreadsheet me-1"></i>CSV
            </button>
            <button class="btn btn-outline-primary" onclick="exportData('pdf')">
                <i class="bi bi-file-earmark-pdf me-1"></i>PDF
            </button>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover mb-0">
                <thead>
                    <tr>
                        <th>Code</th>
                        <th>Customer</th>
                        <th>Offer</th>
                        <th>Venue</th>
                        <th>Redeemed By</th>
                        <th>Date & Time</th>
                        <th>Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($redemptions as $redemption)
                    <tr>
                        <td>
                            <div class="d-flex align-items-center">
                                <div class="me-2" style="cursor: pointer;" data-bs-toggle="modal" data-bs-target="#qrModal{{ $redemption->id }}">
                                    <i class="bi bi-qr-code fs-4 text-primary"></i>
                                </div>
                                <div>
                                    <div class="fw-semibold font-monospace">{{ $redemption->code }}</div>
                                    <small class="text-muted">Click QR to view</small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <div class="d-flex align-items-center">
                                <img src="{{ $redemption->user->avatar ?? 'https://ui-avatars.com/api/?name='.$redemption->user->full_name }}"
                                     class="rounded-circle me-2" width="32" height="32" alt="Avatar">
                                <div>
                                    <div class="fw-semibold">{{ $redemption->user->full_name }}</div>
                                    <small class="text-muted">{{ $redemption->user->phone }}</small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <div class="fw-semibold">{{ Str::limit($redemption->offer->title, 30) }}</div>
                            <small class="text-muted">{{ $redemption->offer->discount_value }}% OFF</small>
                        </td>
                        <td>{{ $redemption->venue->name ?? 'N/A' }}</td>
                        <td>
                            <div class="d-flex align-items-center">
                                <img src="{{ $redemption->redeemedBy->avatar ?? 'https://ui-avatars.com/api/?name='.$redemption->redeemedBy->full_name }}"
                                     class="rounded-circle me-2" width="24" height="24" alt="Avatar">
                                <span>{{ $redemption->redeemedBy->full_name ?? 'System' }}</span>
                            </div>
                        </td>
                        <td>
                            <div>{{ $redemption->redeemed_at->format('M d, Y') }}</div>
                            <small class="text-muted">{{ $redemption->redeemed_at->format('h:i A') }}</small>
                        </td>
                        <td>
                            @if($redemption->status === 'redeemed')
                                <span class="badge bg-success">
                                    <i class="bi bi-check-circle me-1"></i>Redeemed
                                </span>
                            @elseif($redemption->status === 'cancelled')
                                <span class="badge bg-danger">
                                    <i class="bi bi-x-circle me-1"></i>Cancelled
                                </span>
                            @else
                                <span class="badge bg-secondary">
                                    <i class="bi bi-clock me-1"></i>Expired
                                </span>
                            @endif
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#detailsModal{{ $redemption->id }}">
                                    <i class="bi bi-eye"></i>
                                </button>
                                @if($redemption->status === 'redeemed')
                                <button class="btn btn-outline-danger" onclick="cancelRedemption({{ $redemption->id }})">
                                    <i class="bi bi-x-lg"></i>
                                </button>
                                @endif
                            </div>
                        </td>
                    </tr>

                    <!-- QR Code Modal -->
                    <div class="modal fade" id="qrModal{{ $redemption->id }}" tabindex="-1">
                        <div class="modal-dialog modal-dialog-centered">
                            <div class="modal-content">
                                <div class="modal-header border-0">
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body text-center py-4">
                                    <h5 class="mb-3">Redemption QR Code</h5>
                                    <div class="mb-3">
                                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data={{ $redemption->code }}"
                                             alt="QR Code" class="img-fluid">
                                    </div>
                                    <div class="font-monospace fw-bold mb-2">{{ $redemption->code }}</div>
                                    <small class="text-muted">{{ $redemption->offer->title }}</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Details Modal -->
                    <div class="modal fade" id="detailsModal{{ $redemption->id }}" tabindex="-1">
                        <div class="modal-dialog modal-lg">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <h5 class="modal-title">Redemption Details</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                </div>
                                <div class="modal-body">
                                    <div class="row g-3">
                                        <div class="col-md-6">
                                            <label class="text-muted small">Redemption Code</label>
                                            <div class="fw-bold font-monospace">{{ $redemption->code }}</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">Status</label>
                                            <div>
                                                @if($redemption->status === 'redeemed')
                                                    <span class="badge bg-success">Redeemed</span>
                                                @elseif($redemption->status === 'cancelled')
                                                    <span class="badge bg-danger">Cancelled</span>
                                                @else
                                                    <span class="badge bg-secondary">Expired</span>
                                                @endif
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">Customer Name</label>
                                            <div class="fw-semibold">{{ $redemption->user->full_name }}</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">Customer Phone</label>
                                            <div class="fw-semibold">{{ $redemption->user->phone }}</div>
                                        </div>
                                        <div class="col-md-12">
                                            <label class="text-muted small">Offer</label>
                                            <div class="fw-semibold">{{ $redemption->offer->title }}</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">Venue</label>
                                            <div class="fw-semibold">{{ $redemption->venue->name }}</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">Redeemed By</label>
                                            <div class="fw-semibold">{{ $redemption->redeemedBy->full_name ?? 'System' }}</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">Redemption Date</label>
                                            <div class="fw-semibold">{{ $redemption->redeemed_at->format('M d, Y h:i A') }}</div>
                                        </div>
                                        <div class="col-md-6">
                                            <label class="text-muted small">IP Address</label>
                                            <div class="font-monospace">{{ $redemption->ip_address ?? 'N/A' }}</div>
                                        </div>
                                        @if($redemption->notes)
                                        <div class="col-12">
                                            <label class="text-muted small">Notes</label>
                                            <div class="bg-light p-3 rounded">{{ $redemption->notes }}</div>
                                        </div>
                                        @endif
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                </div>
                            </div>
                        </div>
                    </div>
                    @empty
                    <tr>
                        <td colspan="8" class="text-center py-5">
                            <i class="bi bi-qr-code fs-1 text-muted d-block mb-3"></i>
                            <h5>No redemptions found</h5>
                            <p class="text-muted">Redemptions will appear here once customers start using your offers</p>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>
    </div>
    @if($redemptions->hasPages())
    <div class="card-footer bg-white">
        {{ $redemptions->links() }}
    </div>
    @endif
</div>

<!-- Scan QR Code Modal -->
<div class="modal fade" id="scanQRModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Scan QR Code</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="row">
                    <div class="col-md-6">
                        <div id="qr-reader" style="width: 100%; min-height: 300px; border: 2px dashed #ddd; border-radius: 8px; display: flex; align-items: center; justify-content: center; background: #f8f9fa;">
                            <div class="text-center p-4">
                                <i class="bi bi-camera fs-1 text-muted mb-3"></i>
                                <p class="text-muted">Click "Start Scanning" to activate camera</p>
                            </div>
                        </div>
                        <button id="startScanBtn" class="btn btn-primary w-100 mt-3">
                            <i class="bi bi-camera me-2"></i>Start Scanning
                        </button>
                    </div>
                    <div class="col-md-6">
                        <div class="text-center mb-3">
                            <h6>Or Enter Code Manually</h6>
                        </div>
                        <form id="manualRedemptionForm" action="{{ route('business.redemptions.manual') }}" method="POST">
                            @csrf
                            <div class="mb-3">
                                <label class="form-label">Redemption Code</label>
                                <input type="text" class="form-control form-control-lg text-center font-monospace"
                                       name="code" id="manualCode" placeholder="XXXX-XXXX-XXXX" required>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Notes (Optional)</label>
                                <textarea class="form-control" name="notes" rows="3"></textarea>
                            </div>
                            <button type="submit" class="btn btn-success btn-lg w-100">
                                <i class="bi bi-check-lg me-2"></i>Redeem Offer
                            </button>
                        </form>

                        <div class="alert alert-info mt-4">
                            <i class="bi bi-info-circle me-2"></i>
                            <strong>How to Redeem:</strong>
                            <ol class="mb-0 mt-2 ps-3">
                                <li>Ask customer to show their QR code</li>
                                <li>Scan the code or enter it manually</li>
                                <li>Verify the offer details</li>
                                <li>Complete the redemption</li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
function exportData(format) {
    const params = new URLSearchParams(window.location.search);
    params.append('export', format);
    window.location.href = '{{ route("business.redemptions.export") }}?' + params.toString();
}

function cancelRedemption(id) {
    if (confirm('Are you sure you want to cancel this redemption?')) {
        fetch(`/business/redemptions/${id}/cancel`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Content-Type': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert(data.message || 'Failed to cancel redemption');
            }
        });
    }
}

// QR Scanner initialization (requires html5-qrcode library)
document.getElementById('startScanBtn')?.addEventListener('click', function() {
    // Initialize QR scanner here
    alert('QR Scanner will be initialized with camera access. Requires html5-qrcode library.');
    // This would integrate with a library like html5-qrcode
});
</script>
@endpush
