<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
     
    @hotelSettings
    <title>Create Reservation - {{ hotelName() }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/css/intlTelInput.css" rel="stylesheet" />
    <style>
        :root {
            --primary-green: #1a936f;
            --secondary-green: #88d498;
            --light-green: #c6dabf;
            --dark-green: #114b5f;
            --accent: #f3e9d2;
        }
        
        body {
            background-color: #f8f9fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            padding: 20px;
        }
        
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .btn-primary {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
        }
        
        .btn-outline-primary {
            color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-outline-primary:hover {
            background-color: var(--primary-green);
            color: white;
        }
        
        .btn-outline-secondary {
            color: #6c757d;
            border-color: #6c757d;
        }
        
        .btn-outline-secondary:hover {
            background-color: #6c757d;
            border-color: #6c757d;
            color: white;
        }
        
        .card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .card-header {
            background: linear-gradient(90deg, var(--primary-green) 0%, var(--secondary-green) 100%);
            color: white;
            border-radius: 10px 10px 0 0 !important;
        }
        
        .form-label {
            font-weight: 600;
            color: var(--dark-green);
        }
        
        .required:after {
            content: " *";
            color: #dc3545;
        }

        /* Guest Selection Styles */
        .guest-option-container {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 0.375rem;
            padding: 20px;
            margin-bottom: 20px;
        }

        .guest-option-tabs {
            display: flex;
            border-bottom: 1px solid #dee2e6;
            margin-bottom: 20px;
        }

        .guest-option-tab {
            flex: 1;
            padding: 10px 15px;
            text-align: center;
            cursor: pointer;
            border: none;
            background: none;
            font-weight: 600;
            color: #6c757d;
            transition: all 0.3s;
            border-bottom: 3px solid transparent;
        }

        .guest-option-tab:hover {
            color: var(--primary-green);
        }

        .guest-option-tab.active {
            color: var(--primary-green);
            border-bottom: 3px solid var(--primary-green);
        }

        .guest-option-content {
            display: none;
        }

        .guest-option-content.active {
            display: block;
        }

        .guest-email-warning {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            color: #856404;
            padding: 10px 15px;
            border-radius: 5px;
            margin-bottom: 15px;
            display: none;
        }

        .guest-email-warning.show {
            display: block;
        }

        /* Select2 Custom Styling */
        .select2-container--default .select2-selection--single {
            border: 1px solid #ced4da;
            border-radius: 0.375rem;
            height: 38px;
            padding: 0.375rem 0.75rem;
        }

        .select2-container--default .select2-selection--single .select2-selection__arrow {
            height: 36px;
        }

        .select2-container--default .select2-selection--single .select2-selection__rendered {
            line-height: 24px;
            padding-left: 0;
        }

        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: var(--primary-green);
        }

        .select2-container--default .select2-selection--single {
            background-color: #fff;
        }

        .guest-option {
            padding: 8px 12px;
            border-bottom: 1px solid #f0f0f0;
        }

        .guest-option:last-child {
            border-bottom: none;
        }

        .guest-name {
            font-weight: 600;
            color: var(--dark-green);
        }

        .guest-details {
            font-size: 0.875rem;
            color: #6c757d;
        }

        .guest-phone, .guest-email {
            margin-right: 10px;
        }
        
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
        }

        /* VAT Calculation Styles */
        .vat-calculation-container {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 0.375rem;
            padding: 20px;
            margin-bottom: 20px;
        }

        .calculation-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px dashed #dee2e6;
        }

        .calculation-row:last-child {
            border-bottom: none;
        }

        .calculation-label {
            font-weight: 500;
            color: #495057;
        }

        .calculation-value {
            font-weight: 600;
            color: var(--dark-green);
        }

        .total-row {
            font-size: 1.1rem;
            font-weight: 700;
            color: var(--primary-green);
            border-top: 2px solid var(--primary-green);
            margin-top: 10px;
            padding-top: 10px;
        }

        .balance-row {
            background-color: #e8f5e9;
            padding: 10px;
            border-radius: 0.375rem;
            margin-top: 10px;
            font-weight: 600;
        }

        .balance-positive {
            color: #dc3545;
        }

        .balance-zero {
            color: var(--primary-green);
        }

        /* Country Code Input Styling - FIXED */
        .iti {
            width: 100%;
            display: block;
        }
        
        .iti__country {
            font-size: 14px;
        }
        
        .iti__flag-container {
            z-index: 2;
            padding: 0;
        }
        
        /* Fix for the phone input */
        .iti--allow-dropdown input, 
        .iti--allow-dropdown input[type=tel],
        .iti--separate-dial-code input,
        .iti--separate-dial-code input[type=tel] {
            padding-left: 90px !important;
            height: 38px;
            width: 100%;
            border-radius: 0.375rem;
        }
        
        /* Adjust for different dial code lengths */
        .iti--separate-dial-code .iti__selected-dial-code {
            font-size: 14px;
        }
        
        .iti__flag-container .iti__selected-flag {
            background-color: #f8f9fa;
            border-right: 1px solid #ced4da;
            border-radius: 0.375rem 0 0 0.375rem;
            height: 36px;
            padding: 0 6px 0 8px;
        }
        
        .iti__flag-container .iti__selected-flag:hover {
            background-color: #e9ecef;
        }
        
        .iti__country-list {
            border-radius: 0.375rem;
            border: 1px solid #ced4da;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            z-index: 1050;
            max-height: 250px;
            width: 350px;
        }
        
        .iti__country-name {
            color: #212529;
        }
        
        .iti__dial-code {
            color: #6c757d;
        }
        
        .iti__country.iti__highlight {
            background-color: var(--light-green);
        }
        
        /* Container for the phone input to ensure proper spacing */
        .phone-input-container {
            position: relative;
            width: 100%;
        }
        
        /* Page Title */
        .page-title {
            font-size: 2.5rem;
            font-weight: 700;
            color: #1a2b3c;
            text-align: left;
            margin: 0 0 20px 0;
            font-family: 'Inter', sans-serif;
            letter-spacing: -0.5px;
            padding: 0 0 15px 0;
            border-bottom: 3px solid var(--primary-green);
            display: inline-block;
        }
        
        .page-title i {
            color: var(--primary-green);
            margin-right: 15px;
            font-size: 2.5rem;
        }
        
        @media (max-width: 768px) {
            .main-content {
                padding: 10px;
            }
            
            .page-title {
                font-size: 2rem;
                display: block;
                text-align: center;
            }
            
            .page-title i {
                display: block;
                margin: 0 auto 10px auto;
            }
        }
    </style>
