@extends('admin-layouts.master')
<style>
/* Step Indicator */
.step-indicator {
    display: flex;
    justify-content: space-between;
    margin-bottom: 2rem;
    padding: 0 2rem;
}

.step {
    flex: 1;
    text-align: center;
    position: relative;
}

.step::before {
    content: '';
    position: absolute;
    top: 15px;
    left: 50%;
    right: -50%;
    height: 2px;
    background: #dee2e6;
    z-index: 1;
}

.step:last-child::before {
    display: none;
}

.step-number {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background: #dee2e6;
    color: #6c757d;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    position: relative;
    z-index: 2;
    transition: all 0.3s ease;
}

.step.active .step-number {
    background: #4e73df;
    color: white;
    transform: scale(1.1);
}

.step.completed .step-number {
    background: #1cc88a;
    color: white;
}

.step.completed::before {
    background: #1cc88a;
}

.step-title {
    margin-top: 0.5rem;
    font-size: 0.8rem;
    color: #6c757d;
    transition: all 0.3s ease;
}

.step.active .step-title {
    color: #4e73df;
    font-weight: bold;
}

/* Form Steps */
.form-step {
    transition: all 0.3s ease;
}

.step-header {
    border-bottom: 2px solid #f8f9fc;
    padding-bottom: 1rem;
}

.step-header h5 {
    margin-bottom: 0.5rem;
}

.step-header p {
    margin-bottom: 0;
    font-size: 0.9rem;
}

/* Enhanced form styling */
.form-control:focus {
    border-color: #4e73df;
    box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
}

.form-group label {
    font-weight: 600;
    color: #5a5c69;
}

/* Card animations */
.card {
    transition: all 0.3s ease;
}

.card:hover {
    transform: translateY(-2px);
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15) !important;
}

/* Button enhancements */
.btn-group-toggle .btn {
    transition: all 0.2s ease;
}

.btn-group-toggle .btn:hover {
    transform: translateY(-1px);
}

/* Navigation buttons */
.form-navigation .btn {
    min-width: 120px;
}

/* Loading states */
.loading {
    position: relative;
    pointer-events: none;
}

.loading::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.8);
    border-radius: 0.35rem;
    z-index: 10;
}

.loading::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 20px;
    height: 20px;
    margin: -10px 0 0 -10px;
    border: 2px solid #f3f3f3;
    border-top: 2px solid #4e73df;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    z-index: 11;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* Form validation */
.is-invalid {
    border-color: #e74a3b;
    animation: shake 0.5s ease-in-out;
}

@keyframes shake {
    0%, 100% { transform: translateX(0); }
    25% { transform: translateX(-5px); }
    75% { transform: translateX(5px); }
}

.invalid-feedback {
    display: block;
    font-size: 0.875rem;
    color: #e74a3b;
    margin-top: 0.25rem;
}

/* Preview card enhancements */
#previewCard {
    border-left: 4px solid #1cc88a;
}

#guestInfoCard {
    border-left: 4px solid #36b9cc;
}

#bookingDetailsCard {
    border-left: 4px solid #f6c23e;
}

/* Payment method styling */
.payment-method-card {
    border: 2px solid #e3e6f0;
    border-radius: 0.5rem;
    padding: 1rem;
    margin-bottom: 0.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
}

.payment-method-card:hover {
    border-color: #4e73df;
    background-color: #f8f9fc;
}

.payment-method-card.selected {
    border-color: #1cc88a;
    background-color: #d1ecf1;
}

.payment-method-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 1rem;
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .step-indicator {
        padding: 0 1rem;
    }

    .step-title {
        font-size: 0.7rem;
    }

    .step-number {
        width: 25px;
        height: 25px;
        font-size: 0.8rem;
    }

    .payment-method-card {
        padding: 0.75rem;
    }
}

