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

defined('ABSPATH') || exit;

// ─── Helpers (guarded, defined at top per CLAUDE.md rule) ───
if ( ! function_exists( 'wahrb_vendor_detail_status_badge' ) ) {
    function wahrb_vendor_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')],
        ];
        $c = $map[$status][0] ?? '#666';
        $l = $map[$status][1] ?? ucfirst($status);
        return '<span class="wahrb-status wahrb-status-' . esc_attr($status) . '" style="display:inline-block;padding:3px 10px;border-radius:4px;background:' . esc_attr($c) . ';color:#fff;font-size:.85em;">' . esc_html($l) . '</span>';
    }
}

if ( ! function_exists( 'wahrb_vendor_detail_pay_badge' ) ) {
    function wahrb_vendor_detail_pay_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')],
        ];
        $c = $map[$status][0] ?? '#94a3b8';
        $l = $map[$status][1] ?? ucfirst(str_replace('_', ' ', $status));
        return '<span style="display:inline-block;padding:2px 8px;border-radius:12px;background:' . esc_attr($c) . '22;color:' . esc_attr($c) . ';font-size:.8em;font-weight:600;border:1px solid ' . esc_attr($c) . '44;">' . esc_html($l) . '</span>';
    }
}

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

// 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="dokan-alert dokan-alert-danger">' . esc_html__('No booking ID provided.', 'wahra-rentals-bookings') . '</div>';
    return;
}

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

// Ownership check: vendor must own the booking or the product
$bdata = $booking->get_data();
$owns = ( (int) ($bdata['vendor_id'] ?? 0) === $vendor_id );
if ( ! $owns && ! empty($bdata['product_id']) ) {
    $product_author = (int) get_post_field('post_author', $bdata['product_id']);
    $owns = ( $product_author === $vendor_id );
}
if ( ! $owns && ! current_user_can('manage_woocommerce') ) {
    echo '<div class="dokan-alert dokan-alert-danger">' . esc_html__('You do not have permission to view this booking.', 'wahra-rentals-bookings') . '</div>';
    return;
}

// 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 & category 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'];
}

// 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);

$back_url = wahrb_get_vendor_dashboard_url('bookings');

$tabs = [
    'manage'  => ['label' => __('Manage', 'wahra-rentals-bookings'),         'icon' => '⚙️'],
    'details' => ['label' => __('Details', 'wahra-rentals-bookings'),         'icon' => '📋'],
    'email'   => ['label' => __('Email Customer', 'wahra-rentals-bookings'),  'icon' => '✉️'],
    'emaillog'=> ['label' => __('Email Logs', 'wahra-rentals-bookings'),      'icon' => '📧'],
    'notes'   => ['label' => __('Notes', 'wahra-rentals-bookings'),           'icon' => '📝'],
    'smslog'  => ['label' => __('SMS Logs', 'wahra-rentals-bookings'),        'icon' => '📱'],
    'payment' => ['label' => __('Payment', 'wahra-rentals-bookings'),         'icon' => '💰'],
    'formdata'=> ['label' => __('Form Data', 'wahra-rentals-bookings'),       'icon' => '📋'],
    'contract'=> ['label' => __('Contract', 'wahra-rentals-bookings'),        'icon' => '📄'],
    'invoice' => ['label' => __('Invoice', 'wahra-rentals-bookings'),         'icon' => '🧾'],
];
?>