</head>
<body>
    <!-- Main Content -->
    <div class="main-content">
        <!-- Page Title and Actions -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h1 class="page-title">
                <i class="fas fa-calendar-plus"></i>
                Create New Reservation
            </h1>
            <div>
                <a href="{{ route('dashboard') }}" class="btn btn-outline-secondary me-2">
                    <i class="fas fa-tachometer-alt me-2"></i>Back to Dashboard
                </a>
                <a href="{{ route('reservations.index') }}" class="btn btn-outline-primary">
                    <i class="fas fa-arrow-left me-2"></i>Back to Reservations
                </a>
            </div>
        </div>

        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">Reservation Details</h5>
            </div>
            <div class="card-body">
                @if($errors->any())
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        <strong>Please fix the following errors:</strong>
                        <ul class="mb-0 mt-2">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

                @if(session('error'))
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                        {{ session('error') }}
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                @endif

                <form method="POST" action="{{ route('reservations.store') }}" id="reservationForm">
                    @csrf
                    
                    <!-- Guest Selection Section -->
                    <div class="guest-option-container">
                        <h6 class="mb-3 required">Guest Information</h6>
                        
                        <div class="guest-option-tabs">
                            <button type="button" class="guest-option-tab active" data-option="existing">
                                <i class="fas fa-user-friends me-2"></i>Select Existing Guest
                            </button>
                            <button type="button" class="guest-option-tab" data-option="new">
                                <i class="fas fa-user-plus me-2"></i>Add New Guest
                            </button>
                        </div>
                        
                        <!-- Existing Guest Option -->
                        <div class="guest-option-content active" id="existingGuestSection">
                            <div class="mb-3">
                                <label for="guest_search" class="form-label required">Search Guest</label>
                                <select class="form-select @error('guest_id') is-invalid @enderror" 
                                        id="guest_search" name="guest_id">
                                    <option value="">Type to search existing guests...</option>
                                    @foreach($guests as $guest)
                                        <option value="{{ $guest->id }}" 
                                                data-email="{{ $guest->email }}"
                                                data-phone="{{ $guest->phone }}"
                                                {{ old('guest_id') == $guest->id ? 'selected' : '' }}>
                                            {{ $guest->first_name }} {{ $guest->last_name }}
                                            @if($guest->email) - {{ $guest->email }} @endif
                                            @if($guest->phone) - {{ $guest->phone }} @endif
                                        </option>
                                    @endforeach
                                </select>
                                @error('guest_id')
                                    <div class="error-message">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        
                        <!-- New Guest Option -->
                        <div class="guest-option-content" id="newGuestSection">
                            <!-- Email Warning -->
                            <div class="guest-email-warning" id="emailWarning">
                                <i class="fas fa-exclamation-triangle me-2"></i>
                                <span id="warningMessage"></span>
                                <button type="button" class="btn btn-sm btn-outline-warning ms-2" id="switchToExisting">
                                    Select This Guest
                                </button>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="new_guest_first_name" class="form-label required">First Name</label>
                                        <input type="text" class="form-control @error('new_guest_first_name') is-invalid @enderror" 
                                               id="new_guest_first_name" name="new_guest_first_name" 
                                               value="{{ old('new_guest_first_name', 'NABWAMI') }}">
                                        @error('new_guest_first_name')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="new_guest_last_name" class="form-label required">Last Name</label>
                                        <input type="text" class="form-control @error('new_guest_last_name') is-invalid @enderror" 
                                               id="new_guest_last_name" name="new_guest_last_name" 
                                               value="{{ old('new_guest_last_name', 'IMMY') }}">
                                        @error('new_guest_last_name')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="new_guest_email" class="form-label">Email</label>
                                        <input type="email" class="form-control @error('new_guest_email') is-invalid @enderror" 
                                               id="new_guest_email" name="new_guest_email" 
                                               value="{{ old('new_guest_email', 'nwnabami@gmail.com') }}">
                                        @error('new_guest_email')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                        <div class="form-text">Leave blank if guest doesn't have an email</div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="new_guest_phone" class="form-label">Phone</label>
                                        <div class="phone-input-container">
                                            <input type="tel" class="form-control @error('new_guest_phone') is-invalid @enderror" 
                                                   id="new_guest_phone" name="new_guest_phone" 
                                                   value="{{ old('new_guest_phone', '702064779') }}">
                                        </div>
                                        <input type="hidden" id="phone_country_code" name="phone_country_code" value="UG">
                                        @error('new_guest_phone')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="mb-3">
                                        <label for="new_guest_address" class="form-label">Address</label>
                                        <textarea class="form-control @error('new_guest_address') is-invalid @enderror" 
                                                  id="new_guest_address" name="new_guest_address" rows="2">{{ old('new_guest_address') }}</textarea>
                                        @error('new_guest_address')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Room Selection -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="room_id" class="form-label required">Room</label>
                                <select class="form-select @error('room_id') is-invalid @enderror" id="room_id" name="room_id" required>
                                    <option value="">Select Room</option>
                                    @foreach($rooms as $room)
                                        <option value="{{ $room->id }}" 
                                                data-price="{{ $room->price_per_night }}"
                                                data-capacity="{{ $room->capacity }}"
                                                {{ old('room_id') == $room->id ? 'selected' : '' }}>
                                            {{ $room->room_number }} ({{ $room->roomType->name ?? 'N/A' }}) - 
                                            UGX {{ number_format($room->price_per_night, 2) }}/night
                                        </option>
                                    @endforeach
                                </select>
                                @error('room_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="is_walk_in" class="form-label">Reservation Type</label>
                                <select class="form-select @error('is_walk_in') is-invalid @enderror" id="is_walk_in" name="is_walk_in">
                                    <option value="0" {{ old('is_walk_in', '0') == '0' ? 'selected' : '' }}>Regular Reservation</option>
                                    <option value="1" {{ old('is_walk_in') == '1' ? 'selected' : '' }}>Walk-in Reservation</option>
                                </select>
                                @error('is_walk_in')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                    
                    <!-- Dates and Guests -->
                    <div class="row">
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="check_in" class="form-label required">Check-in Date</label>
                                <input type="date" class="form-control @error('check_in') is-invalid @enderror" 
                                       id="check_in" name="check_in" value="{{ old('check_in') }}" required>
                                @error('check_in')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="check_out" class="form-label required">Check-out Date</label>
                                <input type="date" class="form-control @error('check_out') is-invalid @enderror" 
                                       id="check_out" name="check_out" value="{{ old('check_out') }}" required>
                                @error('check_out')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="adults" class="form-label required">Adults</label>
                                <input type="number" class="form-control @error('adults') is-invalid @enderror" 
                                       id="adults" name="adults" value="{{ old('adults', 1) }}" min="1" max="10" required>
                                @error('adults')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                        
                        <div class="col-md-3">
                            <div class="mb-3">
                                <label for="children" class="form-label">Children</label>
                                <input type="number" class="form-control @error('children') is-invalid @enderror" 
                                       id="children" name="children" value="{{ old('children', 0) }}" min="0" max="10">
                                @error('children')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <!-- Staff Assignment Section -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="assigned_staff_id" class="form-label">Assigned Staff</label>
                                <select class="form-select @error('assigned_staff_id') is-invalid @enderror" 
                                        id="assigned_staff_id" name="assigned_staff_id">
                                    <option value="">Select Staff Member</option>
                                    @if(isset($staff) && $staff->count() > 0)
                                        @foreach($staff as $staffMember)
                                            <option value="{{ $staffMember->id }}" 
                                                {{ old('assigned_staff_id') == $staffMember->id ? 'selected' : '' }}>
                                                {{ $staffMember->first_name }} {{ $staffMember->last_name }}
                                                @if(isset($staffMember->department) || isset($staffMember->position))
                                                    - 
                                                    @if(isset($staffMember->position) && $staffMember->position)
                                                        {{ $staffMember->position->name }}
                                                    @endif
                                                    @if(isset($staffMember->department) && $staffMember->department && isset($staffMember->position) && $staffMember->position)
                                                        , 
                                                    @endif
                                                    @if(isset($staffMember->department) && $staffMember->department)
                                                        {{ $staffMember->department->name }}
                                                    @endif
                                                @endif
                                            </option>
                                        @endforeach
                                    @else
                                        <option value="">No staff members available</option>
                                    @endif
                                </select>
                                @error('assigned_staff_id')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                    
                    <!-- VAT Calculation Section -->
                    <div class="vat-calculation-container">
                        <h6 class="mb-3 required">VAT Calculation</h6>
                        
                        <!-- Hidden fields for VAT calculation -->
                        <input type="hidden" id="vat_rate" value="{{ $vatRate ?? 18 }}">
                        <input type="hidden" id="calculated_nights" value="0">
                        <input type="hidden" id="calculated_room_charges" value="0">
                        <input type="hidden" id="calculated_vat" value="0">
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="calculation-row">
                                    <span class="calculation-label">Room Price per Night:</span>
                                    <span class="calculation-value" id="display_room_price">UGX 0</span>
                                </div>
                                <div class="calculation-row">
                                    <span class="calculation-label">Number of Nights:</span>
                                    <span class="calculation-value" id="display_nights">0</span>
                                </div>
                                <div class="calculation-row">
                                    <span class="calculation-label">Room Charges (Subtotal):</span>
                                    <span class="calculation-value" id="display_room_charges">UGX 0</span>
                                </div>
                                <div class="calculation-row">
                                    <span class="calculation-label">VAT ({{ $vatRate ?? 18 }}%):</span>
                                    <span class="calculation-value" id="display_vat">UGX 0</span>
                                </div>
                                <div class="calculation-row total-row">
                                    <span class="calculation-label">Total (Inc. VAT):</span>
                                    <span class="calculation-value" id="display_total_with_vat">UGX 0</span>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="calculation-row">
                                    <span class="calculation-label">Amount Paid:</span>
                                    <span class="calculation-value" id="display_paid_amount">UGX 0</span>
                                </div>
                                <div class="balance-row" id="balance_display">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <span class="fw-bold">Balance After Payment:</span>
                                        <span class="fw-bold" id="display_balance">UGX 0</span>
                                    </div>
                                    <small class="text-muted" id="balance_status">No payment yet</small>
                                </div>
                                <div class="mt-3 small text-muted">
                                    <i class="fas fa-info-circle me-1"></i>
                                    Total amount includes room charges and VAT. Payment status will update automatically.
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Amount and Status -->
                    <div class="row">
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="total_amount" class="form-label required">Total Amount (Inc. VAT)</label>
                                <div class="input-group">
                                    <span class="input-group-text">UGX</span>
                                    <input type="number" class="form-control @error('total_amount') is-invalid @enderror" 
                                           id="total_amount" name="total_amount" value="{{ old('total_amount') }}" 
                                           step="0.01" min="0" readonly required>
                                    @error('total_amount')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                                <small class="text-muted">Automatically calculated including VAT</small>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="paid_amount" class="form-label">Paid Amount</label>
                                <div class="input-group">
                                    <span class="input-group-text">UGX</span>
                                    <input type="number" class="form-control @error('paid_amount') is-invalid @enderror" 
                                           id="paid_amount" name="paid_amount" value="{{ old('paid_amount', 0) }}" 
                                           step="0.01" min="0">
                                    @error('paid_amount')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="col-md-4">
                            <div class="mb-3">
                                <label for="status" class="form-label required">Status</label>
                                <select class="form-select @error('status') is-invalid @enderror" id="status" name="status" required>
                                    <option value="pending" {{ old('status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                    <option value="confirmed" {{ old('status') == 'confirmed' ? 'selected' : '' }}>Confirmed</option>
                                    <option value="cancelled" {{ old('status') == 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                                </select>
                                @error('status')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <!-- Payment Status -->
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label for="payment_status" class="form-label required">Payment Status</label>
                                <select class="form-select @error('payment_status') is-invalid @enderror" 
                                        id="payment_status" name="payment_status" required>
                                    <option value="pending" {{ old('payment_status') == 'pending' ? 'selected' : '' }}>Pending</option>
                                    <option value="paid" {{ old('payment_status') == 'paid' ? 'selected' : '' }}>Paid</option>
                                    <option value="partially_paid" {{ old('payment_status') == 'partially_paid' ? 'selected' : '' }}>Partially Paid</option>
                                    <option value="refunded" {{ old('payment_status') == 'refunded' ? 'selected' : '' }}>Refunded</option>
                                </select>
                                @error('payment_status')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                @enderror
                            </div>
                        </div>
                    </div>
                    
                    <!-- Special Requests -->
                    <div class="mb-3">
                        <label for="special_requests" class="form-label">Special Requests</label>
                        <textarea class="form-control @error('special_requests') is-invalid @enderror" 
                                  id="special_requests" name="special_requests" rows="3" 
                                  placeholder="Any special requests or notes...">{{ old('special_requests') }}</textarea>
                        @error('special_requests')
                            <div class="invalid-feedback">{{ $message }}</div>
                        @enderror
                    </div>
                    
                    <!-- Submit Buttons -->
                    <div class="d-flex justify-content-end">
                        <button type="submit" class="btn btn-primary me-2" id="submitBtn">
                            <i class="fas fa-save me-2"></i>Create Reservation
                        </button>
                        <a href="{{ route('reservations.index') }}" class="btn btn-outline-secondary">
                            <i class="fas fa-times me-2"></i>Cancel
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/intlTelInput.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2 for guest search
            $('#guest_search').select2({
                placeholder: 'Type to search existing guests...',
                allowClear: true,
                width: '100%',
                templateResult: formatGuest,
                templateSelection: formatGuestSelection
            });

            function formatGuest(guest) {
                if (!guest.id) {
                    return guest.text;
                }
                
                var $guest = $(
                    '<div class="guest-option">' +
                        '<div class="guest-name">' + guest.text + '</div>' +
                        '<div class="guest-details">' +
                            (guest.element.getAttribute('data-email') ? '<span class="guest-email"><i class="fas fa-envelope me-1"></i>' + guest.element.getAttribute('data-email') + '</span>' : '') +
                            (guest.element.getAttribute('data-phone') ? '<span class="guest-phone"><i class="fas fa-phone me-1"></i>' + guest.element.getAttribute('data-phone') + '</span>' : '') +
                        '</div>' +
                    '</div>'
                );
                return $guest;
            }

            function formatGuestSelection(guest) {
                if (!guest.id) {
                    return guest.text;
                }
                return guest.text.split(' - ')[0];
            }

            // Initialize intl-tel-input for phone number with country codes
            const phoneInput = document.querySelector("#new_guest_phone");
            if (phoneInput) {
                const iti = window.intlTelInput(phoneInput, {
                    initialCountry: "ug",
                    preferredCountries: ["ug", "ke", "tz", "us", "gb"],
                    separateDialCode: true,
                    utilsScript: "https://cdnjs.cloudflare.com/ajax/libs/intl-tel-input/17.0.8/js/utils.js",
                    geoIpLookup: function(callback) {
                        $.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
                            var countryCode = (resp && resp.country) ? resp.country : "ug";
                            callback(countryCode.toLowerCase());
                        });
                    },
                    customContainer: "iti-container",
                    dropdownContainer: document.body
                });

                phoneInput.addEventListener('countrychange', function() {
                    const countryData = iti.getSelectedCountryData();
                    $('#phone_country_code').val(countryData.iso2.toUpperCase());
                });

                $('#reservationForm').on('submit', function() {
                    if (iti.isValidNumber()) {
                        const fullNumber = iti.getNumber();
                        $('#new_guest_phone').val(fullNumber);
                    }
                });

                setTimeout(function() {
                    phoneInput.style.paddingLeft = '90px';
                }, 100);
            }

            // Guest option tabs
            $('.guest-option-tab').click(function() {
                const option = $(this).data('option');
                
                $('.guest-option-tab').removeClass('active');
                $(this).addClass('active');
                
                $('.guest-option-content').removeClass('active');
                $(`#${option}GuestSection`).addClass('active');
                
                if (option === 'existing') {
                    $('#new_guest_first_name').val('');
                    $('#new_guest_last_name').val('');
                    $('#new_guest_email').val('');
                    $('#new_guest_phone').val('');
                    $('#new_guest_address').val('');
                    $('#emailWarning').removeClass('show');
                    
                    if (window.intlTelInputGlobals) {
                        const iti = window.intlTelInputGlobals.getInstance(document.querySelector("#new_guest_phone"));
                        if (iti) {
                            iti.setNumber('');
                        }
                    }
                } else {
                    $('#guest_search').val('').trigger('change');
                }
            });

            // Check for duplicate email
            let emailCheckTimeout;
            $('#new_guest_email').on('input', function() {
                clearTimeout(emailCheckTimeout);
                const email = $(this).val().trim();
                
                if (email && isValidEmail(email)) {
                    emailCheckTimeout = setTimeout(() => {
                        checkDuplicateEmail(email);
                    }, 500);
                } else {
                    $('#emailWarning').removeClass('show');
                }
            });

            function isValidEmail(email) {
                const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                return re.test(email);
            }

            function checkDuplicateEmail(email) {
                $.ajax({
                    url: '{{ route("check-guest-email") }}',
                    method: 'POST',
                    data: {
                        email: email,
                        _token: '{{ csrf_token() }}'
                    },
                    success: function(response) {
                        if (response.exists) {
                            $('#warningMessage').text('This email is already registered to an existing guest. You can either use a different email or select the existing guest.');
                            $('#emailWarning').addClass('show');
                        } else {
                            $('#emailWarning').removeClass('show');
                        }
                    },
                    error: function() {
                        console.log('Error checking email');
                    }
                });
            }

            // Switch to existing guest when email duplicate is found
            $('#switchToExisting').click(function() {
                const email = $('#new_guest_email').val().trim();
                
                const $guestSearch = $('#guest_search');
                const $options = $guestSearch.find('option');
                let foundGuestId = null;
                
                $options.each(function() {
                    const guestEmail = $(this).data('email');
                    if (guestEmail === email) {
                        foundGuestId = $(this).val();
                        return false;
                    }
                });
                
                if (foundGuestId) {
                    $guestSearch.val(foundGuestId).trigger('change');
                    $('.guest-option-tab[data-option="existing"]').click();
                }
            });

            // Room selection and price calculation with VAT
            const roomSelect = document.getElementById('room_id');
            const checkInInput = document.getElementById('check_in');
            const checkOutInput = document.getElementById('check_out');
            const totalAmountInput = document.getElementById('total_amount');
            const paidAmountInput = document.getElementById('paid_amount');
            const paymentStatusSelect = document.getElementById('payment_status');
            const form = document.getElementById('reservationForm');
            const submitBtn = document.getElementById('submitBtn');
            const vatRate = parseFloat(document.getElementById('vat_rate').value) || 18;

            // Display elements
            const displayRoomPrice = document.getElementById('display_room_price');
            const displayNights = document.getElementById('display_nights');
            const displayRoomCharges = document.getElementById('display_room_charges');
            const displayVat = document.getElementById('display_vat');
            const displayTotalWithVat = document.getElementById('display_total_with_vat');
            const displayPaidAmount = document.getElementById('display_paid_amount');
            const displayBalance = document.getElementById('display_balance');
            const balanceStatus = document.getElementById('balance_status');

            // Hidden fields for calculations
            const calculatedNights = document.getElementById('calculated_nights');
            const calculatedRoomCharges = document.getElementById('calculated_room_charges');
            const calculatedVat = document.getElementById('calculated_vat');

            // Set minimum date for check-in to today
            const today = new Date().toISOString().split('T')[0];
            checkInInput.min = today;

            // Calculate total amount when dates or room change
            function calculateTotalAmount() {
                console.log('Calculating total amount...'); // Debug log
                console.log('Room selected:', roomSelect.value);
                console.log('Check-in:', checkInInput.value);
                console.log('Check-out:', checkOutInput.value);
                
                if (roomSelect.value && checkInInput.value && checkOutInput.value) {
                    const selectedOption = roomSelect.options[roomSelect.selectedIndex];
                    const roomPrice = parseFloat(selectedOption.getAttribute('data-price'));
                    
                    console.log('Room price:', roomPrice);
                    
                    const checkIn = new Date(checkInInput.value);
                    const checkOut = new Date(checkOutInput.value);
                    
                    // Calculate number of nights
                    const timeDiff = checkOut.getTime() - checkIn.getTime();
                    const nights = Math.ceil(timeDiff / (1000 * 3600 * 24));
                    
                    console.log('Nights:', nights);
                    
                    if (nights > 0 && !isNaN(roomPrice)) {
                        const roomCharges = roomPrice * nights;
                        const vatAmount = roomCharges * vatRate / 100;
                        const totalWithVat = roomCharges + vatAmount;
                        
                        // Update display elements
                        displayRoomPrice.textContent = 'UGX ' + roomPrice.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                        displayNights.textContent = nights;
                        displayRoomCharges.textContent = 'UGX ' + roomCharges.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                        displayVat.textContent = 'UGX ' + vatAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                        displayTotalWithVat.textContent = 'UGX ' + totalWithVat.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                        
                        // Update hidden fields
                        calculatedNights.value = nights;
                        calculatedRoomCharges.value = roomCharges.toFixed(2);
                        calculatedVat.value = vatAmount.toFixed(2);
                        
                        // Update total amount input
                        totalAmountInput.value = totalWithVat.toFixed(2);
                        
                        // Update payment status based on paid amount
                        updatePaymentStatus();
                    }
                } else {
                    // Reset display if incomplete
                    displayRoomPrice.textContent = 'UGX 0';
                    displayNights.textContent = '0';
                    displayRoomCharges.textContent = 'UGX 0';
                    displayVat.textContent = 'UGX 0';
                    displayTotalWithVat.textContent = 'UGX 0';
                    totalAmountInput.value = '';
                }
            }

            // Update payment status based on paid amount
            function updatePaymentStatus() {
                const totalAmount = parseFloat(totalAmountInput.value) || 0;
                const paidAmount = parseFloat(paidAmountInput.value) || 0;
                
                displayPaidAmount.textContent = 'UGX ' + paidAmount.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                
                if (totalAmount > 0) {
                    const balance = totalAmount - paidAmount;
                    displayBalance.textContent = 'UGX ' + balance.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                    
                    if (balance <= 0) {
                        displayBalance.className = 'fw-bold balance-zero';
                        balanceStatus.textContent = '✓ Fully paid';
                        balanceStatus.className = 'text-success';
                        if (paymentStatusSelect) paymentStatusSelect.value = 'paid';
                    } else if (paidAmount > 0) {
                        displayBalance.className = 'fw-bold balance-positive';
                        balanceStatus.textContent = '⚠ Partially paid - Balance: UGX ' + balance.toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
                        balanceStatus.className = 'text-warning';
                        if (paymentStatusSelect) paymentStatusSelect.value = 'partially_paid';
                    } else {
                        displayBalance.className = 'fw-bold balance-positive';
                        balanceStatus.textContent = '✗ No payment yet';
                        balanceStatus.className = 'text-danger';
                        if (paymentStatusSelect) paymentStatusSelect.value = 'pending';
                    }
                }
            }

            // Set minimum date for check-out to be after check-in
            checkInInput.addEventListener('change', function() {
                checkOutInput.min = this.value;
                if (checkOutInput.value && checkOutInput.value < this.value) {
                    checkOutInput.value = '';
                }
                calculateTotalAmount();
            });

            checkOutInput.addEventListener('change', calculateTotalAmount);
            roomSelect.addEventListener('change', calculateTotalAmount);
            paidAmountInput.addEventListener('input', updatePaymentStatus);

            // FIX: Add event listener for Select2 change to trigger calculation
            $('#guest_search').on('select2:select', function(e) {
                console.log('Guest selected, ensuring calculation works...');
                // The calculation doesn't depend on guest, but we can log to confirm
                calculateTotalAmount();
            });

            // FIX: Ensure calculation works when switching tabs
            $('.guest-option-tab').on('click', function() {
                console.log('Tab switched, ensuring calculation works...');
                // Small timeout to allow DOM to update
                setTimeout(function() {
                    calculateTotalAmount();
                }, 100);
            });

            // FIX: Check if there are existing values in the form (from old input)
            if (roomSelect.value && checkInInput.value && checkOutInput.value) {
                console.log('Found existing values, calculating...');
                calculateTotalAmount();
            }

            // Form submission validation
            form.addEventListener('submit', function(e) {
                // Validate guest selection
                const guestSearch = $('#guest_search').val();
                const isNewGuestTab = $('.guest-option-tab[data-option="new"]').hasClass('active');
                
                if (!guestSearch && !isNewGuestTab) {
                    e.preventDefault();
                    alert('Please select an existing guest or add a new guest.');
                    return;
                }

                if (isNewGuestTab) {
                    const firstName = $('#new_guest_first_name').val().trim();
                    const lastName = $('#new_guest_last_name').val().trim();
                    
                    if (!firstName || !lastName) {
                        e.preventDefault();
                        alert('Please fill in at least first name and last name for the new guest.');
                        return;
                    }
                    
                    const email = $('#new_guest_email').val().trim();
                    if (email && $('#emailWarning').hasClass('show')) {
                        e.preventDefault();
                        alert('This email is already registered. Please use a different email or select the existing guest from the dropdown.');
                        return;
                    }

                    const phoneInput = document.querySelector("#new_guest_phone");
                    if (phoneInput && phoneInput.value.trim() !== '') {
                        const iti = window.intlTelInputGlobals.getInstance(phoneInput);
                        if (iti && !iti.isValidNumber()) {
                            e.preventDefault();
                            alert('Please enter a valid phone number with country code.');
                            return;
                        }
                    }
                }

                const totalAmount = parseFloat(totalAmountInput.value);
                if (!totalAmount || totalAmount <= 0) {
                    e.preventDefault();
                    alert('Please select a room and dates to calculate the total amount.');
                    return;
                }

                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i>Creating...';
            });

            // Initialize calculation if values are already present
            calculateTotalAmount();

            // Initialize based on form errors or old data
            @if(old('new_guest_first_name') || old('new_guest_last_name') || old('new_guest_email'))
                $('.guest-option-tab[data-option="new"]').click();
            @endif

            @if(old('guest_id'))
                $('.guest-option-tab[data-option="existing"]').click();
                // Make sure Select2 has the value selected
                $('#guest_search').val('{{ old("guest_id") }}').trigger('change');
            @endif

            // Auto-show new guest section if guest data is pre-filled
            @if(old('new_guest_first_name', '') === 'NABWAMI' || old('new_guest_last_name', '') === 'IMMY')
                $('.guest-option-tab[data-option="new"]').click();
            @endif

            // Initialize paid amount display
            updatePaymentStatus();
        });
    </script>
    
<script src="{{ asset('js/theme-applier.js') }}"></script>
</body>
</html>