/* Print styles */
@media print {
    .btn, .card-header, .alert {
        display: none !important;
    }
}
</style>
@section('content')
<div class="container-fluid">

    <!-- Page Heading -->
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Buat Invoice</h1>
        <div>
            <a href="{{ route('invoices.index') }}" class="btn btn-sm btn-secondary shadow-sm mr-2">
                <i class="fas fa-arrow-left fa-sm text-white-50"></i> Kembali
            </a>
            <button type="button" class="btn btn-sm btn-warning shadow-sm mr-2" onclick="clearForm()">
                <i class="fas fa-redo fa-sm text-white-50"></i> Reset Form
            </button>
            <button type="button" class="btn btn-sm btn-info shadow-sm" onclick="previewInvoiceData()">
                <i class="fas fa-eye fa-sm text-white-50"></i> Preview
            </button>
        </div>
    </div>

    <!-- Progress Steps -->
    <div class="step-indicator mb-4">
        <div class="step active" id="step-1">
            <div class="step-number">1</div>
            <div class="step-title">Pilih Booking</div>
        </div>
        <div class="step" id="step-2">
            <div class="step-number">2</div>
            <div class="step-title">Atur Tanggal</div>
        </div>
        <div class="step" id="step-3">
            <div class="step-number">3</div>
            <div class="step-title">Diskon, Pajak & Pembayaran</div>
        </div>
        <div class="step" id="step-4">
            <div class="step-number">4</div>
            <div class="step-title">Review & Submit</div>
        </div>
    </div>

    <!-- Alert for Keyboard Shortcuts -->
    <div class="alert alert-info alert-dismissible fade show" role="alert">
        <strong><i class="fas fa-keyboard"></i> Keyboard Shortcuts:</strong>
        Ctrl+S (Save Draft) | Ctrl+Enter (Submit) | Shift+Esc (Clear Form) | F9 (Preview)
        <button type="button" class="close" data-dismiss="alert">
            <span>&times;</span>
        </button>
    </div>

    <!-- Form Card -->
    <div class="row">
        <div class="col-lg-8">
            <div class="card shadow mb-4">
                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                    <h6 class="m-0 font-weight-bold text-primary">Form Invoice</h6>
                    <div class="dropdown no-arrow">
                        <button class="btn btn-sm btn-light dropdown-toggle" type="button" id="formActions" data-toggle="dropdown">
                            <i class="fas fa-ellipsis-v"></i>
                        </button>
                        <div class="dropdown-menu dropdown-menu-right shadow">
                            <a class="dropdown-item" href="#" onclick="saveDraft()">
                                <i class="fas fa-save text-success"></i> Save Draft
                            </a>
                            <a class="dropdown-item" href="#" onclick="loadDraft()">
                                <i class="fas fa-folder-open text-info"></i> Load Draft
                            </a>
                            <div class="dropdown-divider"></div>
                            <a class="dropdown-item" href="#" onclick="clearForm()">
                                <i class="fas fa-trash text-danger"></i> Clear Form
                            </a>
                        </div>
                    </div>
                </div>
                <div class="card-body">
                    <form id="invoiceForm" action="{{ route('invoices.store') }}" method="POST" novalidate>
                        @csrf

                        <!-- Step 1: Booking Selection -->
                        <div class="form-step" id="form-step-1">
                            <div class="step-header mb-3">
                                <h5 class="text-primary">
                                    <i class="fas fa-bed"></i> Pilih Booking
                                </h5>
                                <p class="text-muted">Pilih booking yang akan dibuatkan invoice</p>
                            </div>

                            <div class="form-group">
                                <label for="booking_id">Booking <span class="text-danger">*</span></label>
                                <select class="form-control select2" id="booking_id" name="booking_id" required>
                                    <option value="">-- Pilih Booking --</option>
                                    @foreach($availableBookings as $availableBooking)
                                    <option value="{{ $availableBooking->id }}"
                                            data-guest="{{ $availableBooking->guest->name }}"
                                            data-phone="{{ $availableBooking->guest->phone }}"
                                            data-email="{{ $availableBooking->guest->email }}"
                                            data-checkin="{{ $availableBooking->check_in_date_formatted }}"
                                            data-checkout="{{ $availableBooking->check_out_date_formatted }}"
                                            data-rooms="{{ $availableBooking->bookingDetails->count() }}"
                                            data-services="{{ $availableBooking->bookingServices->count() }}"
                                            data-room-total="{{ $availableBooking->total_amount }}"
                                            data-services-total="{{ $availableBooking->bookingServices->sum('total_amount') }}"
                                            {{ (request('booking_id') == $availableBooking->id || (isset($booking) && $booking->id == $availableBooking->id)) ? 'selected' : '' }}>
                                        #{{ $availableBooking->id }} - {{ $availableBooking->guest->name }}
                                        ({{ $availableBooking->check_in_date_formatted }})
                                    </option>
                                    @endforeach
                                </select>
                                @error('booking_id')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                                <small class="form-text text-muted">
                                    <i class="fas fa-info-circle"></i>
                                    Hanya booking dengan status "checked-in" yang bisa dibuatkan invoice
                                </small>
                            </div>
                        </div>

                        <!-- Step 2: Date Configuration -->
                        <div class="form-step" id="form-step-2" style="display: none;">
                            <div class="step-header mb-3">
                                <h5 class="text-primary">
                                    <i class="fas fa-calendar-alt"></i> Konfigurasi Tanggal
                                </h5>
                                <p class="text-muted">Atur tanggal invoice dan jatuh tempo pembayaran</p>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="invoice_date">Tanggal Invoice <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="invoice_date" name="invoice_date"
                                               value="{{ old('invoice_date', date('Y-m-d')) }}" required>
                                        @error('invoice_date')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="due_date">Tanggal Jatuh Tempo <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" id="due_date" name="due_date"
                                               value="{{ old('due_date', date('Y-m-d', strtotime('+3 days'))) }}" required>
                                        @error('due_date')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                        @enderror
                                        <small class="form-text text-muted">Default: 3 hari setelah tanggal invoice</small>
                                    </div>
                                </div>
                            </div>

                            <!-- Quick Date Presets -->
                            <div class="form-group">
                                <label>Quick Presets Jatuh Tempo:</label>
                                <div class="btn-group-toggle d-flex flex-wrap" data-toggle="buttons">
                                    <label class="btn btn-outline-success btn-sm mr-2 mb-2" onclick="applyPreset('same_day')">
                                        <input type="radio" name="preset" autocomplete="off"> Same Day
                                    </label>
                                    <label class="btn btn-outline-info btn-sm mr-2 mb-2" onclick="applyPreset('next_day')">
                                        <input type="radio" name="preset" autocomplete="off"> Next Day
                                    </label>
                                    <label class="btn btn-outline-warning btn-sm mr-2 mb-2" onclick="applyPreset('3_days')">
                                        <input type="radio" name="preset" autocomplete="off"> 3 Days
                                    </label>
                                    <label class="btn btn-outline-primary btn-sm mr-2 mb-2" onclick="applyPreset('7_days')">
                                        <input type="radio" name="preset" autocomplete="off"> 7 Days
                                    </label>
                                    <label class="btn btn-outline-secondary btn-sm mr-2 mb-2" onclick="applyPreset('30_days')">
                                        <input type="radio" name="preset" autocomplete="off"> 30 Days
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- Step 3: Discount, Tax & Payment Method -->
                        <div class="form-step" id="form-step-3" style="display: none;">
                            <div class="step-header mb-3">
                                <h5 class="text-primary">
                                    <i class="fas fa-calculator"></i> Diskon, Pajak & Metode Pembayaran
                                </h5>
                                <p class="text-muted">Atur diskon, pajak, dan pilih metode pembayaran untuk invoice</p>
                            </div>

                            <!-- Discount and Tax Row -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="discount_amount">Diskon (Rp)</label>
                                        <div class="input-group">
                                            <div class="input-group-prepend">
                                                <span class="input-group-text">Rp</span>
                                            </div>
                                            <input type="number" class="form-control" id="discount_amount" name="discount_amount"
                                                   value="{{ old('discount_amount', 0) }}" min="0" step="1000">
                                            <div class="input-group-append">
                                                <button class="btn btn-outline-secondary" type="button" onclick="calculatePercentageDiscount()">
                                                    <i class="fas fa-percent"></i>
                                                </button>
                                            </div>
                                        </div>
                                        @error('discount_amount')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                        @enderror
                                        <small class="form-text text-muted">Masukkan nominal diskon dalam Rupiah</small>
                                    </div>

                                    <!-- Quick Discount Presets -->
                                    <div class="form-group">
                                        <label>Quick Discount:</label>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-outline-success" onclick="applyDiscount(5)">5%</button>
                                            <button type="button" class="btn btn-outline-info" onclick="applyDiscount(10)">10%</button>
                                            <button type="button" class="btn btn-outline-warning" onclick="applyDiscount(15)">15%</button>
                                            <button type="button" class="btn btn-outline-danger" onclick="applyDiscount(20)">20%</button>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label for="tax_rate">Pajak (%)</label>
                                        <div class="input-group">
                                            <input type="number" class="form-control" id="tax_rate" name="tax_rate"
                                                   value="{{ old('tax_rate', 11) }}" min="0" max="100" step="0.01">
                                            <div class="input-group-append">
                                                <span class="input-group-text">%</span>
                                            </div>
                                        </div>
                                        @error('tax_rate')
                                        <div class="invalid-feedback d-block">{{ $message }}</div>
                                        @enderror
                                        <small class="form-text text-muted">Default PPN Indonesia 11%</small>
                                    </div>

                                    <!-- Tax Presets -->
                                    <div class="form-group">
                                        <label>Tax Presets:</label>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-outline-primary" onclick="setTaxRate(0)">0% (Tax Free)</button>
                                            <button type="button" class="btn btn-outline-success" onclick="setTaxRate(11)">11% (PPN)</button>
                                            <button type="button" class="btn btn-outline-warning" onclick="setTaxRate(10)">10% (VAT)</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Payment Method Selection -->
                            <div class="form-group">
                                <label>Metode Pembayaran <span class="text-danger">*</span></label>
                                <div class="row" id="payment-methods-container">
                                    @if(isset($metodePembayaran) && $metodePembayaran->count() > 0)
                                        @foreach($metodePembayaran as $metode)
                                        <div class="col-md-6 col-lg-4 mb-3">
                                            <div class="payment-method-card" data-method-id="{{ $metode->id }}" onclick="selectPaymentMethod({{ $metode->id }})">
                                                <div class="d-flex align-items-center">
                                                    <div class="payment-method-icon bg-light text-primary">
                                                        <i class="fas {{ $metode->icon ?? 'fa-credit-card' }}"></i>
                                                    </div>
                                                    <div class="flex-grow-1">
                                                        <div class="font-weight-bold">{{ $metode->nama }}</div>
                                                        <small class="text-muted">{{ $metode->deskripsi ?? 'Metode pembayaran' }}</small>
                                                        @if($metode->biaya_admin > 0)
                                                            <div class="text-warning">
                                                                <small><i class="fas fa-exclamation-triangle"></i> Admin: Rp {{ number_format($metode->biaya_admin, 0, ',', '.') }}</small>
                                                            </div>
                                                        @endif
                                                    </div>
                                                    <div class="payment-method-check">
                                                        <i class="fas fa-check-circle text-success" style="display: none;"></i>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        @endforeach
                                    @else
                                        <div class="col-12">
                                            <div class="alert alert-warning">
                                                <i class="fas fa-exclamation-triangle"></i>
                                                Tidak ada metode pembayaran yang tersedia. Silakan hubungi administrator.
                                            </div>
                                        </div>
                                    @endif
                                </div>

                                <!-- Hidden input untuk menyimpan metode pembayaran yang dipilih -->
                                <input type="hidden" name="metode_pembayaran_id" id="metode_pembayaran_id" value="{{ old('metode_pembayaran_id') }}">
                                @error('metode_pembayaran_id')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror

                                <small class="form-text text-muted">
                                    <i class="fas fa-info-circle"></i>
                                    Pilih metode pembayaran yang akan digunakan untuk invoice ini
                                </small>
                            </div>

                            <!-- Calculation Display -->
                            <div class="form-group">
                                <div class="card border-left-info">
                                    <div class="card-body">
                                        <h6 class="text-info">Kalkulasi Sementara:</h6>
                                        <div class="row" id="calculation-display">
                                            <div class="col-12 text-muted">
                                                <small>Pilih booking untuk melihat kalkulasi</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Step 4: Review & Notes -->
                        <div class="form-step" id="form-step-4" style="display: none;">
                            <div class="step-header mb-3">
                                <h5 class="text-primary">
                                    <i class="fas fa-clipboard-check"></i> Review & Submit
                                </h5>
                                <p class="text-muted">Review informasi invoice dan tambahkan catatan</p>
                            </div>

                            <!-- Notes -->
                            <div class="form-group">
                                <label for="notes">Catatan Invoice</label>
                                <textarea class="form-control" id="notes" name="notes" rows="4"
                                          placeholder="Catatan tambahan untuk invoice (opsional)...">{{ old('notes') }}</textarea>
                                @error('notes')
                                <div class="invalid-feedback d-block">{{ $message }}</div>
                                @enderror
                                <small class="form-text text-muted">Catatan akan ditampilkan di invoice PDF</small>
                            </div>

                            <!-- Invoice Summary -->
                            <div class="card border-left-success">
                                <div class="card-body">
                                    <h6 class="text-success mb-3">
                                        <i class="fas fa-file-invoice-dollar"></i> Ringkasan Invoice
                                    </h6>
                                    <div id="final-review">
                                        <p class="text-muted">Data akan muncul setelah semua form diisi</p>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Navigation Buttons -->
                        <div class="form-navigation mt-4">
                            <div class="row">
                                <div class="col-6">
                                    <button type="button" class="btn btn-secondary" id="prevBtn" onclick="changeStep(-1)" style="display: none;">
                                        <i class="fas fa-arrow-left"></i> Previous
                                    </button>
                                </div>
                                <div class="col-6 text-right">
                                    <button type="button" class="btn btn-primary" id="nextBtn" onclick="changeStep(1)">
                                        Next <i class="fas fa-arrow-right"></i>
                                    </button>
                                    <button type="submit" class="btn btn-success" id="submitBtn" style="display: none;">
                                        <i class="fas fa-save"></i> Buat Invoice
                                    </button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Sidebar -->
        <div class="col-lg-4">
            <!-- Guest Info Card -->
            <div class="card shadow mb-4" id="guestInfoCard" style="display: none;">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-info">
                        <i class="fas fa-user"></i> Info Tamu
                    </h6>
                </div>
                <div class="card-body">
                    <div id="guestInfo">
                        <!-- Guest info will be displayed here -->
                    </div>
                </div>
            </div>

            <!-- Booking Details Card -->
            <div class="card shadow mb-4" id="bookingDetailsCard" style="display: none;">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-warning">
                        <i class="fas fa-bed"></i> Detail Booking
                    </h6>
                </div>
                <div class="card-body">
                    <div id="bookingDetails">
                        <!-- Booking details will be displayed here -->
                    </div>
                </div>
            </div>

            <!-- Live Preview Card -->
            <div class="card shadow mb-4" id="previewCard" style="display: none;">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-success">
                        <i class="fas fa-calculator"></i> Live Preview
                    </h6>
                </div>
                <div class="card-body">
                    <div id="invoicePreview">
                        <!-- Invoice preview will be displayed here -->
                    </div>
                    <hr>
                    <div class="d-flex justify-content-between">
                        <strong>Grand Total:</strong>
                        <strong class="text-success" id="grandTotalAmount">Rp 0</strong>
                    </div>
                </div>
            </div>

            <!-- Pre-selected Booking Info -->
            @if(isset($booking))
            <div class="card shadow mb-4 border-left-primary">
                <div class="card-header py-3">
                    <h6 class="m-0 font-weight-bold text-primary">
                        <i class="fas fa-info-circle"></i> Booking Terpilih
                    </h6>
                </div>
                <div class="card-body">
                    <table class="table table-borderless table-sm">
                        <tr>
                            <td width="40%"><strong>ID:</strong></td>
                            <td>#{{ $booking->id }}</td>
                        </tr>
                        <tr>
                            <td><strong>Tamu:</strong></td>
                            <td>{{ $booking->guest->name }}</td>
                        </tr>
                        <tr>
                            <td><strong>Check-in:</strong></td>
                            <td>{{ $booking->check_in_date_formatted }}</td>
                        </tr>
                        <tr>
                            <td><strong>Check-out:</strong></td>
                            <td>{{ $booking->check_out_date_formatted }}</td>
                        </tr>
                        <tr>
                            <td><strong>Status:</strong></td>
                            <td><span class="badge badge-success">{{ ucfirst($booking->status) }}</span></td>
                        </tr>
                        <tr>
                            <td><strong>Total Kamar:</strong></td>
                            <td class="text-success"><strong>{{ $booking->formatted_total_amount }}</strong></td>
                        </tr>
                        @if($booking->bookingServices->count() > 0)
                        <tr>
                            <td><strong>Layanan:</strong></td>
                            <td>{{ $booking->bookingServices->count() }} item(s)</td>
                        </tr>
                        @endif
                    </table>
                </div>
            </div>
            @endif

            <!-- Invoice Tips Card -->
            <div class="card shadow border-left-info mb-4">
                <div class="card-body">
                    <h6 class="text-info mb-2">
                        <i class="fas fa-lightbulb"></i> Tips Invoice
                    </h6>
                    <ul class="text-muted small mb-0">
                        <li>Invoice otomatis menghitung total kamar + layanan</li>
                        <li>Diskon akan mengurangi subtotal sebelum pajak</li>
                        <li>PPN 11% adalah standar Indonesia</li>
                        <li>Jatuh tempo default 3 hari dari tanggal invoice</li>
                        <li>Pilih metode pembayaran yang sesuai</li>
                        <li>Biaya admin akan otomatis ditambahkan jika ada</li>
                        <li>Status akan otomatis berubah jadi "overdue" jika lewat jatuh tempo</li>
                        <li>Draft otomatis tersimpan setiap 30 detik</li>
                    </ul>
                </div>
            </div>

            <!-- Help Card -->
            <div class="card shadow border-left-secondary mb-4">
                <div class="card-body">
                    <h6 class="text-secondary mb-2">
                        <i class="fas fa-question-circle"></i> Bantuan
                    </h6>
                    <div class="text-muted small">
                        <p><strong>Keyboard Shortcuts:</strong></p>
                        <ul class="mb-2">
                            <li>Ctrl + S: Save Draft</li>
                            <li>Ctrl + Enter: Submit Form</li>
                            <li>Shift + Esc: Reset Form</li>
                            <li>F9: Quick Preview</li>
                        </ul>
                        <p><strong>Navigasi:</strong></p>
                        <ul class="mb-0">
                            <li>Tab: Pindah field</li>
                            <li>Enter: Next step</li>
                            <li>Backspace: Previous step</li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>

