<?php
/**
 * @var array $services
 * @var array $employees
 * @var string $selectedCustomerId
 */
?>
<div class="page-title mb-4">
    <h5><i class="fas fa-calendar-plus me-2 text-gold"></i>New Appointment</h5>
</div>

<div class="glass-card p-0">
    <div class="card-header">
        <div class="card-header-left">
            <i class="fas fa-calendar-check card-icon"></i>
            <h6 class="card-title">Booking Details</h6>
        </div>
        <div>
            <span class="text-muted small"><span class="text-danger">*</span> Required fields</span>
        </div>
    </div>
    <div class="card-body">
        <form method="POST" action="<?= url('appointments/store') ?>" id="appointmentForm">
            <?= csrf_field() ?>

            <div class="row g-3">
                <div class="col-md-6">
                    <div class="mb-3">
                        <label class="form-label">Customer <span class="text-danger">*</span></label>
                        <div class="input-group">
                            <input type="text" id="customerSearch" class="form-control bg-transparent"
                                   placeholder="Search customer by name or phone..."
                                   autocomplete="off">
                            <input type="hidden" name="customer_id" id="customer_id"
                                   value="<?= e(old('customer_id', $selectedCustomerId)) ?>">
                            <button type="button" class="btn btn-outline-gold" id="clearCustomer">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div id="customerSearchResults" class="search-results-container mt-1"></div>
                        <div id="selectedCustomerInfo" class="mt-2 d-none">
                            <div class="glass-card p-2">
                                <strong id="selectedCustomerName"></strong>
                                <br><small class="text-muted" id="selectedCustomerContact"></small>
                            </div>
                        </div>
                        <?= errorMsg('customer_id') ?>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Date <span class="text-danger">*</span></label>
                        <input type="date" name="date" id="appointmentDate"
                               class="form-control bg-transparent <?= errorClass('start_datetime') ?>"
                               value="<?= e(old('date', date('Y-m-d'))) ?>" required>
                        <?= errorMsg('start_datetime') ?>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="mb-3">
                        <label class="form-label">Time <span class="text-danger">*</span></label>
                        <input type="time" name="time" id="appointmentTime"
                               class="form-control bg-transparent"
                               value="<?= e(old('time', date('H:i'))) ?>" required>
                    </div>
                </div>
            </div>

            <div class="row g-3">
                <div class="col-md-12">
                    <div class="mb-3">
                        <label class="form-label">Notes</label>
                        <textarea name="notes" class="form-control bg-transparent <?= errorClass('notes') ?>"
                                  rows="2" maxlength="2000"><?= e(old('notes')) ?></textarea>
                        <?= errorMsg('notes') ?>
                    </div>
                </div>
            </div>

            <hr class="border-secondary">
            <h6 class="text-gold mb-3"><i class="fas fa-concierge-bell me-2"></i>Services</h6>

            <div id="servicesContainer">
                <div class="service-row glass-card p-3 mb-3">
                    <div class="row g-2 align-items-end">
                        <div class="col-md-5">
                            <label class="form-label small">Service <span class="text-danger">*</span></label>
                            <select name="services[0][service_id]" class="form-select form-select-sm bg-transparent service-select" required>
                                <option value="">Select Service</option>
                                <?php foreach ($services as $svc): ?>
                                    <option value="<?= $svc->id ?>"
                                            data-duration="<?= (int)$svc->duration_minutes ?>"
                                            data-price="<?= $svc->price ?>">
                                        <?= e($svc->name) ?> (<?= (int)$svc->duration_minutes ?>min - <?= currency($svc->price) ?>)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label small">Employee</label>
                            <select name="services[0][employee_id]" class="form-select form-select-sm bg-transparent employee-select">
                                <option value="">Auto Assign</option>
                                <?php foreach ($employees as $emp): ?>
                                    <option value="<?= $emp->id ?>"><?= e($emp->first_name . ' ' . $emp->last_name) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label small">Duration</label>
                            <input type="text" class="form-control form-control-sm bg-transparent service-duration" readonly value="0 min">
                        </div>
                        <div class="col-md-1 text-end">
                            <button type="button" class="btn btn-sm btn-outline-danger remove-service d-none" title="Remove">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <button type="button" class="btn btn-sm btn-outline-gold mb-3" id="addServiceRow">
                <i class="fas fa-plus me-1"></i>Add Another Service
            </button>

            <div class="glass-card p-3 mb-3">
                <div class="row g-2">
                    <div class="col-md-4">
                        <span class="text-muted small">Total Duration:</span>
                        <strong id="totalDuration">0 min</strong>
                    </div>
                    <div class="col-md-4">
                        <span class="text-muted small">Total Price:</span>
                        <strong id="totalPrice" class="text-gold"><?= currency(0) ?></strong>
                    </div>
                    <div class="col-md-4 text-end">
                        <input type="hidden" name="start_datetime" id="start_datetime">
                        <input type="hidden" name="end_datetime" id="end_datetime">
                    </div>
                </div>
            </div>

            <div class="mt-4 d-flex gap-2">
                <button type="submit" class="btn btn-gold">
                    <i class="fas fa-save me-1"></i>Create Appointment
                </button>
                <a href="<?= url('appointments') ?>" class="btn btn-outline-secondary">
                    <i class="fas fa-times me-1"></i>Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<?php
