<?php
/**
 * Admin Booking Detail Page — 8-Tab Layout
 *
 * Tabs: Manage Booking | Booking Details | Email Customer | Email Logs | Notes | SMS Logs | Payment Details | Contract | Invoice
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

// ─── Helper: status badge ───
if ( ! function_exists( 'wahrb_admin_detail_status_badge' ) ) {
    /**
     * Render a status badge.
     *
     * @param string $status Status key.
     * @return string HTML
     */
    function wahrb_admin_detail_status_badge( string $status ): string {
        $map = [
            'pending'     => ['#ed6c02', __('Pending', 'wahra-rentals-bookings')],
            'confirmed'   => ['#2e7d32', __('Confirmed', 'wahra-rentals-bookings')],
            'checked_in'  => ['#1976d2', __('In Progress', 'wahra-rentals-bookings')],
            'checked_out' => ['#9c27b0', __('Returned', 'wahra-rentals-bookings')],
            'completed'   => ['#388e3c', __('Completed', 'wahra-rentals-bookings')],
            'cancelled'   => ['#d32f2f', __('Cancelled', 'wahra-rentals-bookings')],
            'refunded'    => ['#757575', __('Refunded', 'wahra-rentals-bookings')],
            'failed'      => ['#b71c1c', __('Failed', 'wahra-rentals-bookings')],
        ];
        $color = $map[$status][0] ?? '#666';
        $label = $map[$status][1] ?? ucfirst($status);
        return '<span style="display:inline-block;padding:3px 10px;border-radius:4px;background:' . esc_attr($color) . ';color:#fff;font-size:.85em;">' . esc_html($label) . '</span>';
    }
}

if ( ! function_exists( 'wahrb_admin_detail_payment_badge' ) ) {
    /**
     * Render a payment status badge (lighter style).
     *
     * @param string $status Payment status key.
     * @return string HTML
     */
    function wahrb_admin_detail_payment_badge( string $status ): string {
        $map = [
            'not_due'           => ['#94a3b8', __('Not Due', 'wahra-rentals-bookings')],
            'pending'           => ['#f59e0b', __('Pending', 'wahra-rentals-bookings')],
            'paid'              => ['#22c55e', __('Paid', 'wahra-rentals-bookings')],
            'failed'            => ['#ef4444', __('Failed', 'wahra-rentals-bookings')],
            'refunded'          => ['#6366f1', __('Refunded', 'wahra-rentals-bookings')],
            'partial'           => ['#f97316', __('Partial', 'wahra-rentals-bookings')],
            'authorized'        => ['#3b82f6', __('Authorized', 'wahra-rentals-bookings')],
            'captured'          => ['#22c55e', __('Captured', 'wahra-rentals-bookings')],
            'released'          => ['#10b981', __('Released', 'wahra-rentals-bookings')],
            'forfeited'         => ['#dc2626', __('Forfeited', 'wahra-rentals-bookings')],
            'partial_forfeited' => ['#ea580c', __('Partial Forfeited', 'wahra-rentals-bookings')],
        ];
        $color = $map[$status][0] ?? '#94a3b8';
        $label = $map[$status][1] ?? ucfirst(str_replace('_', ' ', $status));
        return '<span style="display:inline-block;padding:2px 8px;border-radius:12px;background:' . esc_attr($color) . '22;color:' . esc_attr($color) . ';font-size:.8em;font-weight:600;border:1px solid ' . esc_attr($color) . '44;">' . esc_html($label) . '</span>';
    }
}

// ─── Load booking ───
global $wpdb;
$db = WAHRB_Database::instance();

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational parameter
$booking_id = isset($_GET['booking_id']) ? absint(wp_unslash($_GET['booking_id'])) : 0;
if ( ! $booking_id ) {
    echo '<div class="wrap"><div class="notice notice-error"><p>' . esc_html__('No booking ID provided.', 'wahra-rentals-bookings') . '</p></div></div>';
    return;
}

$booking = new WAHRB_Booking($booking_id);
if ( ! $booking->exists() ) {
    echo '<div class="wrap"><div class="notice notice-error"><p>' . esc_html__('Booking not found.', 'wahra-rentals-bookings') . '</p></div></div>';
    return;
}

$bdata = $booking->get_data();

// Payment schedule
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$payment = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$db->table('payment_schedule')} WHERE booking_id = %d", $booking_id), ARRAY_A) ?: [];

// Product info
$product_name = '';
if ( ! empty($bdata['product_id']) ) {
    $prod = wc_get_product($bdata['product_id']);
    $product_name = $prod ? $prod->get_name() : esc_html__('Product', 'wahra-rentals-bookings') . ' #' . $bdata['product_id'];
}

// Vendor info
$vendor_name = '';
if ( ! empty($bdata['vendor_id']) ) {
    $user = get_user_by('id', $bdata['vendor_id']);
    $vendor_name = $user ? $user->display_name : esc_html__('Vendor', 'wahra-rentals-bookings') . ' #' . $bdata['vendor_id'];
}

// Notes, email logs, sms logs
$notes_handler = WAHRB_Booking_Notes::instance();
$notes = $notes_handler->get_notes($booking_id);
$emailer = WAHRB_Emailer::instance();
$email_logs = $emailer->get_email_logs($booking_id);
$sms_logs = $emailer->get_sms_logs($booking_id);

$currency_symbol = html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, 'UTF-8');

// ─── Form data & coupon meta ───
$form_data  = $booking->get_meta('form_data', null);
$coupon_meta = $booking->get_meta('coupon', null);

// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Navigational tab parameter, no data modification
$active_tab = isset($_GET['tab']) ? sanitize_text_field(wp_unslash($_GET['tab'])) : 'manage';

$tabs = [
    'manage'  => __('Manage Booking', 'wahra-rentals-bookings'),
    'details' => __('Booking Details', 'wahra-rentals-bookings'),
    'email'   => __('Email Customer', 'wahra-rentals-bookings'),
    'emaillog'=> __('Email Logs', 'wahra-rentals-bookings'),
    'notes'   => __('Notes', 'wahra-rentals-bookings'),
    'smslog'  => __('SMS Logs', 'wahra-rentals-bookings'),
    'payment' => __('Payment Details', 'wahra-rentals-bookings'),
    'formdata'=> __('Form Data', 'wahra-rentals-bookings'),
    'contract'=> __('Contract', 'wahra-rentals-bookings'),
    'invoice' => __('Invoice', 'wahra-rentals-bookings'),
];

$back_url = wahrb_get_admin_dashboard_url('bookings');
?>

<div class="wrap wahrb-admin-wrap wahrb-booking-detail-wrap">

    <!-- Header -->
    <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;">
        <a href="<?php echo esc_url($back_url); ?>" style="text-decoration:none;font-size:1.4rem;" title="<?php esc_attr_e('Back to bookings', 'wahra-rentals-bookings'); ?>">&larr;</a>
        <h1 style="margin:0;">
            <?php
            /* translators: %s: booking number */
            printf(esc_html__('Booking #%s', 'wahra-rentals-bookings'), esc_html($bdata['booking_number']));
            ?>
        </h1>
        <?php echo wp_kses_post(wahrb_admin_detail_status_badge($bdata['status'])); ?>
    </div>

    <!-- Tab Navigation -->
    <nav class="nav-tab-wrapper" style="margin-bottom:0;border-bottom:2px solid #c3c4c7;">
        <?php foreach ( $tabs as $slug => $label ) : ?>
            <a href="#"
               class="nav-tab wahrb-detail-tab <?php echo $active_tab === $slug ? 'nav-tab-active' : ''; ?>"
               data-tab="<?php echo esc_attr($slug); ?>"
               style="<?php echo $active_tab === $slug ? '' : ''; ?>">
                <?php echo esc_html($label); ?>
            </a>
        <?php endforeach; ?>
    </nav>

    <!-- ═══════════ TAB: Manage Booking ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-manage" style="<?php echo $active_tab !== 'manage' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
            <!-- Left: Booking summary -->
            <div>
                <h3 style="margin-top:0;"><?php esc_html_e('Booking Summary', 'wahra-rentals-bookings'); ?></h3>
                <table class="form-table" style="margin:0;">
                    <tr><th style="width:140px;"><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></th><td><?php echo esc_html($product_name); ?></td></tr>
                    <tr><th><?php esc_html_e('Vendor', 'wahra-rentals-bookings'); ?></th><td><?php echo esc_html($vendor_name); ?></td></tr>
                    <tr><th><?php esc_html_e('Customer', 'wahra-rentals-bookings'); ?></th><td><?php echo esc_html($bdata['customer_name'] ?? ''); ?><br><small><?php echo esc_html($bdata['customer_email'] ?? ''); ?></small></td></tr>
                    <tr><th><?php esc_html_e('Dates', 'wahra-rentals-bookings'); ?></th><td><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['start_dt']))) . ' &rarr; ' . esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['end_dt']))); ?></td></tr>
                    <tr><th><?php esc_html_e('Quantity', 'wahra-rentals-bookings'); ?></th><td><?php echo esc_html($bdata['qty'] ?? 1); ?></td></tr>
                    <tr><th><?php esc_html_e('Mode', 'wahra-rentals-bookings'); ?></th><td><?php echo esc_html(ucfirst($bdata['booking_mode'] ?? 'day')); ?></td></tr>
                    <tr><th><?php esc_html_e('Total', 'wahra-rentals-bookings'); ?></th><td><strong><?php echo wp_kses_post(wc_price($payment['total_amount'] ?? $bdata['total_amount'] ?? 0)); ?></strong></td></tr>
                </table>
            </div>

            <!-- Right: Status transitions -->
            <div>
                <h3 style="margin-top:0;"><?php esc_html_e('Status Actions', 'wahra-rentals-bookings'); ?></h3>
                <p style="color:#64748b;font-size:13px;"><?php esc_html_e('Transition the booking to the next state.', 'wahra-rentals-bookings'); ?></p>

                <?php
                $status = $bdata['status'];
                $transitions = [];
                if ($status === 'pending') {
                    $transitions = [
                        'confirmed' => __('Confirm', 'wahra-rentals-bookings'),
                        'cancelled' => __('Cancel', 'wahra-rentals-bookings'),
                    ];
                } elseif ($status === 'confirmed') {
                    $transitions = [
                        'checked_in' => __('Check In', 'wahra-rentals-bookings'),
                        'cancelled'  => __('Cancel', 'wahra-rentals-bookings'),
                    ];
                } elseif ($status === 'checked_in') {
                    $transitions = [
                        'checked_out' => __('Mark Returned', 'wahra-rentals-bookings'),
                        'cancelled'   => __('Cancel', 'wahra-rentals-bookings'),
                    ];
                } elseif ($status === 'checked_out') {
                    $transitions = [
                        'completed' => __('Validate & Complete', 'wahra-rentals-bookings'),
                    ];
                }

                if ( ! empty($transitions) ) :
                    foreach ( $transitions as $target => $btn_label ) :
                        $btn_class = $target === 'cancelled' ? 'button' : 'button button-primary';
                        ?>
                        <button type="button"
                                class="<?php echo esc_attr($btn_class); ?> wahrb-admin-transition-btn"
                                data-booking-id="<?php echo esc_attr($booking_id); ?>"
                                data-target-status="<?php echo esc_attr($target); ?>"
                                style="margin-right:8px;margin-bottom:8px;">
                            <?php echo esc_html($btn_label); ?>
                        </button>
                    <?php endforeach;
                else : ?>
                    <p style="color:#94a3b8;font-style:italic;"><?php esc_html_e('No transitions available for this status.', 'wahra-rentals-bookings'); ?></p>
                <?php endif; ?>

                <!-- Quick Notes for restitution -->
                <?php if ($status === 'checked_out') : ?>
                    <div style="margin-top:16px;padding:16px;background:#fffbeb;border:1px solid #fcd34d;border-radius:6px;">
                        <label for="wahrb-restitution-notes" style="font-weight:600;display:block;margin-bottom:6px;"><?php esc_html_e('Restitution Notes', 'wahra-rentals-bookings'); ?></label>
                        <textarea id="wahrb-restitution-notes" rows="3" style="width:100%;" placeholder="<?php esc_attr_e('Condition, damage, etc.', 'wahra-rentals-bookings'); ?>"></textarea>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- ═══════════ TAB: Booking Details ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-details" style="<?php echo $active_tab !== 'details' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">

        <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
            <div>
                <h3 style="margin-top:0;">📋 <?php esc_html_e('Core Information', 'wahra-rentals-bookings'); ?></h3>
                <table class="widefat fixed striped" style="border:none;">
                    <tbody>
                        <tr><td style="font-weight:600;width:180px;"><?php esc_html_e('Booking ID', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($booking_id); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Booking Number', 'wahra-rentals-bookings'); ?></td><td>#<?php echo esc_html($bdata['booking_number']); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Status', 'wahra-rentals-bookings'); ?></td><td><?php echo wp_kses_post(wahrb_admin_detail_status_badge($bdata['status'])); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($product_name); ?> (ID: <?php echo esc_html($bdata['product_id']); ?>)</td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Category', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(ucfirst($bdata['platform_category'] ?? '-')); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Booking Mode', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(ucfirst($bdata['booking_mode'] ?? 'day')); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Created', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['created_at']))); ?></td></tr>
                        <?php if ( ! empty($bdata['updated_at']) ) : ?>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Updated', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['updated_at']))); ?></td></tr>
                        <?php endif; ?>
                        <?php if ( ! empty($bdata['wc_order_id']) ) : ?>
                        <tr><td style="font-weight:600;"><?php esc_html_e('WC Order', 'wahra-rentals-bookings'); ?></td><td><a href="<?php echo esc_url(admin_url('post.php?post=' . intval($bdata['wc_order_id']) . '&action=edit')); ?>">#<?php echo esc_html($bdata['wc_order_id']); ?></a></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <div>
                <h3 style="margin-top:0;">👤 <?php esc_html_e('Customer', 'wahra-rentals-bookings'); ?></h3>
                <table class="widefat fixed striped" style="border:none;">
                    <tbody>
                        <tr><td style="font-weight:600;width:140px;"><?php esc_html_e('Name', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($bdata['customer_name'] ?? '-'); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Email', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($bdata['customer_email'] ?? '-'); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Phone', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($bdata['customer_phone'] ?? '-'); ?></td></tr>
                        <?php if ( ! empty($bdata['customer_id']) ) : ?>
                        <tr><td style="font-weight:600;"><?php esc_html_e('User ID', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($bdata['customer_id']); ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>

                <h3>📅 <?php esc_html_e('Schedule', 'wahra-rentals-bookings'); ?></h3>
                <table class="widefat fixed striped" style="border:none;">
                    <tbody>
                        <tr><td style="font-weight:600;width:140px;"><?php esc_html_e('Start', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['start_dt']))); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('End', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['end_dt']))); ?></td></tr>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Quantity', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($bdata['qty'] ?? 1); ?></td></tr>
                        <?php if ( ! empty($bdata['slot_start']) ) : ?>
                        <tr><td style="font-weight:600;"><?php esc_html_e('Slot', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($bdata['slot_start'] . ' – ' . ($bdata['slot_end'] ?? '')); ?></td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <?php if ( ! empty($bdata['notes_customer']) ) : ?>
        <div style="margin-top:20px;padding:16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;">
            <h4 style="margin:0 0 8px;">💬 <?php esc_html_e('Customer Message', 'wahra-rentals-bookings'); ?></h4>
            <p style="margin:0;font-style:italic;"><?php echo esc_html($bdata['notes_customer']); ?></p>
        </div>
        <?php endif; ?>

        <?php if ( ! empty($bdata['pricing_snapshot']) && is_array($bdata['pricing_snapshot']) ) : ?>
        <div style="margin-top:20px;">
            <h3>💲 <?php esc_html_e('Pricing Snapshot', 'wahra-rentals-bookings'); ?></h3>
            <pre style="background:#f1f5f9;padding:12px;border-radius:6px;overflow:auto;max-height:200px;font-size:12px;"><?php echo esc_html(wp_json_encode($bdata['pricing_snapshot'], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)); ?></pre>
        </div>
        <?php endif; ?>
    </div>

    <!-- ═══════════ TAB: Email Customer ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-email" style="<?php echo $active_tab !== 'email' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">

        <h3 style="margin-top:0;">✉️ <?php esc_html_e('Send Email to Customer', 'wahra-rentals-bookings'); ?></h3>

        <table class="form-table">
            <tr>
                <th><label for="wahrb-email-to"><?php esc_html_e('Recipient', 'wahra-rentals-bookings'); ?></label></th>
                <td><input type="email" id="wahrb-email-to" class="regular-text" value="<?php echo esc_attr($bdata['customer_email'] ?? ''); ?>" /></td>
            </tr>
            <tr>
                <th><label for="wahrb-email-subject"><?php esc_html_e('Subject', 'wahra-rentals-bookings'); ?></label></th>
                <td><input type="text" id="wahrb-email-subject" class="regular-text" value="<?php
                    /* translators: %s: booking number */
                    echo esc_attr(sprintf(__('Regarding your booking #%s', 'wahra-rentals-bookings'), $bdata['booking_number']));
                ?>" /></td>
            </tr>
            <tr>
                <th><label for="wahrb-email-body"><?php esc_html_e('Message', 'wahra-rentals-bookings'); ?></label></th>
                <td><textarea id="wahrb-email-body" rows="8" class="large-text"></textarea></td>
            </tr>
        </table>

        <p>
            <button type="button" id="wahrb-send-email-btn" class="button button-primary" data-booking-id="<?php echo esc_attr($booking_id); ?>">
                <?php esc_html_e('Send Email', 'wahra-rentals-bookings'); ?>
            </button>
            <span id="wahrb-email-status" style="margin-left:12px;"></span>
        </p>
    </div>

    <!-- ═══════════ TAB: Email Logs ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-emaillog" style="<?php echo $active_tab !== 'emaillog' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">

        <h3 style="margin-top:0;">📧 <?php esc_html_e('Email History', 'wahra-rentals-bookings'); ?></h3>

        <?php if ( empty($email_logs) ) : ?>
            <p style="color:#94a3b8;"><?php esc_html_e('No emails have been sent for this booking.', 'wahra-rentals-bookings'); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped" style="margin-top:12px;">
                <thead>
                    <tr>
                        <th style="width:160px;"><?php esc_html_e('Date', 'wahra-rentals-bookings'); ?></th>
                        <th style="width:120px;"><?php esc_html_e('Type', 'wahra-rentals-bookings'); ?></th>
                        <th><?php esc_html_e('Recipient', 'wahra-rentals-bookings'); ?></th>
                        <th><?php esc_html_e('Subject', 'wahra-rentals-bookings'); ?></th>
                        <th style="width:80px;"><?php esc_html_e('Status', 'wahra-rentals-bookings'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $email_logs as $elog ) : ?>
                    <tr>
                        <td><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($elog['sent_at']))); ?></td>
                        <td><?php echo esc_html(ucfirst(str_replace('_', ' ', $elog['email_type'] ?? '-'))); ?></td>
                        <td><?php echo esc_html($elog['recipient']); ?></td>
                        <td><?php echo esc_html($elog['subject']); ?></td>
                        <td>
                            <?php if ( ($elog['status'] ?? '') === 'sent' ) : ?>
                                <span style="color:#22c55e;">✓ <?php esc_html_e('Sent', 'wahra-rentals-bookings'); ?></span>
                            <?php else : ?>
                                <span style="color:#ef4444;">✗ <?php esc_html_e('Failed', 'wahra-rentals-bookings'); ?></span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <!-- ═══════════ TAB: Notes ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-notes" style="<?php echo $active_tab !== 'notes' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">

        <h3 style="margin-top:0;">📝 <?php esc_html_e('Booking Notes', 'wahra-rentals-bookings'); ?></h3>

        <!-- Add Note Form -->
        <div style="margin-bottom:20px;padding:16px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;">
            <textarea id="wahrb-new-note" rows="3" style="width:100%;margin-bottom:8px;" placeholder="<?php esc_attr_e('Add a note…', 'wahra-rentals-bookings'); ?>"></textarea>
            <div style="display:flex;align-items:center;gap:12px;">
                <button type="button" id="wahrb-add-note-btn" class="button button-primary" data-booking-id="<?php echo esc_attr($booking_id); ?>">
                    <?php esc_html_e('Add Note', 'wahra-rentals-bookings'); ?>
                </button>
                <label style="font-size:13px;"><input type="checkbox" id="wahrb-note-private" /> <?php esc_html_e('Private (hidden from customer)', 'wahra-rentals-bookings'); ?></label>
            </div>
        </div>

        <!-- Notes List -->
        <div id="wahrb-notes-list">
            <?php if ( empty($notes) ) : ?>
                <p style="color:#94a3b8;" id="wahrb-no-notes"><?php esc_html_e('No notes yet.', 'wahra-rentals-bookings'); ?></p>
            <?php else : ?>
                <?php foreach ( $notes as $note ) :
                    $author = $note['author_id'] ? get_user_by('id', $note['author_id']) : null;
                    $author_name = $author ? $author->display_name : __('System', 'wahra-rentals-bookings');
                    $type_icons = ['manual' => '✏️', 'system' => '🤖', 'email' => '📧', 'sms' => '📱'];
                    $icon = $type_icons[$note['note_type'] ?? 'manual'] ?? '📌';
                ?>
                <div class="wahrb-note-item" data-note-id="<?php echo esc_attr($note['note_id']); ?>" style="padding:12px 16px;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:8px;<?php echo !empty($note['is_private']) ? 'background:#fefce8;border-color:#fcd34d;' : ''; ?>">
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;">
                        <span style="font-size:13px;color:#64748b;">
                            <?php echo esc_html($icon . ' ' . $author_name); ?>
                            <?php if ( ! empty($note['is_private']) ) : ?>
                                <span style="font-size:11px;color:#d97706;">(<?php esc_html_e('private', 'wahra-rentals-bookings'); ?>)</span>
                            <?php endif; ?>
                            &middot; <?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($note['created_at']))); ?>
                        </span>
                        <?php if ( ($note['note_type'] ?? '') === 'manual' ) : ?>
                        <button type="button" class="button button-small wahrb-delete-note" data-note-id="<?php echo esc_attr($note['note_id']); ?>" data-booking-id="<?php echo esc_attr($booking_id); ?>" title="<?php esc_attr_e('Delete', 'wahra-rentals-bookings'); ?>">&times;</button>
                        <?php endif; ?>
                    </div>
                    <div style="white-space:pre-wrap;"><?php echo esc_html($note['content']); ?></div>
                </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>

    <!-- ═══════════ TAB: SMS Logs ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-smslog" style="<?php echo $active_tab !== 'smslog' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">

        <h3 style="margin-top:0;">📱 <?php esc_html_e('SMS History', 'wahra-rentals-bookings'); ?></h3>

        <?php if ( empty($sms_logs) ) : ?>
            <p style="color:#94a3b8;"><?php esc_html_e('No SMS messages have been sent for this booking.', 'wahra-rentals-bookings'); ?></p>
            <p style="color:#64748b;font-size:13px;"><?php esc_html_e('SMS automation will be available in a future update (Phase 2).', 'wahra-rentals-bookings'); ?></p>
        <?php else : ?>
            <table class="wp-list-table widefat fixed striped" style="margin-top:12px;">
                <thead>
                    <tr>
                        <th style="width:160px;"><?php esc_html_e('Date', 'wahra-rentals-bookings'); ?></th>
                        <th style="width:120px;"><?php esc_html_e('Type', 'wahra-rentals-bookings'); ?></th>
                        <th style="width:140px;"><?php esc_html_e('Phone', 'wahra-rentals-bookings'); ?></th>
                        <th><?php esc_html_e('Message', 'wahra-rentals-bookings'); ?></th>
                        <th style="width:100px;"><?php esc_html_e('Provider', 'wahra-rentals-bookings'); ?></th>
                        <th style="width:80px;"><?php esc_html_e('Status', 'wahra-rentals-bookings'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ( $sms_logs as $slog ) : ?>
                    <tr>
                        <td><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($slog['sent_at']))); ?></td>
                        <td><?php echo esc_html(ucfirst(str_replace('_', ' ', $slog['sms_type'] ?? '-'))); ?></td>
                        <td><?php echo esc_html($slog['phone']); ?></td>
                        <td style="max-width:300px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?php echo esc_html($slog['message']); ?></td>
                        <td><?php echo esc_html(ucfirst($slog['provider'] ?? '-')); ?></td>
                        <td>
                            <?php
                            $sms_color = ['sent' => '#22c55e', 'delivered' => '#16a34a', 'failed' => '#ef4444', 'queued' => '#f59e0b'];
                            $sc = $sms_color[$slog['status'] ?? ''] ?? '#94a3b8';
                            ?>
                            <span style="color:<?php echo esc_attr($sc); ?>;font-weight:600;"><?php echo esc_html(ucfirst($slog['status'] ?? '-')); ?></span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <!-- ═══════════ TAB: Payment Details ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-payment" style="<?php echo $active_tab !== 'payment' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">

        <h3 style="margin-top:0;">💰 <?php esc_html_e('Payment Details', 'wahra-rentals-bookings'); ?></h3>

        <?php if ( empty($payment) ) : ?>
            <p style="color:#94a3b8;"><?php esc_html_e('No payment schedule found for this booking.', 'wahra-rentals-bookings'); ?></p>
        <?php else : ?>
        <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px;margin-bottom:24px;">
            <!-- Deposit Card -->
            <div style="padding:20px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
                <div style="font-size:13px;color:#64748b;margin-bottom:4px;"><?php esc_html_e('Deposit', 'wahra-rentals-bookings'); ?></div>
                <div style="font-size:1.5rem;font-weight:700;margin-bottom:8px;"><?php echo wp_kses_post(wc_price($payment['deposit_amount_final'] ?? 0)); ?></div>
                <?php echo wp_kses_post(wahrb_admin_detail_payment_badge($payment['deposit_status'] ?? 'not_due')); ?>
                <?php if ( ! empty($payment['deposit_paid_at']) ) : ?>
                    <div style="font-size:12px;color:#94a3b8;margin-top:6px;"><?php esc_html_e('Paid:', 'wahra-rentals-bookings'); ?> <?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($payment['deposit_paid_at']))); ?></div>
                <?php endif; ?>
            </div>
            <!-- Security Deposit Card -->
            <div style="padding:20px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
                <div style="font-size:13px;color:#64748b;margin-bottom:4px;"><?php esc_html_e('Security Deposit', 'wahra-rentals-bookings'); ?></div>
                <div style="font-size:1.5rem;font-weight:700;margin-bottom:8px;"><?php echo wp_kses_post(wc_price($payment['security_deposit_amount_final'] ?? 0)); ?></div>
                <?php echo wp_kses_post(wahrb_admin_detail_payment_badge($payment['security_status'] ?? 'not_due')); ?>
                <?php if ( ! empty($payment['security_captured_at']) ) : ?>
                    <div style="font-size:12px;color:#94a3b8;margin-top:6px;"><?php esc_html_e('Captured:', 'wahra-rentals-bookings'); ?> <?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($payment['security_captured_at']))); ?></div>
                <?php endif; ?>
                <?php if ( ! empty($payment['security_released_at']) ) : ?>
                    <div style="font-size:12px;color:#94a3b8;margin-top:6px;"><?php esc_html_e('Released:', 'wahra-rentals-bookings'); ?> <?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($payment['security_released_at']))); ?></div>
                <?php endif; ?>
                <?php if ( ! empty($payment['damage_amount']) && floatval($payment['damage_amount']) > 0 ) : ?>
                    <div style="font-size:12px;color:#ef4444;margin-top:6px;"><?php esc_html_e('Damage:', 'wahra-rentals-bookings'); ?> <?php echo wp_kses_post(wc_price($payment['damage_amount'])); ?></div>
                <?php endif; ?>
            </div>
            <!-- Balance Card -->
            <div style="padding:20px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
                <div style="font-size:13px;color:#64748b;margin-bottom:4px;"><?php esc_html_e('Balance', 'wahra-rentals-bookings'); ?></div>
                <div style="font-size:1.5rem;font-weight:700;margin-bottom:8px;"><?php echo wp_kses_post(wc_price($payment['balance_amount_final'] ?? 0)); ?></div>
                <?php echo wp_kses_post(wahrb_admin_detail_payment_badge($payment['balance_status'] ?? 'not_due')); ?>
                <?php if ( ! empty($payment['balance_paid_at']) ) : ?>
                    <div style="font-size:12px;color:#94a3b8;margin-top:6px;"><?php esc_html_e('Paid:', 'wahra-rentals-bookings'); ?> <?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($payment['balance_paid_at']))); ?></div>
                <?php endif; ?>
                <?php if ( ! empty($payment['balance_payment_method']) ) : ?>
                    <div style="font-size:12px;color:#64748b;margin-top:4px;"><?php esc_html_e('Method:', 'wahra-rentals-bookings'); ?> <?php echo esc_html(ucfirst($payment['balance_payment_method'])); ?></div>
                <?php endif; ?>
            </div>
        </div>

        <!-- Totals -->
        <table class="widefat fixed striped">
            <tbody>
                <tr><td style="font-weight:600;width:200px;"><?php esc_html_e('Total Amount', 'wahra-rentals-bookings'); ?></td><td><?php echo wp_kses_post(wc_price($payment['total_amount'] ?? 0)); ?></td></tr>
                <?php if ( ! empty($payment['deposit_type']) ) : ?>
                <tr><td style="font-weight:600;"><?php esc_html_e('Deposit Type', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(ucfirst($payment['deposit_type'] ?? '-')); ?> (<?php echo esc_html($payment['deposit_value'] ?? '-'); ?>)</td></tr>
                <?php endif; ?>
                <?php if ( ! empty($payment['wc_deposit_order_id']) ) : ?>
                <tr><td style="font-weight:600;"><?php esc_html_e('Deposit Order', 'wahra-rentals-bookings'); ?></td><td><a href="<?php echo esc_url(admin_url('post.php?post=' . intval($payment['wc_deposit_order_id']) . '&action=edit')); ?>">#<?php echo esc_html($payment['wc_deposit_order_id']); ?></a></td></tr>
                <?php endif; ?>
                <?php if ( ! empty($payment['wc_balance_order_id']) ) : ?>
                <tr><td style="font-weight:600;"><?php esc_html_e('Balance Order', 'wahra-rentals-bookings'); ?></td><td><a href="<?php echo esc_url(admin_url('post.php?post=' . intval($payment['wc_balance_order_id']) . '&action=edit')); ?>">#<?php echo esc_html($payment['wc_balance_order_id']); ?></a></td></tr>
                <?php endif; ?>
            </tbody>
        </table>

        <?php if ( ! empty($coupon_meta) ) : ?>
        <div style="margin-top:16px;padding:14px;border:1px solid #dbeafe;border-radius:8px;background:#eff6ff;">
            <h4 style="margin:0 0 8px;font-size:14px;color:#1e40af;">🎟️ <?php esc_html_e('Coupon Applied', 'wahra-rentals-bookings'); ?></h4>
            <table class="widefat fixed striped">
                <tbody>
                    <tr><td style="font-weight:600;width:200px;"><?php esc_html_e('Code', 'wahra-rentals-bookings'); ?></td><td><code><?php echo esc_html($coupon_meta['code'] ?? '-'); ?></code></td></tr>
                    <tr><td style="font-weight:600;"><?php esc_html_e('Discount Type', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html(ucfirst($coupon_meta['discount_type'] ?? '-')); ?></td></tr>
                    <?php if ( ($coupon_meta['discount_type'] ?? '') === 'percent' ) : ?>
                    <tr><td style="font-weight:600;"><?php esc_html_e('Discount Rate', 'wahra-rentals-bookings'); ?></td><td><?php echo esc_html($coupon_meta['discount_value'] ?? 0); ?>%</td></tr>
                    <?php endif; ?>
                    <tr><td style="font-weight:600;"><?php esc_html_e('Discount Amount', 'wahra-rentals-bookings'); ?></td><td style="color:#16a34a;font-weight:600;"><?php echo wp_kses_post(wc_price($coupon_meta['discount_amount'] ?? 0)); ?></td></tr>
                </tbody>
            </table>
        </div>
        <?php endif; ?>

        <?php endif; ?>
    </div>

    <!-- ═══════════ TAB: Form Data ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-formdata" style="<?php echo $active_tab !== 'formdata' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">
        <h3 style="margin-top:0;">📋 <?php esc_html_e('Custom Form Data', 'wahra-rentals-bookings'); ?></h3>

        <?php if ( empty($form_data) || empty($form_data['fields']) ) : ?>
            <p style="color:#94a3b8;"><?php esc_html_e('No custom form data was submitted with this booking.', 'wahra-rentals-bookings'); ?></p>
        <?php else : ?>
            <?php if ( ! empty($form_data['template_name']) ) : ?>
            <p style="font-size:13px;color:#64748b;">
                <?php
                /* translators: 1: template name, 2: submission date */
                printf(esc_html__('Template: %1$s — Submitted: %2$s', 'wahra-rentals-bookings'), '<strong>' . esc_html($form_data['template_name']) . '</strong>', esc_html(date_i18n('d/m/Y H:i', strtotime($form_data['submitted_at'] ?? ''))));
                ?>
            </p>
            <?php endif; ?>

            <table class="widefat fixed striped">
                <thead>
                    <tr>
                        <th style="width:200px;"><?php esc_html_e('Field', 'wahra-rentals-bookings'); ?></th>
                        <th><?php esc_html_e('Value', 'wahra-rentals-bookings'); ?></th>
                        <th style="width:100px;"><?php esc_html_e('Type', 'wahra-rentals-bookings'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $display_only = WAHRB_Form_Builder::DISPLAY_ONLY_TYPES;
                    foreach ( $form_data['fields'] as $field ) :
                        $ftype = $field['type'] ?? 'text';
                        if ( in_array($ftype, $display_only, true) ) {
                            continue;
                        }
                        $fvalue = $field['value'] ?? '';
                        if ($ftype === 'checkbox' || $ftype === 'consent') {
                            $display_val = $fvalue ? esc_html__('Yes', 'wahra-rentals-bookings') : esc_html__('No', 'wahra-rentals-bookings');
                        } elseif ($ftype === 'date' && $fvalue) {
                            $display_val = esc_html(date_i18n('d/m/Y', strtotime($fvalue)));
                        } else {
                            $display_val = esc_html($fvalue ?: '-');
                        }
                    ?>
                    <tr>
                        <td style="font-weight:600;"><?php echo esc_html($field['label'] ?? $field['key']); ?></td>
                        <td><?php echo $display_val; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Already escaped above ?></td>
                        <td><code><?php echo esc_html($ftype); ?></code></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>

    <!-- ═══════════ TAB: Contract ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-contract" style="<?php echo $active_tab !== 'contract' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">
        <h3 style="margin-top:0;">📄 <?php esc_html_e('Contract', 'wahra-rentals-bookings'); ?></h3>
        <div style="text-align:center;padding:40px;color:#94a3b8;">
            <span style="font-size:3rem;">📄</span>
            <p style="font-size:1.1rem;margin-top:12px;"><?php esc_html_e('Contract generation coming in Phase 4.', 'wahra-rentals-bookings'); ?></p>
            <p style="font-size:13px;"><?php esc_html_e('Auto-generate PDF contracts or upload signed documents.', 'wahra-rentals-bookings'); ?></p>
        </div>
    </div>

    <!-- ═══════════ TAB: Invoice ═══════════ -->
    <div class="wahrb-tab-content" id="wahrb-tc-invoice" style="<?php echo $active_tab !== 'invoice' ? 'display:none;' : ''; ?>background:#fff;border:1px solid #c3c4c7;border-top:none;padding:24px;">
        <h3 style="margin-top:0;">🧾 <?php esc_html_e('Invoice', 'wahra-rentals-bookings'); ?></h3>
        <div style="text-align:center;padding:40px;color:#94a3b8;">
            <span style="font-size:3rem;">🧾</span>
            <p style="font-size:1.1rem;margin-top:12px;"><?php esc_html_e('Invoice generation coming in Phase 4.', 'wahra-rentals-bookings'); ?></p>
            <p style="font-size:13px;"><?php esc_html_e('Auto-generate invoices linked to WooCommerce orders.', 'wahra-rentals-bookings'); ?></p>
        </div>
    </div>

</div><!-- .wahrb-booking-detail-wrap -->

<script>
jQuery(document).ready(function($) {
    'use strict';

    var bookingId = <?php echo (int) $booking_id; ?>;
    var restNonce = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var restBase  = '<?php echo esc_js(rest_url('wahrb/v1')); ?>';

    // ─── Tab switching ───
    $('.wahrb-detail-tab').on('click', function(e) {
        e.preventDefault();
        var tab = $(this).data('tab');
        $('.wahrb-detail-tab').removeClass('nav-tab-active');
        $(this).addClass('nav-tab-active');
        $('.wahrb-tab-content').hide();
        $('#wahrb-tc-' + tab).show();
    });

    // ─── Status transition ───
    $('.wahrb-admin-transition-btn').on('click', function() {
        var btn = $(this);
        var targetStatus = btn.data('target-status');
        if (!confirm('<?php echo esc_js(__('Are you sure?', 'wahra-rentals-bookings')); ?>')) return;

        btn.prop('disabled', true).text('…');

        var endpoint = restBase + '/vendor/bookings/' + bookingId;
        var method = 'PUT';
        var payload = { status: targetStatus };

        // Use specific endpoints for lifecycle transitions
        var actionMap = {
            'checked_in':  { url: endpoint + '/checkin',  method: 'POST', data: {} },
            'checked_out': { url: endpoint + '/checkout', method: 'POST', data: {} },
            'completed':   { url: endpoint + '/complete', method: 'POST', data: { notes: $('#wahrb-restitution-notes').val() || '' } },
            'cancelled':   { url: endpoint + '/cancel',   method: 'POST', data: {} }
        };

        var action = actionMap[targetStatus] || { url: endpoint, method: 'PUT', data: payload };

        $.ajax({
            url: action.url,
            method: action.method,
            headers: { 'X-WP-Nonce': restNonce },
            contentType: 'application/json',
            data: JSON.stringify(action.data),
            success: function() { location.reload(); },
            error: function(xhr) {
                var msg = (xhr.responseJSON && xhr.responseJSON.message) || '<?php echo esc_js(__('Error', 'wahra-rentals-bookings')); ?>';
                alert(msg);
                btn.prop('disabled', false).text(targetStatus);
            }
        });
    });

    // ─── Send Email ───
    $('#wahrb-send-email-btn').on('click', function() {
        var btn = $(this);
        var recipient = $('#wahrb-email-to').val();
        var subject   = $('#wahrb-email-subject').val();
        var body      = $('#wahrb-email-body').val();
        if (!recipient || !subject || !body) {
            alert('<?php echo esc_js(__('Please fill all fields.', 'wahra-rentals-bookings')); ?>');
            return;
        }
        btn.prop('disabled', true);
        $('#wahrb-email-status').text('<?php echo esc_js(__('Sending…', 'wahra-rentals-bookings')); ?>');

        $.ajax({
            url: restBase + '/vendor/bookings/' + bookingId + '/send-email',
            method: 'POST',
            headers: { 'X-WP-Nonce': restNonce },
            contentType: 'application/json',
            data: JSON.stringify({ recipient: recipient, subject: subject, body: body }),
            success: function(res) {
                $('#wahrb-email-status').html('<span style="color:#22c55e;">✓ ' + (res.message || '<?php echo esc_js(__('Sent!', 'wahra-rentals-bookings')); ?>') + '</span>');
                $('#wahrb-email-body').val('');
                btn.prop('disabled', false);
            },
            error: function(xhr) {
                var msg = (xhr.responseJSON && xhr.responseJSON.message) || '<?php echo esc_js(__('Failed to send.', 'wahra-rentals-bookings')); ?>';
                $('#wahrb-email-status').html('<span style="color:#ef4444;">✗ ' + msg + '</span>');
                btn.prop('disabled', false);
            }
        });
    });

    // ─── Add Note ───
    $('#wahrb-add-note-btn').on('click', function() {
        var btn = $(this);
        var content = $('#wahrb-new-note').val();
        if (!content.trim()) return;
        var isPrivate = $('#wahrb-note-private').is(':checked');
        btn.prop('disabled', true);

        $.ajax({
            url: restBase + '/vendor/bookings/' + bookingId + '/notes',
            method: 'POST',
            headers: { 'X-WP-Nonce': restNonce },
            contentType: 'application/json',
            data: JSON.stringify({ content: content, is_private: isPrivate }),
            success: function(note) {
                $('#wahrb-no-notes').remove();
                var bg = note.is_private ? 'background:#fefce8;border-color:#fcd34d;' : '';
                var priv = note.is_private ? ' <span style="font-size:11px;color:#d97706;">(<?php echo esc_js(__('private', 'wahra-rentals-bookings')); ?>)</span>' : '';
                function escHtml(s) { var d = document.createElement('div'); d.appendChild(document.createTextNode(s || '')); return d.innerHTML; }
                var html = '<div class="wahrb-note-item" data-note-id="' + note.note_id + '" style="padding:12px 16px;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:8px;' + bg + '">'
                    + '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:6px;">'
                    + '<span style="font-size:13px;color:#64748b;">✏️ <?php echo esc_js(wp_get_current_user()->display_name); ?>' + priv + ' &middot; <?php echo esc_js(__('just now', 'wahra-rentals-bookings')); ?></span>'
                    + '<button type="button" class="button button-small wahrb-delete-note" data-note-id="' + note.note_id + '" data-booking-id="' + bookingId + '">&times;</button>'
                    + '</div>'
                    + '<div style="white-space:pre-wrap;">' + escHtml(note.content) + '</div>'
                    + '</div>';
                $('#wahrb-notes-list').prepend(html);
                $('#wahrb-new-note').val('');
                $('#wahrb-note-private').prop('checked', false);
                btn.prop('disabled', false);
            },
            error: function() {
                alert('<?php echo esc_js(__('Failed to add note.', 'wahra-rentals-bookings')); ?>');
                btn.prop('disabled', false);
            }
        });
    });

    // ─── Delete Note ───
    $(document).on('click', '.wahrb-delete-note', function() {
        var noteBtn = $(this);
        var noteId = noteBtn.data('note-id');
        if (!confirm('<?php echo esc_js(__('Delete this note?', 'wahra-rentals-bookings')); ?>')) return;

        $.ajax({
            url: restBase + '/vendor/bookings/' + bookingId + '/notes/' + noteId,
            method: 'DELETE',
            headers: { 'X-WP-Nonce': restNonce },
            success: function() {
                noteBtn.closest('.wahrb-note-item').fadeOut(300, function() { $(this).remove(); });
            },
            error: function() {
                alert('<?php echo esc_js(__('Failed to delete note.', 'wahra-rentals-bookings')); ?>');
            }
        });
    });
});
</script>