</div>
@push('scripts')
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>
<script>
    let currentStep = 1;
let formData = {};
let autoSaveInterval;
let selectedPaymentMethod = null;

$(document).ready(function() {
    initializeForm();
    setupEventListeners();
    setupAutoSave();
    loadDraftIfExists();
});

function initializeForm() {
    // Show first step
    showStep(1);

    // Initialize form validation
    $('#invoiceForm').on('submit', handleFormSubmission);

    // Setup booking search
    setupBookingSearch();

    // Initialize payment method selection
    initializePaymentMethods();
}

function initializePaymentMethods() {
    // Check if there's a pre-selected payment method from old input
    const oldPaymentMethod = $('#metode_pembayaran_id').val();
    if (oldPaymentMethod) {
        selectPaymentMethod(oldPaymentMethod);
    }
}

function selectPaymentMethod(methodId) {
    // Remove selection from all payment method cards
    $('.payment-method-card').removeClass('selected');
    $('.payment-method-check i').hide();

    // Add selection to clicked card
    const selectedCard = $(`.payment-method-card[data-method-id="${methodId}"]`);
    selectedCard.addClass('selected');
    selectedCard.find('.payment-method-check i').show();

    // Update hidden input
    $('#metode_pembayaran_id').val(methodId);
    selectedPaymentMethod = methodId;

    // Update preview and validation
    updatePreview();

    // Mark step as completed if payment method is selected
    if (methodId) {
        updateStepStatus(3, 'completed');
    }

    // Show success feedback
    const methodName = selectedCard.find('.font-weight-bold').text();
    showToast('success', `Metode pembayaran "${methodName}" dipilih`);
}