<div class="dokan-dashboard-wrap">
    <?php do_action('dokan_dashboard_content_before'); ?>

    <div class="dokan-dashboard-content dokan-product-listing">
        <article class="wahrb-booking-detail-page">

            <!-- Header -->
            <header class="wahrb-page-header" style="display:flex;align-items:center;gap:12px;margin-bottom:20px;flex-wrap:wrap;">
                <a href="<?php echo esc_url($back_url); ?>" class="wahrb-btn wahrb-btn-secondary" style="padding:6px 12px;">
                    &larr; <?php esc_html_e('Back', 'wahra-rentals-bookings'); ?>
                </a>
                <h1 class="wahrb-page-title" style="margin:0;font-size:1.4rem;">
                    <?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_vendor_detail_status_badge($bdata['status'])); ?>
            </header>

            <!-- Tab Navigation -->
            <nav class="wahrb-detail-tabs" style="display:flex;flex-wrap:wrap;gap:2px;border-bottom:2px solid #e2e8f0;margin-bottom:0;overflow-x:auto;">
                <?php $first = true; foreach ( $tabs as $slug => $tab ) : ?>
                    <button type="button"
                            class="wahrb-dtab <?php echo $first ? 'wahrb-dtab-active' : ''; ?>"
                            data-tab="<?php echo esc_attr($slug); ?>">
                        <span class="wahrb-dtab-icon"><?php echo esc_html($tab['icon']); ?></span>
                        <span class="wahrb-dtab-label"><?php echo esc_html($tab['label']); ?></span>
                    </button>
                <?php $first = false; endforeach; ?>
            </nav>

            <!-- ═══════════ TAB: Manage ═══════════ -->
            <div class="wahrb-dtab-content wahrb-dtab-active" id="wahrb-vtc-manage">

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
                    <!-- Summary -->
                    <div class="wahrb-card">
                        <h3 class="wahrb-card-title"><?php esc_html_e('Booking Summary', 'wahra-rentals-bookings'); ?></h3>
                        <div class="wahrb-detail-rows">
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($product_name); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Customer', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($bdata['customer_name'] ?? ''); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Dates', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(date_i18n('d/m/Y', strtotime($bdata['start_dt'])) . ' → ' . date_i18n('d/m/Y', strtotime($bdata['end_dt']))); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Quantity', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($bdata['qty'] ?? 1); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Total', 'wahra-rentals-bookings'); ?></span><strong><?php echo wp_kses_post(wc_price($payment['total_amount'] ?? $bdata['total_amount'] ?? 0)); ?></strong></div>
                        </div>
                    </div>

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

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

                        if ( ! empty($transitions) ) :
                            foreach ( $transitions as $target => $btn_label ) :
                                $cls = $target === 'cancelled' ? 'wahrb-btn wahrb-btn-secondary' : 'wahrb-btn wahrb-btn-primary';
                            ?>
                            <button type="button"
                                    class="<?php echo esc_attr($cls); ?> wahrb-vendor-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.', 'wahra-rentals-bookings'); ?></p>
                        <?php endif; ?>

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

            <!-- ═══════════ TAB: Details ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-details" style="display:none;">

                <div style="display:grid;grid-template-columns:1fr 1fr;gap:24px;">
                    <div class="wahrb-card">
                        <h3 class="wahrb-card-title">📋 <?php esc_html_e('Core Information', 'wahra-rentals-bookings'); ?></h3>
                        <div class="wahrb-detail-rows">
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Booking ID', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($booking_id); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Number', 'wahra-rentals-bookings'); ?></span><strong>#<?php echo esc_html($bdata['booking_number']); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Status', 'wahra-rentals-bookings'); ?></span><strong><?php echo wp_kses_post(wahrb_vendor_detail_status_badge($bdata['status'])); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($product_name); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Category', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(ucfirst($bdata['platform_category'] ?? '-')); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Mode', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(ucfirst($bdata['booking_mode'] ?? 'day')); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Created', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['created_at']))); ?></strong></div>
                            <?php if ( ! empty($bdata['wc_order_id']) ) : ?>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('WC Order', 'wahra-rentals-bookings'); ?></span><strong>#<?php echo esc_html($bdata['wc_order_id']); ?></strong></div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="wahrb-card">
                        <h3 class="wahrb-card-title">👤 <?php esc_html_e('Customer', 'wahra-rentals-bookings'); ?></h3>
                        <div class="wahrb-detail-rows">
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Name', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($bdata['customer_name'] ?? '-'); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Email', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($bdata['customer_email'] ?? '-'); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Phone', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($bdata['customer_phone'] ?? '-'); ?></strong></div>
                        </div>

                        <h3 class="wahrb-card-title" style="margin-top:20px;">📅 <?php esc_html_e('Schedule', 'wahra-rentals-bookings'); ?></h3>
                        <div class="wahrb-detail-rows">
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Start', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['start_dt']))); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('End', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($bdata['end_dt']))); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Quantity', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($bdata['qty'] ?? 1); ?></strong></div>
                            <?php if ( ! empty($bdata['slot_start']) ) : ?>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Slot', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($bdata['slot_start'] . ' – ' . ($bdata['slot_end'] ?? '')); ?></strong></div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <?php if ( ! empty($bdata['notes_customer']) ) : ?>
                <div class="wahrb-card" style="margin-top:16px;">
                    <h3 class="wahrb-card-title">💬 <?php esc_html_e('Customer Message', 'wahra-rentals-bookings'); ?></h3>
                    <p style="margin:0;font-style:italic;color:#475569;"><?php echo esc_html($bdata['notes_customer']); ?></p>
                </div>
                <?php endif; ?>
            </div>

            <!-- ═══════════ TAB: Email Customer ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-email" style="display:none;">
                <div class="wahrb-card">
                    <h3 class="wahrb-card-title">✉️ <?php esc_html_e('Send Email to Customer', 'wahra-rentals-bookings'); ?></h3>

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

                    <button type="button" id="wahrb-send-email-btn" class="wahrb-btn wahrb-btn-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>
                </div>
            </div>

            <!-- ═══════════ TAB: Email Logs ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-emaillog" style="display:none;">
                <div class="wahrb-card">
                    <h3 class="wahrb-card-title">📧 <?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 sent for this booking.', 'wahra-rentals-bookings'); ?></p>
                    <?php else : ?>
                        <div class="wahrb-table-responsive">
                        <table class="dokan-table dokan-table-striped">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Date', 'wahra-rentals-bookings'); ?></th>
                                    <th><?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><?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>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ═══════════ TAB: Notes ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-notes" style="display:none;">
                <div class="wahrb-card">
                    <h3 class="wahrb-card-title">📝 <?php esc_html_e('Booking Notes', 'wahra-rentals-bookings'); ?></h3>

                    <!-- Add Note -->
                    <div style="margin-bottom:16px;padding:12px;background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;">
                        <textarea id="wahrb-new-note" rows="3" class="dokan-form-control" placeholder="<?php esc_attr_e('Add a note…', 'wahra-rentals-bookings'); ?>" style="margin-bottom:8px;"></textarea>
                        <div style="display:flex;align-items:center;gap:12px;">
                            <button type="button" id="wahrb-add-note-btn" class="wahrb-btn wahrb-btn-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;cursor:pointer;"><input type="checkbox" id="wahrb-note-private" /> <?php esc_html_e('Private', '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:10px 14px;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:6px;<?php echo !empty($note['is_private']) ? 'background:#fefce8;border-color:#fcd34d;' : ''; ?>">
                                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
                                    <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="wahrb-btn-icon-sm 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>
            </div>

            <!-- ═══════════ TAB: SMS Logs ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-smslog" style="display:none;">
                <div class="wahrb-card">
                    <h3 class="wahrb-card-title">📱 <?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 sent for this booking.', 'wahra-rentals-bookings'); ?></p>
                        <p style="color:#64748b;font-size:13px;"><?php esc_html_e('SMS automation coming in Phase 2.', 'wahra-rentals-bookings'); ?></p>
                    <?php else : ?>
                        <div class="wahrb-table-responsive">
                        <table class="dokan-table dokan-table-striped">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Date', 'wahra-rentals-bookings'); ?></th>
                                    <th><?php esc_html_e('Type', 'wahra-rentals-bookings'); ?></th>
                                    <th><?php esc_html_e('Phone', 'wahra-rentals-bookings'); ?></th>
                                    <th><?php esc_html_e('Message', 'wahra-rentals-bookings'); ?></th>
                                    <th><?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:250px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;"><?php echo esc_html($slog['message']); ?></td>
                                    <td>
                                        <?php
                                        $sms_clr = ['sent' => '#22c55e', 'delivered' => '#16a34a', 'failed' => '#ef4444', 'queued' => '#f59e0b'];
                                        $sc = $sms_clr[$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>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ═══════════ TAB: Payment ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-payment" style="display:none;">
                <div class="wahrb-card">
                    <h3 class="wahrb-card-title">💰 <?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.', 'wahra-rentals-bookings'); ?></p>
                    <?php else : ?>
                    <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;margin-bottom:20px;">
                        <!-- Deposit -->
                        <div style="padding:16px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
                            <div style="font-size:12px;color:#64748b;text-transform:uppercase;letter-spacing:.5px;"><?php esc_html_e('Deposit', 'wahra-rentals-bookings'); ?></div>
                            <div style="font-size:1.4rem;font-weight:700;margin:4px 0;"><?php echo wp_kses_post(wc_price($payment['deposit_amount_final'] ?? 0)); ?></div>
                            <?php echo wp_kses_post(wahrb_vendor_detail_pay_badge($payment['deposit_status'] ?? 'not_due')); ?>
                            <?php if ( ! empty($payment['deposit_paid_at']) ) : ?>
                                <div style="font-size:11px;color:#94a3b8;margin-top:4px;"><?php echo esc_html(date_i18n('d/m/Y H:i', strtotime($payment['deposit_paid_at']))); ?></div>
                            <?php endif; ?>
                        </div>
                        <!-- Security -->
                        <div style="padding:16px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
                            <div style="font-size:12px;color:#64748b;text-transform:uppercase;letter-spacing:.5px;"><?php esc_html_e('Security', 'wahra-rentals-bookings'); ?></div>
                            <div style="font-size:1.4rem;font-weight:700;margin:4px 0;"><?php echo wp_kses_post(wc_price($payment['security_deposit_amount_final'] ?? 0)); ?></div>
                            <?php echo wp_kses_post(wahrb_vendor_detail_pay_badge($payment['security_status'] ?? 'not_due')); ?>
                            <?php if ( ! empty($payment['damage_amount']) && floatval($payment['damage_amount']) > 0 ) : ?>
                                <div style="font-size:11px;color:#ef4444;margin-top:4px;"><?php esc_html_e('Damage:', 'wahra-rentals-bookings'); ?> <?php echo wp_kses_post(wc_price($payment['damage_amount'])); ?></div>
                            <?php endif; ?>
                        </div>
                        <!-- Balance -->
                        <div style="padding:16px;border:1px solid #e2e8f0;border-radius:8px;background:#f8fafc;">
                            <div style="font-size:12px;color:#64748b;text-transform:uppercase;letter-spacing:.5px;"><?php esc_html_e('Balance', 'wahra-rentals-bookings'); ?></div>
                            <div style="font-size:1.4rem;font-weight:700;margin:4px 0;"><?php echo wp_kses_post(wc_price($payment['balance_amount_final'] ?? 0)); ?></div>
                            <?php echo wp_kses_post(wahrb_vendor_detail_pay_badge($payment['balance_status'] ?? 'not_due')); ?>
                            <?php if ( ! empty($payment['balance_payment_method']) ) : ?>
                                <div style="font-size:11px;color:#64748b;margin-top:4px;"><?php echo esc_html(ucfirst($payment['balance_payment_method'])); ?></div>
                            <?php endif; ?>
                        </div>
                    </div>

                    <div class="wahrb-detail-rows">
                        <div class="wahrb-detail-row"><span><?php esc_html_e('Total Amount', 'wahra-rentals-bookings'); ?></span><strong><?php echo wp_kses_post(wc_price($payment['total_amount'] ?? 0)); ?></strong></div>
                        <?php if ( ! empty($payment['deposit_type']) ) : ?>
                        <div class="wahrb-detail-row"><span><?php esc_html_e('Deposit Type', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(ucfirst($payment['deposit_type']) . ' (' . ($payment['deposit_value'] ?? '-') . ')'); ?></strong></div>
                        <?php endif; ?>
                    </div>

                    <?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>
                        <div class="wahrb-detail-rows">
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Code', 'wahra-rentals-bookings'); ?></span><strong style="font-family:monospace;"><?php echo esc_html($coupon_meta['code'] ?? '-'); ?></strong></div>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Discount Type', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html(ucfirst($coupon_meta['discount_type'] ?? '-')); ?></strong></div>
                            <?php if ( ($coupon_meta['discount_type'] ?? '') === 'percent' ) : ?>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Discount Rate', 'wahra-rentals-bookings'); ?></span><strong><?php echo esc_html($coupon_meta['discount_value'] ?? 0); ?>%</strong></div>
                            <?php endif; ?>
                            <div class="wahrb-detail-row"><span><?php esc_html_e('Discount Amount', 'wahra-rentals-bookings'); ?></span><strong style="color:#16a34a;"><?php echo wp_kses_post(wc_price($coupon_meta['discount_amount'] ?? 0)); ?></strong></div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php endif; ?>
                </div>
            </div>

            <!-- ═══════════ TAB: Form Data ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-formdata" style="display:none;">
                <div class="wahrb-card">
                    <h3 class="wahrb-card-title">📋 <?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;margin-top:0;">
                            <?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; ?>

                        <div class="wahrb-detail-rows">
                            <?php
                            $display_only = WAHRB_Form_Builder::DISPLAY_ONLY_TYPES;
                            foreach ( $form_data['fields'] as $field ) :
                                $ftype = $field['type'] ?? 'text';
                                // Skip display-only types (heading, html) — they have no submitted value
                                if ( in_array($ftype, $display_only, true) ) {
                                    continue;
                                }
                                $fvalue = $field['value'] ?? '';
                                // Format display value based on type
                                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 ?: '-');
                                }
                            ?>
                            <div class="wahrb-detail-row">
                                <span><?php echo esc_html($field['label'] ?? $field['key']); ?></span>
                                <strong><?php echo $display_val; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Already escaped above ?></strong>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ═══════════ TAB: Contract ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-contract" style="display:none;">
                <div class="wahrb-card" style="text-align:center;padding:40px;">
                    <span style="font-size:3rem;">📄</span>
                    <p style="font-size:1.1rem;margin-top:12px;color:#94a3b8;"><?php esc_html_e('Contract generation coming in Phase 4.', 'wahra-rentals-bookings'); ?></p>
                    <p style="font-size:13px;color:#94a3b8;"><?php esc_html_e('Auto-generate PDF contracts or upload signed documents.', 'wahra-rentals-bookings'); ?></p>
                </div>
            </div>

            <!-- ═══════════ TAB: Invoice ═══════════ -->
            <div class="wahrb-dtab-content" id="wahrb-vtc-invoice" style="display:none;">
                <div class="wahrb-card" style="text-align:center;padding:40px;">
                    <span style="font-size:3rem;">🧾</span>
                    <p style="font-size:1.1rem;margin-top:12px;color:#94a3b8;"><?php esc_html_e('Invoice generation coming in Phase 4.', 'wahra-rentals-bookings'); ?></p>
                    <p style="font-size:13px;color:#94a3b8;"><?php esc_html_e('Auto-generate invoices linked to WooCommerce orders.', 'wahra-rentals-bookings'); ?></p>
                </div>
            </div>

        </article>
    </div>

    <?php do_action('dokan_dashboard_content_after'); ?>
</div>

<?php
// ─── Inline CSS for detail page ───
$detail_css = '
.wahrb-booking-detail-page{max-width:100%}
.wahrb-detail-tabs{display:flex;flex-wrap:wrap;gap:2px;border-bottom:2px solid #e2e8f0;margin-bottom:0}
.wahrb-dtab{background:none;border:none;padding:10px 16px;cursor:pointer;font-size:13px;color:#64748b;border-bottom:2px solid transparent;margin-bottom:-2px;display:flex;align-items:center;gap:6px;transition:all .2s;white-space:nowrap}
.wahrb-dtab:hover{color:#1e293b;background:#f8fafc}
.wahrb-dtab-active{color:#1976d2;border-bottom-color:#1976d2;font-weight:600}
.wahrb-dtab-icon{font-size:14px}
.wahrb-dtab-content{background:#fff;border:1px solid #e2e8f0;border-top:none;border-radius:0 0 8px 8px;padding:24px}
.wahrb-card{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:20px}
.wahrb-card-title{margin:0 0 12px;font-size:1rem;font-weight:600;color:#1e293b}
.wahrb-detail-rows{display:flex;flex-direction:column;gap:8px}
.wahrb-detail-row{display:flex;justify-content:space-between;align-items:center;padding:6px 0;border-bottom:1px solid #f1f5f9}
.wahrb-detail-row span{color:#64748b;font-size:13px}
.wahrb-detail-row strong{color:#1e293b}
.wahrb-table-responsive{overflow-x:auto}
.wahrb-btn-icon-sm{background:none;border:1px solid #e2e8f0;border-radius:4px;width:24px;height:24px;cursor:pointer;color:#94a3b8;font-size:16px;line-height:1;display:inline-flex;align-items:center;justify-content:center}
.wahrb-btn-icon-sm:hover{color:#ef4444;border-color:#ef4444}
@media(max-width:768px){
    .wahrb-dtab-content>div[style*="grid"]{grid-template-columns:1fr!important}
    .wahrb-dtab{padding:8px 10px;font-size:12px}
    .wahrb-dtab-icon{display:none}
}
';
wp_add_inline_style('wahrb-vendor-styles', wp_strip_all_tags($detail_css));
?>

<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-dtab').on('click', function() {
        var tab = $(this).data('tab');
        $('.wahrb-dtab').removeClass('wahrb-dtab-active');
        $(this).addClass('wahrb-dtab-active');
        $('.wahrb-dtab-content').hide();
        $('#wahrb-vtc-' + tab).show();
    });

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

        var ep = restBase + '/vendor/bookings/' + bookingId;
        var map = {
            'checked_in':  { url: ep + '/checkin',  method: 'POST', data: {} },
            'checked_out': { url: ep + '/checkout', method: 'POST', data: {} },
            'completed':   { url: ep + '/complete', method: 'POST', data: { notes: $('#wahrb-restitution-notes').val() || '' } },
            'cancelled':   { url: ep + '/cancel',   method: 'POST', data: {} }
        };
        var action = map[target] || { url: ep, method: 'PUT', data: { status: target } };

        $.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) {
                alert((xhr.responseJSON && xhr.responseJSON.message) || '<?php echo esc_js(__('Error', 'wahra-rentals-bookings')); ?>');
                btn.prop('disabled', false);
            }
        });
    });

    // ─── Send Email ───
    $('#wahrb-send-email-btn').on('click', function() {
        var btn = $(this);
        var to = $('#wahrb-email-to').val(), subj = $('#wahrb-email-subject').val(), body = $('#wahrb-email-body').val();
        if (!to || !subj || !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: to, subject: subj, body: body }),
            success: function(r) {
                $('#wahrb-email-status').html('<span style="color:#22c55e;">✓ ' + (r.message || '') + '</span>');
                $('#wahrb-email-body').val('');
                btn.prop('disabled', false);
            },
            error: function(xhr) {
                var m = (xhr.responseJSON && xhr.responseJSON.message) || '<?php echo esc_js(__('Failed.', 'wahra-rentals-bookings')); ?>';
                $('#wahrb-email-status').html('<span style="color:#ef4444;">✗ ' + m + '</span>');
                btn.prop('disabled', false);
            }
        });
    });

    // ─── Add Note ───
    $('#wahrb-add-note-btn').on('click', function() {
        var btn = $(this), content = $('#wahrb-new-note').val();
        if (!content.trim()) return;
        var priv = $('#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: priv }),
            success: function(note) {
                $('#wahrb-no-notes').remove();
                function esc(s) { var d = document.createElement('div'); d.appendChild(document.createTextNode(s||'')); return d.innerHTML; }
                var bg = note.is_private ? 'background:#fefce8;border-color:#fcd34d;' : '';
                var pLabel = note.is_private ? ' <span style="font-size:11px;color:#d97706;">(<?php echo esc_js(__('private', 'wahra-rentals-bookings')); ?>)</span>' : '';
                var html = '<div class="wahrb-note-item" data-note-id="' + note.note_id + '" style="padding:10px 14px;border:1px solid #e2e8f0;border-radius:6px;margin-bottom:6px;' + bg + '">'
                    + '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">'
                    + '<span style="font-size:13px;color:#64748b;">✏️ <?php echo esc_js(wp_get_current_user()->display_name); ?>' + pLabel + ' &middot; <?php echo esc_js(__('just now', 'wahra-rentals-bookings')); ?></span>'
                    + '<button type="button" class="wahrb-btn-icon-sm wahrb-delete-note" data-note-id="' + note.note_id + '" data-booking-id="' + bookingId + '">&times;</button>'
                    + '</div><div style="white-space:pre-wrap;">' + esc(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), nid = noteBtn.data('note-id');
        if (!confirm('<?php echo esc_js(__('Delete this note?', 'wahra-rentals-bookings')); ?>')) return;
        $.ajax({
            url: restBase + '/vendor/bookings/' + bookingId + '/notes/' + nid,
            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.', 'wahra-rentals-bookings')); ?>'); }
        });
    });
});
</script>