ob_start();
?>
const baseUrl = '___BASEURL___';
let serviceIndex = 1;

function updateTotal() {
    let totalDuration = 0;
    let totalPrice = 0;
    $('.service-row').each(function() {
        const select = $(this).find('.service-select option:selected');
        if (select.val()) {
            totalDuration += parseInt(select.data('duration')) || 0;
            totalPrice += parseFloat(select.data('price')) || 0;
        }
    });
    $('#totalDuration').text(totalDuration + ' min');
    $('#totalPrice').text('___CURRENCY___' + totalPrice.toFixed(2));

    const date = $('#appointmentDate').val();
    const time = $('#appointmentTime').val();
    if (date && time) {
        const start = date + ' ' + time + ':00';
        const startDate = new Date(date + 'T' + time);
        const endDate = new Date(startDate.getTime() + totalDuration * 60000);
        const endTime = endDate.toTimeString().slice(0, 5);
        const end = date + ' ' + endTime + ':00';
        $('#start_datetime').val(start);
        $('#end_datetime').val(end);
    }
}

$(document).on('change', '.service-select', function() {
    const option = $(this).find('option:selected');
    const row = $(this).closest('.service-row');
    row.find('.service-duration').val((option.data('duration') || 0) + ' min');
    updateTotal();
});

$('#appointmentDate, #appointmentTime').change(function() {
    updateTotal();
});

$('#addServiceRow').click(function() {
    const newRow = $('.service-row:first').clone();
    newRow.find('select').each(function() {
        const name = $(this).attr('name');
        $(this).attr('name', name.replace(/\[\d+\]/g, '[' + serviceIndex + ']'));
        $(this).val('');
    });
    newRow.find('.service-duration').val('0 min');
    newRow.find('.remove-service').removeClass('d-none');
    newRow.find('input, select').val('');
    $('#servicesContainer').append(newRow);
    serviceIndex++;
});

$(document).on('click', '.remove-service', function() {
    if ($('.service-row').length > 1) {
        $(this).closest('.service-row').remove();
        updateTotal();
    }
});

let searchTimeout = null;
$('#customerSearch').on('input', function() {
    clearTimeout(searchTimeout);
    const q = $(this).val();
    if (q.length < 2) {
        $('#customerSearchResults').empty();
        return;
    }
    searchTimeout = setTimeout(function() {
        $.get(baseUrl + '/customers/search', { q: q }, function(res) {
            if (res.success && res.data.length) {
                let html = '<div class="list-group">';
                res.data.forEach(function(c) {
                    html += '<a href="#" class="list-group-item list-group-item-action bg-dark border-gold customer-result" data-id="' + c.id + '" data-name="' + eescape(c.first_name + ' ' + c.last_name) + '" data-contact="' + (c.email || c.phone || '') + '">';
                    html += '<strong>' + eescape(c.first_name + ' ' + c.last_name) + '</strong>';
                    if (c.email) html += '<br><small>' + eescape(c.email) + '</small>';
                    if (c.phone) html += '<br><small>' + eescape(c.phone) + '</small>';
                    html += '</a>';
                });
                html += '</div>';
                $('#customerSearchResults').html(html);
            } else {
                $('#customerSearchResults').html('<div class="text-muted small py-2">No customers found</div>');
            }
        });
    }, 300);
});

function eescape(str) {
    return $('<span>').text(str).html();
}

$(document).on('click', '.customer-result', function(e) {
    e.preventDefault();
    const id = $(this).data('id');
    const name = $(this).data('name');
    const contact = $(this).data('contact');
    $('#customer_id').val(id);
    $('#customerSearch').val(name);
    $('#selectedCustomerName').text(name);
    $('#selectedCustomerContact').text(contact);
    $('#selectedCustomerInfo').removeClass('d-none');
    $('#customerSearchResults').empty();
});

$('#clearCustomer').click(function() {
    $('#customer_id').val('');
    $('#customerSearch').val('');
    $('#selectedCustomerInfo').addClass('d-none');
    $('#customerSearchResults').empty();
});

<?php if (!empty($selectedCustomerId)): ?>
$.get(baseUrl + '/customers/search', { q: '' + <?= (int)$selectedCustomerId ?> }, function(res) {
});
<?php endif; ?>

updateTotal();
<?php
$inlineScripts = ob_get_clean();
$inlineScripts = str_replace('___BASEURL___', rtrim(APP_URL, '/'), $inlineScripts);
$inlineScripts = str_replace('___CURRENCY___', APP_CURRENCY_SYMBOL . ' ', $inlineScripts);
?>