function setupEventListeners() {
    // Booking selection
    $('#booking_id').on('change', function() {
        updateGuestInfo();
        updateBookingDetails();
        updatePreview();

        if ($(this).val()) {
            updateStepStatus(1, 'completed');
            if (currentStep === 1) {
                setTimeout(() => changeStep(1), 500);
            }
        } else {
            updateStepStatus(1, 'active');
        }
    });

    // Date inputs
    $('#invoice_date, #due_date').on('change', function() {
        validateDates();
        updatePreview();

        if ($('#invoice_date').val() && $('#due_date').val()) {
            updateStepStatus(2, 'completed');
        }
    });

    // Discount and tax inputs
    $('#discount_amount, #tax_rate').on('input', function() {
        updatePreview();
        updateCalculationDisplay();

        // Check if step 3 is completed (discount/tax + payment method)
        if (selectedPaymentMethod && ($('#discount_amount').val() !== '' || $('#tax_rate').val() !== '')) {
            updateStepStatus(3, 'completed');
        }
    });

    // Notes input
    $('#notes').on('input', function() {
        updateFinalReview();
    });

    // Keyboard shortcuts
    $(document).keydown(function(e) {
        // F9 for preview
        if (e.keyCode === 120) {
            e.preventDefault();
            previewInvoiceData();
        }

        // Ctrl/Cmd + S for save draft
        if ((e.ctrlKey || e.metaKey) && e.keyCode === 83) {
            e.preventDefault();
            saveDraft();
        }

        // Ctrl/Cmd + Enter for submit
        if ((e.ctrlKey || e.metaKey) && e.keyCode === 13) {
            e.preventDefault();
            if (currentStep === 4) {
                $('#invoiceForm').submit();
            }
        }

        // Shift + Esc for clear form
        if (e.shiftKey && e.keyCode === 27) {
            e.preventDefault();
            clearForm();
        }

        // Enter for next step
        if (e.keyCode === 13 && !$(e.target).is('textarea')) {
            e.preventDefault();
            if (currentStep < 4) {
                changeStep(1);
            }
        }

        // Backspace for previous step (when not in input)
        if (e.keyCode === 8 && !$(e.target).is('input, textarea, select')) {
            e.preventDefault();
            if (currentStep > 1) {
                changeStep(-1);
            }
        }
    });
}

function setupAutoSave() {
    autoSaveInterval = setInterval(() => {
        if (hasFormData()) {
            saveDraft(true); // Silent save
        }
    }, 30000); // Every 30 seconds
}

