@extends('layouts.app')

@section('title', 'New Airtime Payment')

@section('content')
<div class="dashboard-container airtime-payment-page">
    <div class="dashboard-header">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h2 class="mb-0">
                    <i class="fas fa-phone-alt me-2"></i>New Airtime Payment
                </h2>
                <p class="text-muted mb-0">Add airtime topup for station mobile numbers</p>
            </div>
            <div class="col-md-6 text-end">
                <a href="{{ route('payments.airtime.index') }}" class="btn btn-secondary">
                    <i class="fas fa-arrow-left me-1"></i> Back to List
                </a>
            </div>
        </div>
    </div>

    <!-- Stats Cards Section -->
    <div class="stats-grid-wrapper mb-5">
        <div class="row g-4">
            <div class="col-xl-3 col-lg-6 col-md-6">
                <div class="card stat-card bg-primary h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-2 text-white-50">Station Count</h6>
                                <div class="d-flex align-items-baseline gap-2 flex-wrap">
                                    <h4 class="mb-0 text-white">{{ $stations->count() }}</h4>
                                    <span class="badge bg-white bg-opacity-25 text-white">
                                        <i class="fas fa-arrow-up me-1"></i>Total
                                    </span>
                                </div>
                                <small class="text-white-50 mt-2 d-block">
                                    <i class="fas fa-building me-1"></i>Registered stations
                                </small>
                            </div>
                            <div class="icon-circle bg-white-10 flex-shrink-0 ms-3">
                                <i class="fas fa-building text-white"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-lg-6 col-md-6">
                <div class="card stat-card bg-success h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-2 text-white-50">Active Topups</h6>
                                <div class="d-flex align-items-baseline gap-2 flex-wrap">
                                    <h4 class="mb-0 text-white">{{ $stats['active_topups'] }}</h4>
                                    <span class="badge bg-white bg-opacity-25 text-white">
                                        <i class="fas fa-chart-line me-1"></i>Active
                                    </span>
                                </div>
                                <small class="text-white-50 mt-2 d-block">
                                    <i class="fas fa-signal me-1"></i>Currently active
                                </small>
                            </div>
                            <div class="icon-circle bg-white-10 flex-shrink-0 ms-3">
                                <i class="fas fa-signal text-white"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-lg-6 col-md-6">
                <div class="card stat-card bg-warning h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-2 text-white-50">Expiring Soon</h6>
                                <div class="d-flex align-items-baseline gap-2 flex-wrap">
                                    <h4 class="mb-0 text-white">{{ $stats['expiring_soon'] }}</h4>
                                    <span class="badge bg-white bg-opacity-25 text-white">
                                        <i class="fas fa-clock me-1"></i>7 days
                                    </span>
                                </div>
                                <small class="text-white-50 mt-2 d-block">
                                    <i class="fas fa-hourglass-half me-1"></i>Need attention
                                </small>
                            </div>
                            <div class="icon-circle bg-white-10 flex-shrink-0 ms-3">
                                <i class="fas fa-clock text-white"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-xl-3 col-lg-6 col-md-6">
                <div class="card stat-card bg-info h-100">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-2 text-white-50">This Month</h6>
                                <div class="d-flex align-items-baseline gap-2 flex-wrap">
                                    <h4 class="mb-0 text-white">KES {{ number_format($stats['monthly_total'], 0) }}</h4>
                                    <span class="badge bg-white bg-opacity-25 text-white">
                                        <i class="fas fa-trending-up me-1"></i>Revenue
                                    </span>
                                </div>
                                <small class="text-white-50 mt-2 d-block">
                                    <i class="fas fa-calendar me-1"></i>Total revenue
                                </small>
                            </div>
                            <div class="icon-circle bg-white-10 flex-shrink-0 ms-3">
                                <i class="fas fa-money-bill-wave text-white"></i>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content Area -->
    <div class="main-content-area mt-4">
        <div class="row">
            <div class="col-lg-8">
                <div class="card payment-form">
                    <div class="card-header">
                        <div class="d-flex align-items-center">
                            <div class="icon-circle bg-primary bg-opacity-10 me-3">
                                <i class="fas fa-plus-circle text-primary"></i>
                            </div>
                            <div>
                                <h5 class="mb-0">Airtime Payment Details</h5>
                                <small class="text-muted">Fill in the details below to process airtime topup</small>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <form action="{{ route('payments.airtime.store') }}" method="POST" id="airtimeForm">
                            @csrf

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="station_id" class="form-label">
                                        <i class="fas fa-building me-1 text-primary"></i>Station *
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-building"></i></span>
                                        <select class="form-select @error('station_id') is-invalid @enderror"
                                                id="station_id" name="station_id" required>
                                            <option value="">Select Station</option>
                                            @foreach($stations as $station)
                                                <option value="{{ $station->station_id }}"
                                                        {{ old('station_id') == $station->station_id ? 'selected' : '' }}
                                                        data-mobile="{{ $station->contact_phone }}"
                                                        data-location="{{ $station->location }}"
                                                        data-contact-person="{{ $station->contact_person }}"
                                                        data-contact-email="{{ $station->contact_email }}">
                                                    {{ $station->name }} - {{ $station->location }}
                                                </option>
                                            @endforeach
                                        </select>
                                        <button type="button" class="btn btn-outline-secondary" 
                                                onclick="showStationDetails()" 
                                                data-tooltip="View Station Information">
                                            <i class="fas fa-info-circle"></i>
                                        </button>
                                    </div>
                                    @error('station_id')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label for="mobile_number" class="form-label">
                                        <i class="fas fa-mobile-alt me-1 text-primary"></i>Mobile Number *
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-mobile-alt"></i></span>
                                        <input type="text" class="form-control @error('mobile_number') is-invalid @enderror"
                                            id="mobile_number" name="mobile_number"
                                            value="{{ old('mobile_number') }}"
                                            placeholder="e.g., 0712345678" required
                                            list="mobileSuggestions">
                                        <button type="button" class="btn btn-outline-secondary" id="copyMobileBtn" 
                                                data-tooltip="Use Station Contact">
                                            <i class="fas fa-copy"></i>
                                        </button>
                                    </div>
                                    <datalist id="mobileSuggestions">
                                        @foreach($recentNumbers as $number)
                                            <option value="{{ $number }}">{{ $number }}</option>
                                        @endforeach
                                    </datalist>
                                    <small class="text-muted">
                                        <i class="fas fa-info-circle me-1"></i>
                                        Select a station first, then click the copy button to use its contact number.
                                    </small>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="amount" class="form-label">
                                        <i class="fas fa-money-bill-wave me-1 text-primary"></i>Amount (KES) *
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-money-bill-wave"></i></span>
                                        <input type="number" step="0.01" class="form-control @error('amount') is-invalid @enderror"
                                               id="amount" name="amount" value="{{ old('amount') }}" required>
                                        <span class="input-group-text">.00</span>
                                    </div>
                                    <div class="mt-2">
                                        <label for="quick_amount" class="form-label small text-muted">
                                            <i class="fas fa-bolt me-1"></i>Quick Select Amount
                                        </label>
                                        <select class="form-select form-select-sm" id="quick_amount">
                                            <option value="">Choose amount...</option>
                                            @php
                                                $quickAmounts = [100,200,250,500,1000,2000,3000,5000,10000];
                                            @endphp
                                            @foreach($quickAmounts as $quickAmount)
                                                <option value="{{ $quickAmount }}">KES {{ number_format($quickAmount) }}</option>
                                            @endforeach
                                        </select>
                                    </div>
                                    @error('amount')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-md-4 mb-3">
                                    <label for="topup_date" class="form-label">
                                        <i class="fas fa-calendar-alt me-1 text-primary"></i>Topup Date *
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-calendar-alt"></i></span>
                                        <input type="date" class="form-control @error('topup_date') is-invalid @enderror"
                                               id="topup_date" name="topup_date"
                                               value="{{ old('topup_date', date('Y-m-d')) }}" required>
                                        <button type="button" class="btn btn-outline-secondary" onclick="setDate('today')">
                                            Today
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary" onclick="setDate('yesterday')">
                                            Yesterday
                                        </button>
                                    </div>
                                    @error('topup_date')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-md-4 mb-3">
                                    <label for="network_provider" class="form-label">
                                        <i class="fas fa-signal me-1 text-primary"></i>Network Provider *
                                    </label>
                                    <select class="form-select @error('network_provider') is-invalid @enderror"
                                            id="network_provider" name="network_provider" required>
                                        <option value="">Select Provider</option>
                                        <option value="Safaricom" {{ old('network_provider') == 'Safaricom' ? 'selected' : '' }}>Safaricom</option>
                                        <option value="Airtel" {{ old('network_provider') == 'Airtel' ? 'selected' : '' }}>Airtel</option>
                                        <option value="Telkom" {{ old('network_provider') == 'Telkom' ? 'selected' : '' }}>Telkom</option>
                                        <option value="Faiba" {{ old('network_provider') == 'Faiba' ? 'selected' : '' }}>Faiba</option>
                                    </select>
                                    @error('network_provider')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="transaction_id" class="form-label">
                                        <i class="fas fa-receipt me-1 text-primary"></i>Transaction ID
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-receipt"></i></span>
                                        <input type="text" class="form-control @error('transaction_id') is-invalid @enderror"
                                               id="transaction_id" name="transaction_id"
                                               value="{{ old('transaction_id', 'TXN' . date('YmdHis')) }}"
                                               placeholder="e.g., TXN12345678">
                                        <button type="button" class="btn btn-outline-secondary" onclick="generateTransactionId()">
                                            <i class="fas fa-sync-alt"></i>
                                        </button>
                                    </div>
                                    <small class="text-muted">Leave blank to auto-generate</small>
                                    @error('transaction_id')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>

                                <div class="col-md-6 mb-3">
                                    <label class="form-label">
                                        <i class="fas fa-clock me-1 text-primary"></i>Expected Expiry
                                    </label>
                                    <div class="input-group">
                                        <span class="input-group-text"><i class="fas fa-clock"></i></span>
                                        <input type="date" class="form-control" id="expected_expiry"
                                               name="expected_expiry" readonly>
                                    </div>
                                    <div class="mt-2">
                                        <div class="btn-group btn-group-sm w-100" role="group">
                                            <button type="button" class="btn btn-outline-primary" onclick="setExpiryDays(30)">30 days</button>
                                            <button type="button" class="btn btn-outline-primary" onclick="setExpiryDays(60)">60 days</button>
                                            <button type="button" class="btn btn-outline-primary" onclick="setExpiryDays(90)">90 days</button>
                                        </div>
                                    </div>
                                    <small class="text-muted" id="expiryText">Auto-calculated: 30 days from topup date</small>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="payment_method" class="form-label">
                                        <i class="fas fa-credit-card me-1 text-primary"></i>Payment Method
                                    </label>
                                    <select class="form-select @error('payment_method') is-invalid @enderror"
                                            id="payment_method" name="payment_method">
                                        <option value="">Select Method</option>
                                        <option value="M-Pesa" {{ old('payment_method') == 'M-Pesa' ? 'selected' : '' }}>M-Pesa</option>
                                        <option value="Bank Transfer" {{ old('payment_method') == 'Bank Transfer' ? 'selected' : '' }}>Bank Transfer</option>
                                        <option value="Cash" {{ old('payment_method') == 'Cash' ? 'selected' : '' }}>Cash</option>
                                        <option value="Airtime Money" {{ old('payment_method') == 'Airtime Money' ? 'selected' : '' }}>Airtime Money</option>
                                    </select>
                                    @error('payment_method')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="row mb-4">
                                <div class="col-12">
                                    <label for="notes" class="form-label">
                                        <i class="fas fa-sticky-note me-1 text-primary"></i>Notes
                                    </label>
                                    <textarea class="form-control @error('notes') is-invalid @enderror"
                                              id="notes" name="notes" rows="3"
                                              placeholder="Enter any notes about this airtime topup...">{{ old('notes') }}</textarea>
                                    <div class="mt-2">
                                        <label for="quick_notes" class="form-label small text-muted">
                                            <i class="fas fa-tasks me-1"></i>Quick Notes Templates (select one at a time)
                                        </label>
                                        <select class="form-select form-select-sm" id="quick_notes">
                                            <option value="">Select a note template...</option>
                                            @php
                                                $quickNotes = [
                                                    'Monthly airtime allocation',
                                                    'Emergency topup',
                                                    'SMS bundle purchase',
                                                    'Additional data bundle',
                                                    'Special project allocation',
                                                    'Meeting/conference credit',
                                                    'Staff communication allowance',
                                                    'Customer support line topup'
                                                ];
                                            @endphp
                                            @foreach($quickNotes as $note)
                                                <option value="{{ $note }}">{{ $note }}</option>
                                            @endforeach
                                        </select>
                                        <small class="text-muted mt-1 d-block">
                                            <i class="fas fa-info-circle me-1"></i>
                                            Selecting a note will replace the current notes content
                                        </small>
                                    </div>
                                    @error('notes')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <!-- Advanced Options Card -->
                            <div class="card advanced-options-card mb-4">
                                <div class="card-header bg-light" id="advancedOptionsHeader" style="cursor: pointer;">
                                    <h6 class="mb-0 d-flex justify-content-between align-items-center">
                                        <span>
                                            <i class="fas fa-cogs me-2"></i>
                                            Advanced Options
                                        </span>
                                        <i class="fas fa-chevron-down toggle-icon" id="advancedToggleIcon"></i>
                                    </h6>
                                </div>
                                <div class="card-body advanced-options-body" id="advancedOptionsBody" style="display: none;">
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="checkbox"
                                                       name="auto_renew" id="auto_renew" value="1"
                                                       {{ old('auto_renew') ? 'checked' : '' }}>
                                                <label class="form-check-label" for="auto_renew">
                                                    <i class="fas fa-redo me-1"></i> Set up auto-renewal
                                                </label>
                                                <small class="text-muted d-block">
                                                    Automatically renew this airtime every month
                                                </small>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="form-check mb-3">
                                                <input class="form-check-input" type="checkbox"
                                                       name="send_notification" id="send_notification" value="1"
                                                       {{ old('send_notification', true) ? 'checked' : '' }}>
                                                <label class="form-check-label" for="send_notification">
                                                    <i class="fas fa-bell me-1"></i> Send notification
                                                </label>
                                                <small class="text-muted d-block">
                                                    Notify station contact about this topup
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Payment Summary -->
                            <div class="card mb-4">
                                <div class="card-header">
                                    <div class="d-flex align-items-center">
                                        <div class="icon-circle bg-success bg-opacity-10 me-3">
                                            <i class="fas fa-file-invoice text-success"></i>
                                        </div>
                                        <div>
                                            <h6 class="mb-0">Payment Summary</h6>
                                            <small class="text-muted">Review your transaction details</small>
                                        </div>
                                    </div>
                                </div>
                                <div class="card-body">
                                    <div class="summary-preview">
                                        <div class="row">
                                            <div class="col-md-4">
                                                <p class="mb-2"><strong>Station:</strong> <span id="summaryStation">-</span></p>
                                                <p class="mb-2"><strong>Mobile:</strong> <span id="summaryMobile">-</span></p>
                                                <p class="mb-2"><strong>Network:</strong> <span id="summaryNetwork">-</span></p>
                                            </div>
                                            <div class="col-md-4">
                                                <p class="mb-2"><strong>Amount:</strong> <span id="summaryAmount" class="text-success fw-bold">KES 0.00</span></p>
                                                <p class="mb-2"><strong>Topup Date:</strong> <span id="summaryDate">-</span></p>
                                                <p class="mb-2"><strong>Expiry:</strong> <span id="summaryExpiry">-</span></p>
                                            </div>
                                            <div class="col-md-4">
                                                <p class="mb-2"><strong>Transaction ID:</strong> <span id="summaryTxn">-</span></p>
                                                <p class="mb-2"><strong>Payment Method:</strong> <span id="summaryMethod">-</span></p>
                                                <p class="mb-0"><strong>Status:</strong> <span class="badge bg-success">Active</span></p>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Form Actions -->
                            <div class="form-actions">
                                <div>
                                    <button type="button" class="btn btn-outline-secondary" onclick="clearForm()">
                                        <i class="fas fa-broom me-1"></i> Clear Form
                                    </button>
                                    <button type="button" class="btn btn-outline-info" onclick="saveAsDraft()">
                                        <i class="fas fa-save me-1"></i> Save as Draft
                                    </button>
                                    <button type="button" class="btn btn-outline-warning" onclick="loadDraft()">
                                        <i class="fas fa-folder-open me-1"></i> Load Draft
                                    </button>
                                </div>
                                <div>
                                    <a href="{{ route('payments.airtime.index') }}" class="btn btn-secondary">
                                        <i class="fas fa-times me-1"></i> Cancel
                                    </a>
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save me-1"></i> Process Payment
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>

            <div class="col-lg-4">
                <div class="card mb-4">
                    <div class="card-header">
                        <div class="d-flex align-items-center">
                            <div class="icon-circle bg-info bg-opacity-10 me-3">
                                <i class="fas fa-history text-info"></i>
                            </div>
                            <div>
                                <h6 class="mb-0">Recent Airtime Topups</h6>
                                <small class="text-muted">Last 5 transactions</small>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="recent-payments-list">
                            @if($recentPayments->count() > 0)
                                <div class="list-group list-group-flush">
                                    @foreach($recentPayments as $recent)
                                    <div class="list-group-item">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1">{{ $recent->station->name }}</h6>
                                            <small class="text-muted">{{ \Carbon\Carbon::parse($recent->topup_date)->diffForHumans() }}</small>
                                        </div>
                                        <p class="mb-1">
                                            <strong>{{ $recent->mobile_number }}</strong> -
                                            KES {{ number_format($recent->amount, 2) }}
                                        </p>
                                        <small class="text-muted">
                                            <i class="fas fa-{{ $recent->network_provider == 'Safaricom' ? 'wifi' : 'signal' }} me-1"></i>
                                            {{ $recent->network_provider }} •
                                            Expires: {{ \Carbon\Carbon::parse($recent->expected_expiry)->format('M d, Y') }}
                                        </small>
                                    </div>
                                    @endforeach
                                </div>
                                <div class="text-center p-3">
                                    <a href="{{ route('payments.airtime.index') }}" class="btn btn-sm btn-outline-primary">
                                        View All <i class="fas fa-arrow-right ms-1"></i>
                                    </a>
                                </div>
                            @else
                                <div class="text-center py-5">
                                    <i class="fas fa-phone-alt fa-3x text-muted mb-3"></i>
                                    <p class="text-muted">No recent airtime payments</p>
                                </div>
                            @endif
                        </div>
                    </div>
                </div>

                <div class="card">
                    <div class="card-header">
                        <div class="d-flex align-items-center">
                            <div class="icon-circle bg-primary bg-opacity-10 me-3">
                                <i class="fas fa-address-book text-primary"></i>
                            </div>
                            <div>
                                <h6 class="mb-0">Station Contacts</h6>
                                <small class="text-muted">Quick reference</small>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="station-contacts-list">
                            <div class="list-group list-group-flush">
                                @foreach($stations->take(5) as $station)
                                <div class="list-group-item">
                                    <h6 class="mb-1">{{ $station->name }}</h6>
                                    <p class="mb-1 text-muted small">{{ $station->location }}</p>
                                    <small class="text-muted">
                                        <i class="fas fa-user me-1"></i> {{ $station->contact_person }}<br>
                                        <i class="fas fa-phone me-1"></i> {{ $station->contact_phone }}<br>
                                        <i class="fas fa-envelope me-1"></i> {{ $station->contact_email }}
                                    </small>
                                </div>
                                @endforeach
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Station Details Modal -->
<div class="modal fade" id="stationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Station Information</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="stationModalBody"></div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
    // Set amount from quick select dropdown - REPLACES the current amount
    document.getElementById('quick_amount')?.addEventListener('change', function(e) {
        const value = e.target.value;
        if (value) {
            setAmount(value);
        }
        // Reset dropdown after selection
        e.target.value = '';
    });
    
    // Set notes from quick notes dropdown - REPLACES the current notes (one at a time)
    document.getElementById('quick_notes')?.addEventListener('change', function(e) {
        const value = e.target.value;
        if (value) {
            setNote(value);
        }
        // Reset dropdown after selection
        e.target.value = '';
    });
    
    window.setAmount = function(amount) {
        document.getElementById('amount').value = amount;
        updateSummary();
        // Visual feedback
        const amountField = document.getElementById('amount');
        amountField.style.backgroundColor = '#d4edda';
        setTimeout(() => {
            amountField.style.backgroundColor = '';
        }, 500);
    };

    // New function to set note (replaces instead of appends)
    window.setNote = function(note) {
        const notesTextarea = document.getElementById('notes');
        notesTextarea.value = note;
        updateSummary();
        
        // Visual feedback
        notesTextarea.style.backgroundColor = '#d4edda';
        setTimeout(() => {
            notesTextarea.style.backgroundColor = '';
        }, 500);
        
        // Optional: Show success message
        const feedback = document.createElement('div');
        feedback.className = 'text-success small mt-1';
        feedback.innerHTML = '<i class="fas fa-check-circle me-1"></i>Note added successfully';
        notesTextarea.parentNode.appendChild(feedback);
        setTimeout(() => {
            feedback.remove();
        }, 2000);
    };

    window.setDate = function(type) {
        const dateInput = document.getElementById('topup_date');
        const today = new Date();
        
        if (type === 'today') {
            dateInput.value = today.toISOString().split('T')[0];
        } else if (type === 'yesterday') {
            const yesterday = new Date(today);
            yesterday.setDate(today.getDate() - 1);
            dateInput.value = yesterday.toISOString().split('T')[0];
        }
        
        setExpiryDays(30);
        updateSummary();
    };

    window.setExpiryDays = function(days) {
        const topupDate = document.getElementById('topup_date').value;
        if (topupDate) {
            const expiryDate = new Date(topupDate);
            expiryDate.setDate(expiryDate.getDate() + parseInt(days));
            const formattedDate = expiryDate.toISOString().split('T')[0];
            document.getElementById('expected_expiry').value = formattedDate;
            
            const expiryText = document.getElementById('expiryText');
            if (expiryText) {
                expiryText.innerHTML = `Auto-calculated: ${days} days from topup date (expires on ${formattedDate})`;
            }
        }
        updateSummary();
    };

    window.generateTransactionId = function() {
        const timestamp = new Date().getTime();
        const random = Math.floor(Math.random() * 10000);
        const txnId = 'TXN' + timestamp + random;
        document.getElementById('transaction_id').value = txnId;
        updateSummary();
        
        // Visual feedback
        const txnField = document.getElementById('transaction_id');
        txnField.style.backgroundColor = '#d4edda';
        setTimeout(() => {
            txnField.style.backgroundColor = '';
        }, 500);
    };

    window.showStationDetails = function() {
        const stationSelect = document.getElementById('station_id');
        const selectedOption = stationSelect.options[stationSelect.selectedIndex];
        
        if (!selectedOption || !selectedOption.value) {
            alert('Please select a station first');
            return;
        }
        
        const stationName = selectedOption.text.split(' - ')[0];
        const location = selectedOption.getAttribute('data-location') || 'N/A';
        const mobile = selectedOption.getAttribute('data-mobile') || 'N/A';
        const contactPerson = selectedOption.getAttribute('data-contact-person') || 'N/A';
        const contactEmail = selectedOption.getAttribute('data-contact-email') || 'N/A';
        
        const modalBody = document.getElementById('stationModalBody');
        modalBody.innerHTML = `
            <div class="station-info">
                <p><strong>Station Name:</strong> ${stationName}</p>
                <p><strong>Location:</strong> ${location}</p>
                <p><strong>Contact Person:</strong> ${contactPerson}</p>
                <p><strong>Mobile Number:</strong> ${mobile}</p>
                <p><strong>Email:</strong> ${contactEmail}</p>
            </div>
        `;
        
        new bootstrap.Modal(document.getElementById('stationModal')).show();
    };

    window.updateSummary = function() {
        const stationSelect = document.getElementById('station_id');
        const selectedOption = stationSelect.options[stationSelect.selectedIndex];
        const stationName = selectedOption && selectedOption.value ? selectedOption.text.split(' - ')[0] : '-';
        
        const mobile = document.getElementById('mobile_number').value || '-';
        const network = document.getElementById('network_provider').value || '-';
        const amount = document.getElementById('amount').value || '0';
        const topupDate = document.getElementById('topup_date').value || '-';
        const expiryDate = document.getElementById('expected_expiry').value || '-';
        const transactionId = document.getElementById('transaction_id').value || '-';
        const paymentMethod = document.getElementById('payment_method').value || '-';
        const notes = document.getElementById('notes').value || '-';
        
        document.getElementById('summaryStation').innerText = stationName;
        document.getElementById('summaryMobile').innerText = mobile;
        document.getElementById('summaryNetwork').innerText = network;
        document.getElementById('summaryAmount').innerHTML = `KES ${parseFloat(amount).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})}`;
        document.getElementById('summaryDate').innerText = topupDate;
        document.getElementById('summaryExpiry').innerText = expiryDate;
        document.getElementById('summaryTxn').innerText = transactionId;
        document.getElementById('summaryMethod').innerText = paymentMethod;
    };

    window.clearForm = function() {
        if (confirm('Are you sure you want to clear all form fields?')) {
            document.getElementById('airtimeForm').reset();
            document.getElementById('expected_expiry').value = '';
            updateSummary();
        }
    };

    window.saveAsDraft = function() {
        const formData = {
            station_id: document.getElementById('station_id').value,
            mobile_number: document.getElementById('mobile_number').value,
            amount: document.getElementById('amount').value,
            topup_date: document.getElementById('topup_date').value,
            network_provider: document.getElementById('network_provider').value,
            transaction_id: document.getElementById('transaction_id').value,
            payment_method: document.getElementById('payment_method').value,
            notes: document.getElementById('notes').value,
            auto_renew: document.getElementById('auto_renew').checked,
            send_notification: document.getElementById('send_notification').checked,
            saved_at: new Date().toISOString()
        };
        
        localStorage.setItem('airtime_draft', JSON.stringify(formData));
        alert('Draft saved successfully!');
    };

    window.loadDraft = function() {
        const draft = localStorage.getItem('airtime_draft');
        if (draft) {
            const formData = JSON.parse(draft);
            if (confirm('Load saved draft from ' + new Date(formData.saved_at).toLocaleString() + '?')) {
                document.getElementById('station_id').value = formData.station_id || '';
                document.getElementById('mobile_number').value = formData.mobile_number || '';
                document.getElementById('amount').value = formData.amount || '';
                document.getElementById('topup_date').value = formData.topup_date || '';
                document.getElementById('network_provider').value = formData.network_provider || '';
                document.getElementById('transaction_id').value = formData.transaction_id || '';
                document.getElementById('payment_method').value = formData.payment_method || '';
                document.getElementById('notes').value = formData.notes || '';
                document.getElementById('auto_renew').checked = formData.auto_renew || false;
                document.getElementById('send_notification').checked = formData.send_notification !== false;
                
                if (formData.topup_date) {
                    setExpiryDays(30);
                }
                updateSummary();
            }
        } else {
            alert('No saved draft found');
        }
    };

    window.copyMobileFromStation = function() {
        const stationSelect = document.getElementById('station_id');
        const selectedOption = stationSelect.options[stationSelect.selectedIndex];
        
        if (selectedOption && selectedOption.value) {
            const mobileNumber = selectedOption.getAttribute('data-mobile');
            if (mobileNumber && mobileNumber !== 'N/A') {
                document.getElementById('mobile_number').value = mobileNumber;
                updateSummary();
            } else {
                alert('No mobile number found for selected station');
            }
        } else {
            alert('Please select a station first');
        }
    };

    window.toggleAdvancedOptions = function() {
        const body = document.getElementById('advancedOptionsBody');
        const icon = document.getElementById('advancedToggleIcon');
        
        if (body.style.display === 'none' || body.style.display === '') {
            body.style.display = 'block';
            icon.classList.add('rotated');
            localStorage.setItem('advancedOptionsOpen', 'true');
        } else {
            body.style.display = 'none';
            icon.classList.remove('rotated');
            localStorage.setItem('advancedOptionsOpen', 'false');
        }
    };

    $(document).ready(function() {
        const today = document.getElementById('topup_date').value;
        if (today) {
            setExpiryDays(30);
        }
        
        $('#station_id, #mobile_number, #amount, #topup_date, #network_provider, #transaction_id, #payment_method, #notes').on('change input keyup', function() {
            updateSummary();
        });
        
        $('#copyMobileBtn').on('click', copyMobileFromStation);
        
        $('#station_id').on('change', function() {
            const mobileInput = $('#mobile_number');
            if (!mobileInput.val()) {
                copyMobileFromStation();
            }
            updateSummary();
        });
        
        $('#advancedOptionsHeader').on('click', toggleAdvancedOptions);
        
        const savedState = localStorage.getItem('advancedOptionsOpen');
        if (savedState === 'true') {
            document.getElementById('advancedOptionsBody').style.display = 'block';
            document.getElementById('advancedToggleIcon').classList.add('rotated');
        }
        
        const draft = localStorage.getItem('airtime_draft');
        if (draft && confirm('You have a saved draft. Would you like to load it?')) {
            loadDraft();
        }
        
        @if(session('old_data'))
            const oldData = @json(session('old_data'));
            if (oldData.station_id) {
                $('#station_id').val(oldData.station_id).trigger('change');
            }
            if (oldData.mobile_number) {
                $('#mobile_number').val(oldData.mobile_number);
            }
            if (oldData.network_provider) {
                $('#network_provider').val(oldData.network_provider);
            }
            if (oldData.notes) {
                $('#notes').val(oldData.notes);
            }
            if (oldData.amount) {
                $('#amount').val(oldData.amount);
            }
            if (oldData.payment_method) {
                $('#payment_method').val(oldData.payment_method);
            }
            updateSummary();
        @endif
        
        updateSummary();
    });
</script>
@endpush