@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'Purchase History')

@section('left_sidebar')
@include('front_end.pages.courses.courses_left_sidebar')
@endsection

@section('content')
<div class="bg-white shadow-sm border-0 rounded-3">
    <!-- Header Section -->
    <div class="card border-0 mb-4">
        <div class="card-body p-0">
            <div class="row g-0">
                <div class="col-12">
                    <div class="bg-primary text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center">
                            <a href="{{ route('student.dashboard') }}" class="text-white me-3">
                                <i class="fas fa-arrow-left fa-lg"></i>
                            </a>
                            <div>
                                <h4 class="mb-0 text-white">Purchase History</h4>
                                <p class="mb-0 text-white">Your course purchase transactions</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container py-5">
        @if($enrollments->count() > 0)
            <!-- Filter & Search -->
            <div class="row mb-4">
                <div class="col-md-8">
                    <div class="input-group">
                        <span class="input-group-text bg-white">
                            <i class="fas fa-search"></i>
                        </span>
                        <input type="text" class="form-control" id="searchPurchases" placeholder="Search by course title or transaction ID">
                        <button class="btn btn-primary" type="button" id="searchButton">Search</button>
                    </div>
                </div>
                <div class="col-md-4">
                    <select class="form-select" id="filterPurchases">
                        <option value="all">All Purchases</option>
                        <option value="recent">Last 30 days</option>
                        <option value="oldest">Oldest First</option>
                        <option value="highest">Highest Amount</option>
                        <option value="lowest">Lowest Amount</option>
                    </select>
                </div>
            </div>
            
            <!-- Purchase History Table -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="purchaseTable">
                            <thead class="table-light">
                                <tr>
                                    <th>Date</th>
                                    <th>Course</th>
                                    <th>Transaction ID</th>
                                    <th>Payment Method</th>
                                    <th>Amount</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($enrollments as $enrollment)
                                <tr class="purchase-row">
                                    <td class="align-middle">
                                        <div class="d-flex flex-column">
                                            <span>{{ $enrollment->created_at->format('M d, Y') }}</span>
                                            <small class="text-muted">{{ $enrollment->created_at->format('h:i A') }}</small>
                                        </div>
                                    </td>
                                    <td class="align-middle">
                                        <div class="d-flex align-items-center">
                                            <img src="{{ $enrollment->course->thumbnail ? asset('storage/' . $enrollment->course->thumbnail) : asset('assets/images/course-placeholder.jpg') }}" 
                                                alt="{{ $enrollment->course->title }}" class="rounded me-3" width="50" height="30">
                                            <a href="{{ route('courses.show', $enrollment->course->slug) }}" class="text-decoration-none text-dark course-title">
                                                {{ $enrollment->course->title }}
                                            </a>
                                        </div>
                                    </td>
                                    <td class="align-middle transaction-id">{{ $enrollment->transaction_id }}</td>
                                    <td class="align-middle">
                                        <span class="badge bg-light text-dark">
                                            @if($enrollment->payment_method == 'credit_card')
                                                <i class="fas fa-credit-card me-1"></i> Credit Card
                                            @elseif($enrollment->payment_method == 'paypal')
                                                <i class="fab fa-paypal me-1"></i> PayPal
                                            @elseif($enrollment->payment_method == 'bank_transfer')
                                                <i class="fas fa-university me-1"></i> Bank Transfer
                                            @elseif($enrollment->price_paid == 0)
                                                <i class="fas fa-gift me-1"></i> Free Enrollment
                                            @else
                                                <i class="fas fa-money-bill-wave me-1"></i> {{ ucfirst(str_replace('_', ' ', $enrollment->payment_method ?? 'Other')) }}
                                            @endif
                                        </span>
                                    </td>
                                    <td class="align-middle">
                                        @if($enrollment->price_paid > 0)
                                            <span class="fw-bold">${{ number_format($enrollment->price_paid, 2) }}</span>
                                        @else
                                            <span class="text-success">Free</span>
                                        @endif
                                    </td>
                                    <td class="align-middle">
                                        <span class="badge bg-success">Completed</span>
                                    </td>
                                    <td class="align-middle">
                                        <div class="dropdown">
                                            <button class="btn btn-sm btn-outline-secondary dropdown-toggle" type="button" id="dropdownMenuButton{{ $enrollment->id }}" data-bs-toggle="dropdown" aria-expanded="false">
                                                Actions
                                            </button>
                                            <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="dropdownMenuButton{{ $enrollment->id }}">
                                                <li><a class="dropdown-item" href="{{ route('courses.learn', $enrollment->course->slug) }}"><i class="fas fa-play-circle me-2"></i>Go to Course</a></li>
                                                <li><a class="dropdown-item" href="#" data-bs-toggle="modal" data-bs-target="#receiptModal{{ $enrollment->id }}"><i class="fas fa-file-invoice me-2"></i>View Receipt</a></li>
                                                <li><a class="dropdown-item" href="#" onclick="window.print()"><i class="fas fa-print me-2"></i>Print Receipt</a></li>
                                                @if($enrollment->created_at->diffInDays(now()) <= 30)
                                                <li><a class="dropdown-item text-danger" href="#" data-bs-toggle="modal" data-bs-target="#requestRefundModal{{ $enrollment->id }}"><i class="fas fa-undo-alt me-2"></i>Request Refund</a></li>
                                                @endif
                                            </ul>
                                        </div>
                                        
                                        <!-- Receipt Modal -->
                                        <div class="modal fade" id="receiptModal{{ $enrollment->id }}" tabindex="-1" aria-labelledby="receiptModalLabel{{ $enrollment->id }}" aria-hidden="true">
                                            <div class="modal-dialog modal-dialog-centered">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="receiptModalLabel{{ $enrollment->id }}">Purchase Receipt</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <div class="text-center mb-4">
                                                            <img src="{{ asset('assets/images/logo.png') }}" alt="Logo" height="40">
                                                            <h5 class="mt-2">Online Learning Platform</h5>
                                                        </div>
                                                        <div class="row mb-3">
                                                            <div class="col-6">
                                                                <p class="mb-1 fw-bold">Receipt #:</p>
                                                                <p>{{ substr($enrollment->transaction_id, -8) }}</p>
                                                            </div>
                                                            <div class="col-6 text-end">
                                                                <p class="mb-1 fw-bold">Date:</p>
                                                                <p>{{ $enrollment->created_at->format('M d, Y') }}</p>
                                                            </div>
                                                        </div>
                                                        <hr>
                                                        <div class="row mb-3">
                                                            <div class="col-6">
                                                                <p class="mb-1 fw-bold">Customer:</p>
                                                                <p>{{ Auth::user()->name }}<br>
                                                                {{ Auth::user()->email }}</p>
                                                            </div>
                                                            <div class="col-6 text-end">
                                                                <p class="mb-1 fw-bold">Payment Method:</p>
                                                                <p>{{ ucfirst(str_replace('_', ' ', $enrollment->payment_method ?? 'N/A')) }}</p>
                                                            </div>
                                                        </div>
                                                        <div class="table-responsive overflow-visible">
                                                            <table class="table table-bordered">
                                                                <thead class="table-light">
                                                                    <tr>
                                                                        <th>Item</th>
                                                                        <th class="text-end">Amount</th>
                                                                    </tr>
                                                                </thead>
                                                                <tbody>
                                                                    <tr>
                                                                        <td>{{ $enrollment->course->title }}</td>
                                                                        <td class="text-end">${{ number_format($enrollment->price_paid, 2) }}</td>
                                                                    </tr>
                                                                    <tr>
                                                                        <td class="fw-bold">Total</td>
                                                                        <td class="text-end fw-bold">${{ number_format($enrollment->price_paid, 2) }}</td>
                                                                    </tr>
                                                                </tbody>
                                                            </table>
                                                        </div>
                                                        <div class="text-center text-muted small">
                                                            <p>Thank you for your purchase!</p>
                                                            <p>For any questions, please contact support@example.com</p>
                                                        </div>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                        <button type="button" class="btn btn-primary" onclick="window.print()">
                                                            <i class="fas fa-print me-2"></i>Print
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Refund Modal -->
                                        @if($enrollment->created_at->diffInDays(now()) <= 30)
                                        <div class="modal fade" id="requestRefundModal{{ $enrollment->id }}" tabindex="-1" aria-labelledby="requestRefundModalLabel{{ $enrollment->id }}" aria-hidden="true">
                                            <div class="modal-dialog modal-dialog-centered">
                                                <div class="modal-content">
                                                    <div class="modal-header">
                                                        <h5 class="modal-title" id="requestRefundModalLabel{{ $enrollment->id }}">Request Refund</h5>
                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                    </div>
                                                    <div class="modal-body">
                                                        <div class="alert alert-info">
                                                            <i class="fas fa-info-circle me-2"></i>
                                                            <span>Refunds are processed according to our refund policy. You are eligible to request a refund within 30 days of purchase.</span>
                                                        </div>
                                                        <form>
                                                            <div class="mb-3">
                                                                <label for="refundReason{{ $enrollment->id }}" class="form-label">Reason for Refund</label>
                                                                <select class="form-select" id="refundReason{{ $enrollment->id }}" required>
                                                                    <option value="">Select a reason</option>
                                                                    <option value="not_satisfied">Not satisfied with the course</option>
                                                                    <option value="technical_issues">Technical issues</option>
                                                                    <option value="accidental_purchase">Accidental purchase</option>
                                                                    <option value="content_mismatch">Course content different than expected</option>
                                                                    <option value="other">Other reason</option>
                                                                </select>
                                                            </div>
                                                            <div class="mb-3">
                                                                <label for="refundDetails{{ $enrollment->id }}" class="form-label">Additional Details</label>
                                                                <textarea class="form-control" id="refundDetails{{ $enrollment->id }}" rows="3" placeholder="Please provide more details about your refund request"></textarea>
                                                            </div>
                                                        </form>
                                                    </div>
                                                    <div class="modal-footer">
                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                        <button type="button" class="btn btn-danger" id="submitRefund{{ $enrollment->id }}">Submit Refund Request</button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        @endif
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            
            <!-- Pagination -->
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <p class="text-muted mb-0">Showing {{ $enrollments->firstItem() ?? 0 }}-{{ $enrollments->lastItem() ?? 0 }} of {{ $enrollments->total() }} transactions</p>
                </div>
                <div>
                    {{ $enrollments->links('pagination::bootstrap-5') }}
                </div>
            </div>
            
            <!-- Purchase Summary -->
            <div class="row mt-5">
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm text-center">
                        <div class="card-body">
                            <div class="mb-3">
                                <i class="fas fa-shopping-cart fa-3x text-primary opacity-75"></i>
                            </div>
                            <h2 class="mb-1">{{ $enrollments->total() }}</h2>
                            <p class="text-muted mb-0">Total Purchases</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm text-center">
                        <div class="card-body">
                            <div class="mb-3">
                                <i class="fas fa-dollar-sign fa-3x text-success opacity-75"></i>
                            </div>
                            <h2 class="mb-1">${{ number_format($enrollments->sum('price_paid'), 2) }}</h2>
                            <p class="text-muted mb-0">Total Spent</p>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="card border-0 shadow-sm text-center">
                        <div class="card-body">
                            <div class="mb-3">
                                <i class="fas fa-percentage fa-3x text-danger opacity-75"></i>
                            </div>
                            @php
                                $totalSavings = 0;
                                foreach($enrollments as $enrollment) {
                                    if($enrollment->course->price > 0) {
                                        $regularPrice = $enrollment->course->price;
                                        $paidPrice = $enrollment->price_paid;
                                        $totalSavings += ($regularPrice - $paidPrice);
                                    }
                                }
                            @endphp
                            <h2 class="mb-1">${{ number_format($totalSavings, 2) }}</h2>
                            <p class="text-muted mb-0">Total Savings</p>
                        </div>
                    </div>
                </div>
            </div>
        @else
            <!-- Empty State -->
            <div class="text-center py-5">
                <i class="fas fa-receipt fa-4x text-muted mb-4"></i>
                <h4>No Purchase History</h4>
                <p class="text-muted mb-4">You haven't made any course purchases yet.</p>
                <a href="{{ route('courses.index') }}" class="btn btn-primary">Browse Courses</a>
            </div>
        @endif
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        // Search functionality
        $('#searchButton').on('click', function() {
            const searchTerm = $('#searchPurchases').val().toLowerCase();
            
            $('.purchase-row').each(function() {
                const courseTitle = $(this).find('.course-title').text().toLowerCase();
                const transactionId = $(this).find('.transaction-id').text().toLowerCase();
                
                if (courseTitle.includes(searchTerm) || transactionId.includes(searchTerm)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        });
        
        // Filter functionality
        $('#filterPurchases').on('change', function() {
            const filterValue = $(this).val();
            const now = new Date();
            const thirtyDaysAgo = new Date();
            thirtyDaysAgo.setDate(now.getDate() - 30);
            
            $('.purchase-row').each(function() {
                const row = $(this);
                
                switch(filterValue) {
                    case 'recent':
                        // Get date from first column
                        const dateText = row.find('td:first-child span:first-child').text();
                        const purchaseDate = new Date(dateText);
                        
                        if (purchaseDate >= thirtyDaysAgo) {
                            row.show();
                        } else {
                            row.hide();
                        }
                        break;
                    
                    case 'all':
                    default:
                        row.show();
                        break;
                }
            });
            
            // For highest/lowest, we need to sort the table
            if (filterValue === 'highest' || filterValue === 'lowest') {
                const rows = $('#purchaseTable tbody tr').get();
                
                rows.sort(function(a, b) {
                    const priceA = $(a).find('td:nth-child(5) .fw-bold').text();
                    const priceB = $(b).find('td:nth-child(5) .fw-bold').text();
                    
                    // Extract numeric values
                    const valueA = parseFloat(priceA.replace('$', '').replace(',', '')) || 0;
                    const valueB = parseFloat(priceB.replace('$', '').replace(',', '')) || 0;
                    
                    if (filterValue === 'highest') {
                        return valueB - valueA;
                    } else {
                        return valueA - valueB;
                    }
                });
                
                $.each(rows, function(index, row) {
                    $('#purchaseTable tbody').append(row);
                });
            }
        });
        
        // Refund request submission
        $('[id^=submitRefund]').on('click', function() {
            const id = $(this).attr('id').replace('submitRefund', '');
            const reason = $('#refundReason' + id).val();
            
            if (!reason) {
                alert('Please select a reason for your refund request.');
                return;
            }
            
            alert('Your refund request has been submitted. Our team will review it and get back to you within 2-3 business days.');
            $('#requestRefundModal' + id).modal('hide');
        });
    });
</script>
@endpush
@endsection