function setupBookingSearch() {
    $('#booking_search').on('input', function() {
        const searchTerm = $(this).val().toLowerCase();
        const options = $('#booking_id option');

        options.each(function() {
            const optionText = $(this).text().toLowerCase();
            const guestName = $(this).data('guest') ? $(this).data('guest').toLowerCase() : '';

            if (optionText.includes(searchTerm) || guestName.includes(searchTerm)) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    });
}

function clearBookingSearch() {
    $('#booking_search').val('');
    $('#booking_id option').show();
}

function showStep(step) {
    // Hide all steps
    $('.form-step').hide();

    // Show current step
    $(`#form-step-${step}`).fadeIn(300);

    // Update navigation buttons
    updateNavigationButtons(step);

    // Update step indicator
    updateStepIndicator(step);

    currentStep = step;
}

function changeStep(direction) {
    const newStep = currentStep + direction;

    if (newStep < 1 || newStep > 4) return;

    // Validate current step before moving
    if (direction > 0 && !validateCurrentStep()) {
        return;
    }

    showStep(newStep);

    // Auto-focus first input in new step
    setTimeout(() => {
        $(`#form-step-${newStep} .form-control:first`).focus();
    }, 350);
}

function validateCurrentStep() {
    switch (currentStep) {
        case 1:
            if (!$('#booking_id').val()) {
                showValidationError('Silakan pilih booking terlebih dahulu');
                return false;
            }
            break;

        case 2:
            if (!$('#invoice_date').val() || !$('#due_date').val()) {
                showValidationError('Silakan isi tanggal invoice dan jatuh tempo');
                return false;
            }
            if (!validateDates()) {
                return false;
            }
            break;

        case 3:
            // Validate payment method selection
            if (!selectedPaymentMethod || !$('#metode_pembayaran_id').val()) {
                showValidationError('Silakan pilih metode pembayaran');
                return false;
            }

            // Optional validation for discount/tax
            const discount = parseFloat($('#discount_amount').val()) || 0;
            const taxRate = parseFloat($('#tax_rate').val()) || 0;

            if (discount < 0) {
                showValidationError('Diskon tidak boleh negatif');
                return false;
            }

            if (taxRate < 0 || taxRate > 100) {
                showValidationError('Pajak harus antara 0-100%');
                return false;
            }
            break;
    }

    return true;
}

function validateDates() {
    const invoiceDate = new Date($('#invoice_date').val());
    const dueDate = new Date($('#due_date').val());
    const today = new Date();
    today.setHours(0, 0, 0, 0);

    if (invoiceDate < today) {
        showValidationError('Tanggal invoice tidak boleh di masa lalu');
        $('#invoice_date').focus();
        return false;
    }

    if (dueDate < invoiceDate) {
        showValidationError('Tanggal jatuh tempo tidak boleh sebelum tanggal invoice');
        $('#due_date').focus();
        return false;
    }

    return true;
}

function showValidationError(message) {
    Swal.fire({
        icon: 'warning',
        title: 'Validasi Error',
        text: message,
        timer: 3000,
        showConfirmButton: false,
        toast: true,
        position: 'top-end'
    });
}

function updateNavigationButtons(step) {
    if (step === 1) {
        $('#prevBtn').hide();
    } else {
        $('#prevBtn').show();
    }

    if (step === 4) {
        $('#nextBtn').hide();
        $('#submitBtn').show();
    } else {
        $('#nextBtn').show();
        $('#submitBtn').hide();
    }
}

function updateStepIndicator(activeStep) {
    $('.step').removeClass('active');
    $(`#step-${activeStep}`).addClass('active');
}

function updateStepStatus(step, status) {
    const stepElement = $(`#step-${step}`);
    stepElement.removeClass('active completed');
    stepElement.addClass(status);
}

function updateGuestInfo() {
    const selectedOption = $('#booking_id option:selected');

    if (selectedOption.val()) {
        const guestName = selectedOption.data('guest');
        const guestPhone = selectedOption.data('phone');
        const guestEmail = selectedOption.data('email');
        const checkinDate = selectedOption.data('checkin');
        const checkoutDate = selectedOption.data('checkout');

        const guestInfoHtml = `
            <table class="table table-borderless table-sm">
                <tr>
                    <td><strong>Nama:</strong></td>
                    <td>${guestName}</td>
                </tr>
                <tr>
                    <td><strong>Telepon:</strong></td>
                    <td>${guestPhone || 'Tidak ada'}</td>
                </tr>
                <tr>
                    <td><strong>Email:</strong></td>
                    <td>${guestEmail || 'Tidak ada'}</td>
                </tr>
                <tr>
                    <td><strong>Check-in:</strong></td>
                    <td>${checkinDate}</td>
                </tr>
                <tr>
                    <td><strong>Check-out:</strong></td>
                    <td>${checkoutDate}</td>
                </tr>
            </table>
        `;

        $('#guestInfo').html(guestInfoHtml);
        $('#guestInfoCard').fadeIn();
    } else {
        $('#guestInfoCard').fadeOut();
    }
}

function updateBookingDetails() {
    const selectedOption = $('#booking_id option:selected');

    if (selectedOption.val()) {
        const bookingId = selectedOption.val();
        const rooms = selectedOption.data('rooms');
        const services = selectedOption.data('services');
        const roomTotal = selectedOption.data('room-total');
        const servicesTotal = selectedOption.data('services-total');

        const bookingDetailsHtml = `
            <table class="table table-borderless table-sm">
                <tr>
                    <td><strong>Booking ID:</strong></td>
                    <td>#${bookingId}</td>
                </tr>
                <tr>
                    <td><strong>Jumlah Kamar:</strong></td>
                    <td>${rooms} kamar</td>
                </tr>
                <tr>
                    <td><strong>Layanan:</strong></td>
                    <td>${services} item</td>
                </tr>
                <tr>
                    <td><strong>Total Kamar:</strong></td>
                    <td class="text-success"><strong>Rp ${parseFloat(roomTotal).toLocaleString('id-ID')}</strong></td>
                </tr>
                <tr>
                    <td><strong>Total Layanan:</strong></td>
                    <td class="text-info"><strong>Rp ${parseFloat(servicesTotal).toLocaleString('id-ID')}</strong></td>
                </tr>
            </table>
        `;

        $('#bookingDetails').html(bookingDetailsHtml);
        $('#bookingDetailsCard').fadeIn();
    } else {
        $('#bookingDetailsCard').fadeOut();
    }
}

function updatePreview() {
    const bookingId = $('#booking_id').val();
    const discountAmount = parseFloat($('#discount_amount').val()) || 0;
    const taxRate = parseFloat($('#tax_rate').val()) || 11;
    const metodePembayaranId = $('#metode_pembayaran_id').val();

    if (!bookingId) {
        $('#previewCard').fadeOut();
        return;
    }

    // Show loading
    $('#invoicePreview').html(`
        <div class="text-center py-3">
            <div class="spinner-border spinner-border-sm text-primary" role="status">
                <span class="sr-only">Loading...</span>
            </div>
            <p class="mt-2 text-muted">Memuat preview...</p>
        </div>
    `);
    $('#previewCard').fadeIn();

    $.ajax({
        url: '{{ route("api.invoices.preview") }}',
        method: 'GET',
        data: {
            booking_id: bookingId,
            discount_amount: discountAmount,
            tax_rate: taxRate,
            metode_pembayaran_id: metodePembayaranId
        },
        success: function(response) {
            if (response.success) {
                const data = response.data;

                const previewHtml = `
                    <div class="table-responsive">
                        <table class="table table-borderless table-sm">
                            <tr>
                                <td><strong>Total Kamar:</strong></td>
                                <td class="text-right">Rp ${data.room_total.toLocaleString('id-ID')}</td>
                            </tr>
                            <tr>
                                <td><strong>Total Layanan:</strong></td>
                                <td class="text-right">Rp ${data.services_total.toLocaleString('id-ID')}</td>
                            </tr>
                            <tr class="border-top">
                                <td><strong>Subtotal:</strong></td>
                                <td class="text-right">Rp ${data.subtotal.toLocaleString('id-ID')}</td>
                            </tr>
                            ${data.discount_amount > 0 ? `
                            <tr>
                                <td><strong>Diskon:</strong></td>
                                <td class="text-right text-danger">- Rp ${data.discount_amount.toLocaleString('id-ID')}</td>
                            </tr>
                            ` : ''}
                            <tr>
                                <td><strong>Pajak (${data.tax_rate}%):</strong></td>
                                <td class="text-right">Rp ${data.tax_amount.toLocaleString('id-ID')}</td>
                            </tr>
                            ${data.admin_fee && data.admin_fee > 0 ? `
                            <tr>
                                <td><strong>Biaya Admin:</strong></td>
                                <td class="text-right">Rp ${data.admin_fee.toLocaleString('id-ID')}</td>
                            </tr>
                            ` : ''}
                            ${data.payment_method ? `
                            <tr>
                                <td><strong>Metode Bayar:</strong></td>
                                <td class="text-right">${data.payment_method}</td>
                            </tr>
                            ` : ''}
                        </table>
                    </div>

                    <div class="mt-3">
                        <small class="text-muted">
                            <i class="fas fa-info-circle"></i>
                            Preview real-time berdasarkan data terkini
                        </small>
                    </div>
                `;

                $('#invoicePreview').html(previewHtml);
                $('#grandTotalAmount').text('Rp ' + data.grand_total.toLocaleString('id-ID'));

                // Store data for final review
                formData.previewData = data;
                updateFinalReview();
            } else {
                $('#invoicePreview').html(`
                    <div class="alert alert-warning">
                        <i class="fas fa-exclamation-triangle"></i>
                        Gagal memuat preview
                    </div>
                `);
            }
        },
        error: function(xhr) {
            let errorMsg = 'Gagal memuat preview';
            if (xhr.status === 404) {
                errorMsg = 'Booking tidak ditemukan';
            } else if (xhr.status === 422) {
                errorMsg = 'Data booking tidak valid';
            }

            $('#invoicePreview').html(`
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle"></i>
                    ${errorMsg}
                </div>
            `);
        }
    });
}

function updateCalculationDisplay() {
    if (!formData.previewData) return;

    const data = formData.previewData;
    const calculationHtml = `
        <div class="row">
            <div class="col-6">
                <small><strong>Subtotal:</strong></small><br>
                <span class="text-primary">Rp ${data.subtotal.toLocaleString('id-ID')}</span>
            </div>
            <div class="col-6">
                <small><strong>Grand Total:</strong></small><br>
                <span class="text-success"><strong>Rp ${data.grand_total.toLocaleString('id-ID')}</strong></span>
            </div>
        </div>
    `;

    $('#calculation-display').html(calculationHtml);
}

function updateFinalReview() {
    const bookingId = $('#booking_id').val();
    const selectedOption = $('#booking_id option:selected');

    if (!bookingId || !formData.previewData) {
        $('#final-review').html('<p class="text-muted">Lengkapi form untuk melihat ringkasan</p>');
        return;
    }

    const guestName = selectedOption.data('guest');
    const invoiceDate = $('#invoice_date').val();
    const dueDate = $('#due_date').val();
    const notes = $('#notes').val();
    const data = formData.previewData;

    const reviewHtml = `
        <div class="row">
            <div class="col-md-6">
                <h6>Informasi Umum:</h6>
                <table class="table table-borderless table-sm">
                    <tr><td><strong>Tamu:</strong></td><td>${guestName}</td></tr>
                    <tr><td><strong>Booking:</strong></td><td>#${bookingId}</td></tr>
                    <tr><td><strong>Tanggal Invoice:</strong></td><td>${formatDate(invoiceDate)}</td></tr>
                    <tr><td><strong>Jatuh Tempo:</strong></td><td>${formatDate(dueDate)}</td></tr>
                    ${data.payment_method ? `<tr><td><strong>Metode Bayar:</strong></td><td>${data.payment_method}</td></tr>` : ''}
                </table>
            </div>
            <div class="col-md-6">
                <h6>Ringkasan Biaya:</h6>
                <table class="table table-borderless table-sm">
                    <tr><td><strong>Kamar:</strong></td><td class="text-right">Rp ${data.room_total.toLocaleString('id-ID')}</td></tr>
                    <tr><td><strong>Layanan:</strong></td><td class="text-right">Rp ${data.services_total.toLocaleString('id-ID')}</td></tr>
                    ${data.discount_amount > 0 ? `<tr><td><strong>Diskon:</strong></td><td class="text-right text-danger">- Rp ${data.discount_amount.toLocaleString('id-ID')}</td></tr>` : ''}
                    <tr><td><strong>Pajak:</strong></td><td class="text-right">Rp ${data.tax_amount.toLocaleString('id-ID')}</td></tr>
                    ${data.admin_fee && data.admin_fee > 0 ? `<tr><td><strong>Biaya Admin:</strong></td><td class="text-right">Rp ${data.admin_fee.toLocaleString('id-ID')}</td></tr>` : ''}
                    <tr class="border-top"><td><strong>Total:</strong></td><td class="text-right"><strong>Rp ${data.grand_total.toLocaleString('id-ID')}</strong></td></tr>
                </table>
            </div>
        </div>
        ${notes ? `
        <div class="mt-3">
            <h6>Catatan:</h6>
            <p class="text-muted">${notes}</p>
        </div>
        ` : ''}
    `;

    $('#final-review').html(reviewHtml);
}

// Quick preset functions
function applyPreset(preset) {
    const today = new Date();
    let dueDate = new Date(today);

    switch (preset) {
        case 'same_day':
            dueDate = new Date(today);
            break;
        case 'next_day':
            dueDate.setDate(today.getDate() + 1);
            break;
        case '3_days':
            dueDate.setDate(today.getDate() + 3);
            break;
        case '7_days':
            dueDate.setDate(today.getDate() + 7);
            break;
        case '30_days':
            dueDate.setDate(today.getDate() + 30);
            break;
    }

    const invoiceDateStr = today.toISOString().split('T')[0];
    const dueDateStr = dueDate.toISOString().split('T')[0];

    $('#invoice_date').val(invoiceDateStr);
    $('#due_date').val(dueDateStr);

    showToast('success', `Preset "${preset.replace('_', ' ')}" diterapkan!`);
    updatePreview();
}

function applyDiscount(percentage) {
    if (!formData.previewData) {
        showToast('warning', 'Pilih booking terlebih dahulu');
        return;
    }

    const subtotal = formData.previewData.subtotal;
    const discountAmount = (subtotal * percentage) / 100;

    $('#discount_amount').val(Math.round(discountAmount));
    showToast('success', `Diskon ${percentage}% diterapkan!`);
    updatePreview();
}

function calculatePercentageDiscount() {
    if (!formData.previewData) {
        showToast('warning', 'Pilih booking terlebih dahulu');
        return;
    }

    Swal.fire({
        title: 'Hitung Diskon Persentase',
        html: `
            <div class="form-group">
                <label>Persentase Diskon:</label>
                <div class="input-group">
                    <input type="number" class="form-control" id="discount-percentage" min="0" max="100" step="0.1">
                    <div class="input-group-append">
                        <span class="input-group-text">%</span>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <label>Subtotal:</label>
                <p class="form-control-plaintext">Rp ${formData.previewData.subtotal.toLocaleString('id-ID')}</p>
            </div>
            <div class="form-group">
                <label>Nominal Diskon:</label>
                <p class="form-control-plaintext" id="calculated-discount">Rp 0</p>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Terapkan',
        cancelButtonText: 'Batal',
        didOpen: () => {
            $('#discount-percentage').on('input', function() {
                const percentage = parseFloat($(this).val()) || 0;
                const discountAmount = (formData.previewData.subtotal * percentage) / 100;
                $('#calculated-discount').text('Rp ' + Math.round(discountAmount).toLocaleString('id-ID'));
            });
        },
        preConfirm: () => {
            const percentage = parseFloat($('#discount-percentage').val()) || 0;
            return (formData.previewData.subtotal * percentage) / 100;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            $('#discount_amount').val(Math.round(result.value));
            updatePreview();
        }
    });
}

function setTaxRate(rate) {
    $('#tax_rate').val(rate);
    showToast('success', `Pajak diatur ke ${rate}%`);
    updatePreview();
}

// Draft management
function saveDraft(silent = false) {
    const draftData = {
        booking_id: $('#booking_id').val(),
        invoice_date: $('#invoice_date').val(),
        due_date: $('#due_date').val(),
        discount_amount: $('#discount_amount').val(),
        tax_rate: $('#tax_rate').val(),
        metode_pembayaran_id: $('#metode_pembayaran_id').val(),
        notes: $('#notes').val(),
        current_step: currentStep,
        selected_payment_method: selectedPaymentMethod,
        timestamp: new Date().toISOString()
    };

    localStorage.setItem('invoice_draft', JSON.stringify(draftData));

    if (!silent) {
        showToast('success', 'Draft tersimpan!');
    }
}

function loadDraftIfExists() {
    const draft = localStorage.getItem('invoice_draft');
    if (draft) {
        const draftData = JSON.parse(draft);
        const draftAge = new Date() - new Date(draftData.timestamp);

        // Only load draft if less than 24 hours old
        if (draftAge < 24 * 60 * 60 * 1000) {
            Swal.fire({
                title: 'Draft Ditemukan',
                html: `
                    <p>Draft tersimpan pada: <strong>${formatDateTime(draftData.timestamp)}</strong></p>
                    <p>Apakah Anda ingin melanjutkan dari draft yang tersimpan?</p>
                `,
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Ya, Lanjutkan',
                cancelButtonText: 'Tidak, Mulai Baru'
            }).then((result) => {
                if (result.isConfirmed) {
                    loadDraft(draftData);
                } else {
                    localStorage.removeItem('invoice_draft');
                }
            });
        } else {
            localStorage.removeItem('invoice_draft');
        }
    }
}

function loadDraft(draftData = null) {
    if (!draftData) {
        const draft = localStorage.getItem('invoice_draft');
        if (!draft) {
            showToast('warning', 'Tidak ada draft yang tersimpan');
            return;
        }
        draftData = JSON.parse(draft);
    }

    // Load form data
    $('#booking_id').val(draftData.booking_id).trigger('change');
    $('#invoice_date').val(draftData.invoice_date);
    $('#due_date').val(draftData.due_date);
    $('#discount_amount').val(draftData.discount_amount);
    $('#tax_rate').val(draftData.tax_rate);
    $('#notes').val(draftData.notes);

    // Load payment method selection
    if (draftData.metode_pembayaran_id) {
        selectPaymentMethod(draftData.metode_pembayaran_id);
    }

    // Go to saved step
    if (draftData.current_step) {
        showStep(draftData.current_step);
    }

    // Update UI
    updateGuestInfo();
    updateBookingDetails();
    updatePreview();

    showToast('success', 'Draft berhasil dimuat!');
}

function clearForm() {
    Swal.fire({
        title: 'Reset Form?',
        text: 'Semua data yang sudah diisi akan hilang',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Ya, Reset',
        cancelButtonText: 'Batal'
    }).then((result) => {
        if (result.isConfirmed) {
            $('#invoiceForm')[0].reset();
            showStep(1);
            $('#guestInfoCard, #bookingDetailsCard, #previewCard').fadeOut();
            $('.step').removeClass('completed');
            $('.payment-method-card').removeClass('selected');
            $('.payment-method-check i').hide();
            localStorage.removeItem('invoice_draft');
            formData = {};
            selectedPaymentMethod = null;

            showToast('success', 'Form berhasil direset!');
        }
    });
}

function previewInvoiceData() {
    const bookingId = $('#booking_id').val();
    if (!bookingId) {
        showToast('warning', 'Pilih booking terlebih dahulu');
        return;
    }

    if (!formData.previewData) {
        showToast('warning', 'Data preview belum tersedia');
        return;
    }

    const data = formData.previewData;
    const selectedOption = $('#booking_id option:selected');
    const guestName = selectedOption.data('guest');

    Swal.fire({
        title: 'Preview Invoice',
        html: `
            <div class="text-left">
                <div class="row mb-3">
                    <div class="col-6">
                        <strong>Tamu:</strong><br>
                        ${guestName}
                    </div>
                    <div class="col-6">
                        <strong>Booking:</strong><br>
                        #${bookingId}
                    </div>
                </div>
                <table class="table table-sm">
                    <tr><td><strong>Total Kamar:</strong></td><td class="text-right">Rp ${data.room_total.toLocaleString('id-ID')}</td></tr>
                    <tr><td><strong>Total Layanan:</strong></td><td class="text-right">Rp ${data.services_total.toLocaleString('id-ID')}</td></tr>
                    <tr><td><strong>Subtotal:</strong></td><td class="text-right">Rp ${data.subtotal.toLocaleString('id-ID')}</td></tr>
                    ${data.discount_amount > 0 ? `<tr><td><strong>Diskon:</strong></td><td class="text-right text-danger">- Rp ${data.discount_amount.toLocaleString('id-ID')}</td></tr>` : ''}
                    <tr><td><strong>Pajak (${data.tax_rate}%):</strong></td><td class="text-right">Rp ${data.tax_amount.toLocaleString('id-ID')}</td></tr>
                    ${data.admin_fee && data.admin_fee > 0 ? `<tr><td><strong>Biaya Admin:</strong></td><td class="text-right">Rp ${data.admin_fee.toLocaleString('id-ID')}</td></tr>` : ''}
                    ${data.payment_method ? `<tr><td><strong>Metode Bayar:</strong></td><td class="text-right">${data.payment_method}</td></tr>` : ''}
                    <tr class="table-success"><td><strong>Grand Total:</strong></td><td class="text-right"><strong>Rp ${data.grand_total.toLocaleString('id-ID')}</strong></td></tr>
                </table>
            </div>
        `,
        icon: 'info',
        confirmButtonText: 'Tutup',
        width: '600px'
    });
}

// Form submission
function handleFormSubmission(e) {
    e.preventDefault();

    // Final validation
    if (!validateAllSteps()) {
        return;
    }

    const formData = new FormData(this);
    const submitBtn = $('#submitBtn');
    const originalText = submitBtn.html();

    // Show loading state
    submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Membuat Invoice...');
    $('.card-body').addClass('loading');

    // Clear previous errors
    $('.form-control').removeClass('is-invalid');
    $('.invalid-feedback').remove();

    $.ajax({
        url: $(this).attr('action'),
        method: 'POST',
        data: formData,
        processData: false,
        contentType: false,
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
            'Accept': 'application/json'
        },
        dataType: 'json',
        success: function(response) {
            if (response.success) {
                // Clear draft and auto-save
                localStorage.removeItem('invoice_draft');
                clearInterval(autoSaveInterval);

                Swal.fire({
                    icon: 'success',
                    title: 'Invoice Berhasil Dibuat!',
                    html: `
                        <div class="text-center">
                            <i class="fas fa-file-invoice fa-3x text-success mb-3"></i>
                            <p>${response.message}</p>
                            <div class="mt-3">
                                <button class="btn btn-primary btn-sm mr-2" onclick="window.location.href='${response.redirect_url}'">
                                    <i class="fas fa-eye"></i> Lihat Invoice
                                </button>
                                <button class="btn btn-success btn-sm mr-2" onclick="window.open('${response.redirect_url.replace('/show/', '/download-pdf/')}')" }}>
                                    <i class="fas fa-download"></i> Download PDF
                                </button>
                                <button class="btn btn-info btn-sm" onclick="window.location.href='{{ route('invoices.create') }}'">
                                    <i class="fas fa-plus"></i> Buat Lagi
                                </button>
                            </div>
                        </div>
                    `,
                    showConfirmButton: false,
                    allowOutsideClick: false,
                    timer: 10000
                }).then(() => {
                    window.location.href = response.redirect_url || '{{ route("invoices.index") }}';
                });
            }
        },
        error: function(xhr) {
            if (xhr.status === 422) {
                const errors = xhr.responseJSON.errors;
                let hasErrors = false;

                Object.keys(errors).forEach(function(key) {
                    const field = $(`#${key}, [name="${key}"]`);
                    if (field.length > 0) {
                        field.addClass('is-invalid');
                        field.after(`<div class="invalid-feedback">${errors[key][0]}</div>`);
                        hasErrors = true;

                        // Go to step with error
                        const stepWithError = field.closest('.form-step').attr('id').split('-')[2];
                        if (stepWithError) {
                            showStep(parseInt(stepWithError));
                        }
                    }
                });

                if (hasErrors) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Validasi Error!',
                        text: xhr.responseJSON.message || 'Silakan periksa form Anda.',
                        confirmButtonText: 'Perbaiki Form'
                    });
                }
            } else if (xhr.status === 400) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Peringatan!',
                    text: xhr.responseJSON?.message || 'Terjadi masalah dengan data yang dikirim.',
                    confirmButtonText: 'Coba Lagi'
                });
            } else {
                const message = xhr.responseJSON?.message || 'Terjadi kesalahan saat membuat invoice.';
                Swal.fire({
                    icon: 'error',
                    title: 'Server Error!',
                    text: message,
                    footer: '<small>Jika masalah berlanjut, hubungi administrator</small>',
                    confirmButtonText: 'Tutup'
                });
            }
        },
        complete: function() {
            submitBtn.prop('disabled', false).html(originalText);
            $('.card-body').removeClass('loading');
        }
    });
}

