@extends('layouts.app-shell')
@section('bottomnav')
    <a href="{{ route('partner.dashboard') }}"><span class="ic">📊</span><span>Home</span></a>
    <a href="{{ route('partner.bookings') }}" class="active"><span class="ic">📋</span><span>Bookings</span></a>
    <a href="{{ route('partner.schedule') }}"><span class="ic">📅</span><span>Schedule</span></a>
    <a href="{{ route('partner.team') }}"><span class="ic">👥</span><span>Team</span></a>
    <a href="{{ route('partner.profile') }}"><span class="ic">👤</span><span>Profile</span></a>
@endsection
@section('title', 'New booking')
@section('sidebar')
    <a href="{{ route('partner.dashboard') }}"><span class="ic">📊</span> Dashboard</a>
    <a href="{{ route('partner.bookings') }}" class="active"><span class="ic">📋</span> My bookings</a>
    <a href="{{ route('partner.schedule') }}"><span class="ic">📅</span> Schedule</a>
    <a href="{{ route('partner.attendance') }}"><span class="ic">📍</span> Attendance</a>
    <a href="{{ route('partner.leaves') }}"><span class="ic">🏖</span> Leaves</a>
    <a href="{{ route('partner.team') }}"><span class="ic">👥</span> My team</a>
    <a href="{{ route('partner.earnings') }}"><span class="ic">💰</span> Earnings</a>
    <a href="{{ route('partner.profile') }}"><span class="ic">👤</span> Profile</a>
    <a href="{{ route('logout') }}" onclick="event.preventDefault(); document.getElementById('lo').submit()"><span class="ic">⤴</span> Logout</a>
    <form id="lo" method="POST" action="{{ route('logout') }}" style="display:none">@csrf</form>
@endsection
@section('content')

@php
    $defaultDate = request('date', now()->addDay()->format('Y-m-d'));
@endphp

<div class="flex-between mb-3">
    <div>
        <a href="{{ route('partner.bookings') }}" class="btn btn-ghost btn-sm">← All bookings</a>
        <h2 style="font-size: 24px; font-weight: 700; margin-top: 8px;">New booking</h2>
        <p class="muted" style="font-size: 13px;">Create a new subscription. Daily visits will be auto-scheduled.</p>
    </div>
</div>

@if($errors->any())
    <div class="alert alert-error" style="max-width: 920px; margin-bottom: 18px;">
        <ul style="margin: 0 0 0 16px;">@foreach($errors->all() as $err)<li>{{ $err }}</li>@endforeach</ul>
    </div>
@endif

