@extends('front_end.layouts.home')

@php
$showRightSidebar = false;
@endphp
@section('title', 'Manage Coupons - ' . $course->title)

@section('left_sidebar')
@include('front_end.pages.courses.instructor_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-dark text-white p-4 rounded-top-3">
                        <div class="d-flex align-items-center">
                            <a href="{{ route('instructor.courses.edit', $course->id) }}" class="text-white me-3">
                                <i class="fas fa-arrow-left fa-lg"></i>
                            </a>
                            <div>
                                <h4 class="mb-0 text-white">Manage Coupons</h4>
                                <p class="mb-0 text-white">{{ $course->title }}</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container py-5">
        <div class="row">
            <div class="col-lg-8">
                <!-- Coupons List -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-transparent d-flex justify-content-between align-items-center">
                        <h5 class="mb-0">Course Coupons</h5>
                        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCouponModal">
                            <i class="fas fa-plus-circle me-2"></i>Create Coupon
                        </button>
                    </div>
                    <div class="card-body p-0">
                        @if($course->coupons && $course->coupons->count() > 0)
                        <div class="table-responsive">
                            <table class="table table-hover mb-0">
                                <thead class="table-light">
                                    <tr>
                                        <th>Code</th>
                                        <th>Discount</th>
                                        <th>Usage / Limit</th>
                                        <th>Expires</th>
                                        <th>Status</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    @foreach($course->coupons as $coupon)
                                    <tr>
                                        <td>
                                            <span class="badge bg-dark">{{ $coupon->code }}</span>
                                            <button class="btn btn-sm text-primary border-0 copy-btn" data-clipboard-text="{{ $coupon->code }}" title="Copy to clipboard">
                                                <i class="fas fa-copy"></i>
                                            </button>
                                        </td>
                                        <td>
                                            @if($coupon->discount_type == 'percentage')
                                            <span class="text-success">{{ $coupon->discount_amount }}% OFF</span>
                                            @else
                                            <span class="text-success">${{ number_format($coupon->discount_amount, 2) }} OFF</span>
                                            @endif
                                        </td>
                                        <td>
                                            {{ $coupon->usage_count }} / {{ $coupon->usage_limit ?? '∞' }}
                                            @if($coupon->usage_limit && $coupon->usage_count >= $coupon->usage_limit)
                                            <span class="badge bg-danger ms-1">Limit reached</span>
                                            @endif
                                        </td>
                                        <td>
                                            @if($coupon->expires_at)
                                                @if($coupon->expires_at < now())
                                                <span class="text-danger">Expired ({{ $coupon->expires_at->format('M d, Y') }})</span>
                                                @else
                                                <span>{{ $coupon->expires_at->format('M d, Y') }}</span>
                                                <div class="small text-muted">{{ $coupon->expires_at->diffForHumans() }}</div>
                                                @endif
                                            @else
                                            <span class="text-muted">Never expires</span>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="form-check form-switch">
                                                <form action="{{ route('instructor.courses.toggleCoupon', $coupon->id) }}" method="POST" class="toggle-form">
                                                    @csrf
                                                    <input class="form-check-input toggle-status" type="checkbox" role="switch" id="toggle{{ $coupon->id }}" 
                                                        {{ $coupon->is_active ? 'checked' : '' }} data-coupon-id="{{ $coupon->id }}">
                                                </form>
                                                <span class="badge bg-{{ $coupon->is_active ? 'success' : 'secondary' }} ms-2">
                                                    {{ $coupon->is_active ? 'Active' : 'Inactive' }}
                                                </span>
                                            </div>
                                        </td>
                                        <td>
                                            <div class="d-flex">
                                                <button type="button" class="btn btn-sm btn-outline-primary me-2" 
                                                    data-bs-toggle="modal" data-bs-target="#viewCouponModal{{ $coupon->id }}">
                                                    <i class="fas fa-eye"></i>
                                                </button>
                                                <form action="{{ route('instructor.courses.deleteCoupon', $coupon->id) }}" method="POST" onsubmit="return confirm('Are you sure you want to delete this coupon?');">
                                                    @csrf
                                                    @method('DELETE')
                                                    <button type="submit" class="btn btn-sm btn-outline-danger">
                                                        <i class="fas fa-trash"></i>
                                                    </button>
                                                </form>
                                            </div>
                                            
                                            <!-- View Coupon Modal -->
                                            <div class="modal fade" id="viewCouponModal{{ $coupon->id }}" tabindex="-1" aria-labelledby="viewCouponModalLabel{{ $coupon->id }}" aria-hidden="true">
                                                <div class="modal-dialog modal-dialog-centered">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title" id="viewCouponModalLabel{{ $coupon->id }}">Coupon Details</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">
                                                                <div class="display-6 mb-2">{{ $coupon->code }}</div>
                                                                <div class="badge bg-success fs-6 mb-3">
                                                                    @if($coupon->discount_type == 'percentage')
                                                                    {{ $coupon->discount_amount }}% OFF
                                                                    @else
                                                                    ${{ number_format($coupon->discount_amount, 2) }} OFF
                                                                    @endif
                                                                </div>
                                                                <div class="d-flex justify-content-center">
                                                                    <button class="btn btn-sm btn-outline-primary me-2 copy-btn" data-clipboard-text="{{ $coupon->code }}">
                                                                        <i class="fas fa-copy me-1"></i>Copy Code
                                                                    </button>
                                                                    <button class="btn btn-sm btn-outline-primary copy-btn" 
                                                                        data-clipboard-text="{{ route('courses.show', $course->slug) }}?coupon={{ $coupon->code }}">
                                                                        <i class="fas fa-link me-1"></i>Copy URL with Coupon
                                                                    </button>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-6">
                                                                    <div class="fw-bold mb-1">Discount Type</div>
                                                                    <div>{{ ucfirst($coupon->discount_type) }}</div>
                                                                </div>
                                                                <div class="col-6">
                                                                    <div class="fw-bold mb-1">Discount Amount</div>
                                                                    <div>
                                                                        @if($coupon->discount_type == 'percentage')
                                                                        {{ $coupon->discount_amount }}%
                                                                        @else
                                                                        ${{ number_format($coupon->discount_amount, 2) }}
                                                                        @endif
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-6">
                                                                    <div class="fw-bold mb-1">Usage</div>
                                                                    <div>{{ $coupon->usage_count }} / {{ $coupon->usage_limit ?? '∞' }}</div>
                                                                </div>
                                                                <div class="col-6">
                                                                    <div class="fw-bold mb-1">Status</div>
                                                                    <div>
                                                                        <span class="badge bg-{{ $coupon->is_active ? 'success' : 'secondary' }}">
                                                                            {{ $coupon->is_active ? 'Active' : 'Inactive' }}
                                                                        </span>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            
                                                            <div class="row mb-3">
                                                                <div class="col-6">
                                                                    <div class="fw-bold mb-1">Created</div>
                                                                    <div>{{ $coupon->created_at->format('M d, Y') }}</div>
                                                                </div>
                                                                <div class="col-6">
                                                                    <div class="fw-bold mb-1">Expires</div>
                                                                    <div>
                                                                        @if($coupon->expires_at)
                                                                            @if($coupon->expires_at < now())
                                                                            <span class="text-danger">Expired</span>
                                                                            @else
                                                                            {{ $coupon->expires_at->format('M d, Y') }}
                                                                            @endif
                                                                        @else
                                                                        Never expires
                                                                        @endif
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            
                                                            @if($coupon->usage_count > 0)
                                                            <div class="alert alert-info mb-0">
                                                                <div class="fw-bold mb-2">Coupon Usage Stats</div>
                                                                <div class="mb-2">
                                                                    <div class="fw-bold mb-1">Total Revenue with Coupon</div>
                                                                    <div>${{ number_format($coupon->total_revenue ?? 0, 2) }}</div>
                                                                </div>
                                                                <div>
                                                                    <div class="fw-bold mb-1">Total Discount Amount</div>
                                                                    <div>${{ number_format($coupon->total_discount ?? 0, 2) }}</div>
                                                                </div>
                                                            </div>
                                                            @endif
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                            <form action="{{ route('instructor.courses.toggleCoupon', $coupon->id) }}" method="POST">
                                                                @csrf
                                                                <button type="submit" class="btn btn-{{ $coupon->is_active ? 'warning' : 'success' }}">
                                                                    {{ $coupon->is_active ? 'Deactivate' : 'Activate' }}
                                                                </button>
                                                            </form>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        @else
                        <div class="text-center py-5">
                            <i class="fas fa-tags fa-3x text-muted mb-3"></i>
                            <h5>No Coupons Yet</h5>
                            <p class="text-muted mb-4">Create coupons to offer special discounts to your students.</p>
                            <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCouponModal">
                                <i class="fas fa-plus-circle me-2"></i>Create Your First Coupon
                            </button>
                        </div>
                        @endif
                    </div>
                </div>
            </div>
            
            <!-- Sidebar -->
            <div class="col-lg-4">
                <!-- Coupon Info Card -->
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">About Coupons</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-4">
                            <h6 class="fw-bold"><i class="fas fa-info-circle me-2 text-primary"></i>What are coupons?</h6>
                            <p class="text-muted small mb-0">
                                Coupons allow you to offer discounts on your course to attract more students. You can create different coupons with various discount amounts and expiration dates.
                            </p>
                        </div>
                        <div class="mb-4">
                            <h6 class="fw-bold"><i class="fas fa-lightbulb me-2 text-warning"></i>Best Practices</h6>
                            <ul class="text-muted small mb-0">
                                <li>Create limited-time coupons to create urgency</li>
                                <li>Use descriptive coupon codes like "SPRING30" for a 30% spring discount</li>
                                <li>Set usage limits for exclusive promotions</li>
                                <li>Share coupons on social media to drive enrollment</li>
                            </ul>
                        </div>
                        <div>
                            <h6 class="fw-bold"><i class="fas fa-percentage me-2 text-success"></i>Discount Types</h6>
                            <div class="row mb-2">
                                <div class="col-6">
                                    <div class="fw-bold text-muted small">Percentage</div>
                                    <p class="text-muted small mb-0">
                                        Applies a percentage discount to the course price.
                                    </p>
                                </div>
                                <div class="col-6">
                                    <div class="fw-bold text-muted small">Fixed Amount</div>
                                    <p class="text-muted small mb-0">
                                        Applies a fixed dollar amount discount.
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Coupon Stats Card -->
                @if($course->coupons && $course->coupons->count() > 0)
                <div class="card border-0 shadow-sm mb-4">
                    <div class="card-header bg-transparent">
                        <h5 class="mb-0">Coupon Statistics</h5>
                    </div>
                    <div class="card-body">
                        <div class="row text-center g-3">
                            <div class="col-6">
                                <div class="p-3 bg-light rounded-3">
                                    <div class="h3 mb-1">{{ $course->coupons->count() }}</div>
                                    <div class="text-muted small">Total Coupons</div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="p-3 bg-light rounded-3">
                                    <div class="h3 mb-1">{{ $course->coupons->sum('usage_count') }}</div>
                                    <div class="text-muted small">Total Redemptions</div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="p-3 bg-light rounded-3">
                                    <div class="h3 mb-1">{{ $course->coupons->where('is_active', true)->count() }}</div>
                                    <div class="text-muted small">Active Coupons</div>
                                </div>
                            </div>
                            <div class="col-6">
                                <div class="p-3 bg-light rounded-3">
                                    <div class="h3 mb-1">${{ number_format($course->coupons->sum('total_discount') ?? 0, 2) }}</div>
                                    <div class="text-muted small">Total Discounts</div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                @endif
            </div>
        </div>
    </div>
</div>

<!-- Add Coupon Modal -->
<div class="modal fade" id="addCouponModal" tabindex="-1" aria-labelledby="addCouponModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <form action="{{ route('instructor.courses.addCoupon', $course->id) }}" method="POST">
                @csrf
                <div class="modal-header">
                    <h5 class="modal-title" id="addCouponModalLabel">Create New Coupon</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label for="code" class="form-label">Coupon Code <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" class="form-control @error('code') is-invalid @enderror" id="code" name="code" required>
                            <button class="btn btn-outline-secondary" type="button" id="generateCode">Generate</button>
                        </div>
                        <div class="form-text">Enter a unique code for this coupon (e.g., SPRING30, WELCOME50).</div>
                        @error('code')
                        <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="discount_type" class="form-label">Discount Type <span class="text-danger">*</span></label>
                            <select class="form-select @error('discount_type') is-invalid @enderror" id="discount_type" name="discount_type" required>
                                <option value="percentage">Percentage (%)</option>
                                <option value="fixed">Fixed Amount ($)</option>
                            </select>
                            @error('discount_type')
                            <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="col-md-6">
                            <label for="discount_amount" class="form-label">Discount Amount <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <input type="number" class="form-control @error('discount_amount') is-invalid @enderror" id="discount_amount" name="discount_amount" min="1" required>
                                <span class="input-group-text" id="discount_symbol">%</span>
                            </div>
                            <div class="form-text" id="discount_hint">Enter a percentage discount (1-100)</div>
                            @error('discount_amount')
                            <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <label for="usage_limit" class="form-label">Usage Limit</label>
                            <input type="number" class="form-control @error('usage_limit') is-invalid @enderror" id="usage_limit" name="usage_limit" min="1">
                            <div class="form-text">Maximum number of times this coupon can be used (leave blank for unlimited)</div>
                            @error('usage_limit')
                            <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                        <div class="col-md-6">
                            <label for="expires_at" class="form-label">Expiration Date</label>
                            <input type="date" class="form-control @error('expires_at') is-invalid @enderror" id="expires_at" name="expires_at" min="{{ date('Y-m-d') }}">
                            <div class="form-text">When this coupon will expire (leave blank for no expiration)</div>
                            @error('expires_at')
                            <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>
                    </div>
                    
                    <div class="form-check form-switch mb-3">
                        <input class="form-check-input" type="checkbox" role="switch" id="is_active" name="is_active" value="1" checked>
                        <label class="form-check-label" for="is_active">Active</label>
                        <div class="form-text">Activate this coupon immediately</div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Create Coupon</button>
                </div>
            </form>
        </div>
    </div>
</div>

@push('styles')
<style>
    .copy-btn {
        cursor: pointer;
    }
    
    .copy-btn:hover {
        background-color: rgba(0, 0, 0, 0.05);
    }
</style>
@endpush

@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js"></script>
<script>
    $(document).ready(function() {
        // Initialize clipboard.js
        new ClipboardJS('.copy-btn').on('success', function(e) {
            const originalText = $(e.trigger).html();
            $(e.trigger).html('<i class="fas fa-check text-success"></i> Copied!');
            
            setTimeout(function() {
                $(e.trigger).html(originalText);
            }, 2000);
            
            e.clearSelection();
        });
        
        // Generate random coupon code
        $('#generateCode').on('click', function() {
            const prefix = ['LEARN', 'SAVE', 'SALE', 'NEW', 'SPECIAL', 'OFFER'];
            const randomPrefix = prefix[Math.floor(Math.random() * prefix.length)];
            const randomNum = Math.floor(Math.random() * 90) + 10;
            const couponCode = randomPrefix + randomNum;
            
            $('#code').val(couponCode);
        });
        
        // Toggle discount type label and hint
        $('#discount_type').on('change', function() {
            if ($(this).val() === 'percentage') {
                $('#discount_symbol').text('%');
                $('#discount_hint').text('Enter a percentage discount (1-100)');
                $('#discount_amount').attr('max', 100);
            } else {
                $('#discount_symbol').text('$');
                $('#discount_hint').text('Enter a fixed amount discount (max: ${{ $course->price }})');
                $('#discount_amount').attr('max', {{ $course->price }});
            }
        });
        
        // Toggle coupon status
        $('.toggle-status').on('change', function() {
            const couponId = $(this).data('coupon-id');
            $(this).closest('form.toggle-form').submit();
        });
    });
</script>
@endpush
@endsection