function validateAllSteps() {
    // Step 1: Booking selection
    if (!$('#booking_id').val()) {
        showStep(1);
        showValidationError('Silakan pilih booking');
        return false;
    }

    // Step 2: Dates
    if (!$('#invoice_date').val() || !$('#due_date').val()) {
        showStep(2);
        showValidationError('Silakan isi tanggal invoice dan jatuh tempo');
        return false;
    }

    if (!validateDates()) {
        showStep(2);
        return false;
    }

    // Step 3: Payment method selection
    if (!selectedPaymentMethod || !$('#metode_pembayaran_id').val()) {
        showStep(3);
        showValidationError('Silakan pilih metode pembayaran');
        return false;
    }

    // Step 3: Discount and tax validation
    const discount = parseFloat($('#discount_amount').val()) || 0;
    const taxRate = parseFloat($('#tax_rate').val()) || 0;

    if (discount < 0) {
        showStep(3);
        showValidationError('Diskon tidak boleh negatif');
        return false;
    }

    if (taxRate < 0 || taxRate > 100) {
        showStep(3);
        showValidationError('Pajak harus antara 0-100%');
        return false;
    }

    return true;
}

// Helper functions
function hasFormData() {
    return $('#booking_id').val() ||
           $('#invoice_date').val() ||
           $('#due_date').val() ||
           $('#discount_amount').val() ||
           $('#tax_rate').val() !== '11' ||
           $('#metode_pembayaran_id').val() ||
           $('#notes').val();
}

function showToast(icon, title, timer = 2000) {
    Swal.fire({
        icon: icon,
        title: title,
        timer: timer,
        showConfirmButton: false,
        toast: true,
        position: 'top-end'
    });
}

function formatDate(dateString) {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleDateString('id-ID', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric'
    });
}

function formatDateTime(dateTimeString) {
    if (!dateTimeString) return '';
    const date = new Date(dateTimeString);
    return date.toLocaleString('id-ID', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// Cleanup on page unload
$(window).on('beforeunload', function(e) {
    if (hasFormData() && !$('#invoiceForm').hasClass('submitted')) {
        const message = 'Anda memiliki perubahan yang belum disimpan. Yakin ingin meninggalkan halaman?';
        e.returnValue = message;
        return message;
    }
});

// Mark form as submitted to prevent beforeunload warning
$('#invoiceForm').on('submit', function() {
    $(this).addClass('submitted');
});

// Initialize on page load
$(document).ready(function() {
    // Auto-focus first input
    $('#booking_id').focus();

    // Initialize tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Show initial step
    showStep(1);

    // If booking is pre-selected (from URL parameter)
    if ($('#booking_id').val()) {
        $('#booking_id').trigger('change');
    }
});
</script>
@endpush
@endsection