<form method="POST" action="{{ route('partner.bookings.create') }}" style="max-width: 920px;">
    @csrf

    <div class="panel">
        <div class="form-section">
            <div class="ic"><x-icon name="profile" :size="14" /></div>
            <h4>1. Customer</h4>
            <span class="sub">Who is the booking for?</span>
        </div>
        <div class="field">
            <label>Select customer</label>
            <select name="customer_id" id="customerSelect" required>
                <option value="">— Pick a customer —</option>
                @foreach($customers as $c)
                    <option value="{{ $c->id }}" data-name="{{ $c->name }}" data-phone="{{ $c->phone }}" data-address="{{ $c->address }}" data-lat="{{ $c->lat }}" data-lng="{{ $c->lng }}" @selected(old('customer_id') == $c->id)>
                        {{ $c->name }} · {{ $c->phone ?: 'no phone' }}
                    </option>
                @endforeach
            </select>
            @if($customers->isEmpty())
                <span class="hint">No customers yet. They need to sign up at the Befikreyy site first.</span>
            @endif
        </div>
    </div>

    <div class="panel">
        <div class="form-section">
            <div class="ic"><x-icon name="services" :size="14" /></div>
            <h4>2. Service</h4>
            <span class="sub">Only services you are approved for</span>
        </div>
        <div class="field">
            <label>Choose service</label>
            <select name="service_id" id="serviceSelect" required>
                <option value="">— Pick a service —</option>
                @foreach($partnerServices as $s)
                    <option value="{{ $s->id }}" data-price="{{ $s->price_paise }}" data-duration="{{ $s->duration_minutes }}" @selected(old('service_id') == $s->id)>
                        {{ $s->name }} · ₹{{ number_format($s->price_paise / 100, 0) }}/visit
                    </option>
                @endforeach
            </select>
            @if($partnerServices->isEmpty())
                <span class="hint">You are not approved for any services yet. Ask admin to add services to your profile.</span>
            @endif
        </div>
    </div>

    <div class="panel">
        <div class="form-section">
            <div class="ic"><x-icon name="calendar" :size="14" /></div>
            <h4>3. Schedule</h4>
            <span class="sub">Start date, time slot and frequency</span>
        </div>
        <div class="form-grid">
            <div class="field">
                <label>Start date</label>
                <input type="date" name="scheduled_date" value="{{ old('scheduled_date', $defaultDate) }}" required min="{{ now()->format('Y-m-d') }}">
            </div>
            <div class="field">
                <label>Time slot</label>
                <select name="scheduled_slot" required>
                    @foreach(['09:00 AM - 10:00 AM','10:00 AM - 11:00 AM','11:00 AM - 12:00 PM','12:00 PM - 01:00 PM','02:00 PM - 03:00 PM','03:00 PM - 04:00 PM','04:00 PM - 05:00 PM','05:00 PM - 06:00 PM'] as $slot)
                        <option value="{{ $slot }}" @selected(old('scheduled_slot', '10:00 AM - 11:00 AM') === $slot)>{{ $slot }}</option>
                    @endforeach
                </select>
            </div>
            <div class="field">
                <label>Visits in 30-day cycle</label>
                <input type="number" name="visits_per_period" id="visitsPerPeriod" value="{{ old('visits_per_period', 26) }}" min="1" max="60" required>
                <span class="hint">Daily service: ~26 (skip Sundays) · 3x/week: 12 · Weekly: 4</span>
            </div>
        </div>
    </div>

    <div class="panel">
        <div class="form-section">
            <div class="ic"><x-icon name="pin" :size="14" /></div>
            <h4>4. Location</h4>
            <span class="sub">Where should you visit?</span>
        </div>
        <div class="form-grid">
            <div class="field">
                <label>Service area</label>
                <select name="area_id" id="areaSelect">
                    <option value="">— Pick an area —</option>
                    @foreach($areas as $a)
                        <option value="{{ $a->id }}" @selected(old('area_id') == $a->id)>{{ $a->name }} · {{ $a->city }}</option>
                    @endforeach
                </select>
            </div>
            <div class="field">
                <label>Pincode</label>
                <input name="pincode" id="pinInput" value="{{ old('pincode') }}" maxlength="6" inputmode="numeric">
            </div>
            <div class="field full">
                <label>Full address <span class="req">*</span></label>
                <textarea name="address" id="addrInput" required rows="3" placeholder="Flat, tower, building, street">{{ old('address') }}</textarea>
            </div>
            <div class="field">
                <label>Latitude</label>
                <input type="number" step="0.000001" name="lat" id="latInput" value="{{ old('lat') }}" placeholder="28.5167">
            </div>
            <div class="field">
                <label>Longitude</label>
                <input type="number" step="0.000001" name="lng" id="lngInput" value="{{ old('lng') }}" placeholder="77.4119">
            </div>
        </div>
    </div>

    <div class="panel">
        <div class="form-section">
            <div class="ic"><x-icon name="money" :size="14" /></div>
            <h4>5. Pricing</h4>
            <span class="sub">Monthly billing</span>
        </div>
        <div class="form-grid">
            <div class="field">
                <label>Amount (₹)</label>
                <input type="number" name="amount_paise" id="amtInput" value="{{ old('amount_paise', 150000) }}" required min="0">
                <span class="hint">Pre-tax monthly fee in paise (₹1500 = 150000).</span>
            </div>
            <div class="field">
                <label>Tax (₹)</label>
                <input type="number" name="tax_paise" id="taxInput" value="{{ old('tax_paise', 7500) }}" min="0">
            </div>
            <div class="field">
                <label>Total per month (₹)</label>
                <input type="number" name="total_paise" id="totalInput" value="{{ old('total_paise', 157500) }}" required readonly>
                <span class="hint">Auto-calculated.</span>
            </div>
        </div>
    </div>

    <div class="panel">
        <div class="form-section">
            <div class="ic"><x-icon name="info" :size="14" /></div>
            <h4>6. Notes</h4>
            <span class="sub">Internal notes (not shown to customer)</span>
        </div>
        <div class="field">
            <label>Notes</label>
            <textarea name="notes" rows="3" placeholder="Anything specific about this booking">{{ old('notes') }}</textarea>
        </div>
        <div class="field">
            <label class="pill-toggle">
                <input type="checkbox" name="auto_renew" value="1" @checked(old('auto_renew', true))>
                <span class="sw"></span>
                <span class="lbl">Auto-renew this subscription</span>
            </label>
        </div>
    </div>

    <div class="flex" style="gap: 10px;">
        <button class="btn btn-primary" type="submit"><x-icon name="check" :size="14" /> Create booking with <span id="visitCount">26</span> visits</button>
        <a href="{{ route('partner.bookings') }}" class="btn btn-outline">Cancel</a>
    </div>
</form>

<script>
document.getElementById('customerSelect')?.addEventListener('change', function() {
    const opt = this.options[this.selectedIndex];
    if (!opt || !opt.dataset.name) return;
    document.getElementById('addrInput').value = opt.dataset.address || '';
    document.getElementById('latInput').value = opt.dataset.lat || '';
    document.getElementById('lngInput').value = opt.dataset.lng || '';
});
document.getElementById('serviceSelect')?.addEventListener('change', function() {
    const opt = this.options[this.selectedIndex];
    if (!opt || !opt.dataset.price) return;
    const pricePaise = parseInt(opt.dataset.price);
    const monthly = Math.round(pricePaise * 26 / 100) * 100;
    const tax = Math.round(monthly * 0.05);
    document.getElementById('amtInput').value = monthly;
    document.getElementById('taxInput').value = tax;
    document.getElementById('totalInput').value = monthly + tax;
});
function recalcTotal() {
    const amt = parseInt(document.getElementById('amtInput').value || 0);
    const tax = parseInt(document.getElementById('taxInput').value || 0);
    document.getElementById('totalInput').value = amt + tax;
}
document.getElementById('amtInput')?.addEventListener('input', recalcTotal);
document.getElementById('taxInput')?.addEventListener('input', recalcTotal);
document.getElementById('visitsPerPeriod')?.addEventListener('input', function() {
    document.getElementById('visitCount').textContent = this.value || 0;
});
</script>
@endsection