<?php
/**
 * Dokan Vendor Bookings List Template - Modern UI
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

global $wpdb;
$db = WAHRB_Database::instance();

$vendor_id = get_current_user_id();
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Pagination and filter parameters, no data modification
$page = isset($_GET['paged']) ? absint(wp_unslash($_GET['paged'])) : 1;
$status = isset($_GET['status']) ? sanitize_text_field(wp_unslash($_GET['status'])) : '';
$filter_product = isset($_GET['product_id']) ? absint(wp_unslash($_GET['product_id'])) : 0;
$filter_date_from = isset($_GET['date_from']) ? sanitize_text_field(wp_unslash($_GET['date_from'])) : '';
$filter_date_to = isset($_GET['date_to']) ? sanitize_text_field(wp_unslash($_GET['date_to'])) : '';
$filter_amount_min = isset($_GET['amount_min']) && $_GET['amount_min'] !== '' ? sanitize_text_field(wp_unslash($_GET['amount_min'])) : '';
$filter_amount_max = isset($_GET['amount_max']) && $_GET['amount_max'] !== '' ? sanitize_text_field(wp_unslash($_GET['amount_max'])) : '';
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Build where clause - match by vendor_id OR by product owner (post_author)
$where_base = $wpdb->prepare("(b.vendor_id = %d OR p.post_author = %d)", $vendor_id, $vendor_id);
$where_parts = [$where_base, 'b.deleted_at IS NULL'];
if ($status) {
    $where_parts[] = $wpdb->prepare('b.status = %s', $status);
}
if ($filter_product > 0) {
    $where_parts[] = $wpdb->prepare('b.product_id = %d', $filter_product);
}
if ($filter_date_from) {
    $where_parts[] = $wpdb->prepare('b.start_dt >= %s', $filter_date_from);
}
if ($filter_date_to) {
    $where_parts[] = $wpdb->prepare('b.end_dt <= %s', $filter_date_to . ' 23:59:59');
}
if ($filter_amount_min !== '') {
    $where_parts[] = $wpdb->prepare('COALESCE(ps.total_amount, 0) >= %f', (float) $filter_amount_min);
}
if ($filter_amount_max !== '') {
    $where_parts[] = $wpdb->prepare('COALESCE(ps.total_amount, 0) <= %f', (float) $filter_amount_max);
}
$where_sql = implode(' AND ', $where_parts);

// Products with at least one booking for this vendor (for filter dropdown)
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
$products_with_bookings = $wpdb->get_results($wpdb->prepare("SELECT DISTINCT b.product_id, COALESCE(p.post_title, CONCAT('Product #', b.product_id)) as product_name FROM {$db->table('bookings')} b LEFT JOIN {$wpdb->posts} p ON b.product_id = p.ID WHERE (b.vendor_id = %d OR p.post_author = %d) AND b.deleted_at IS NULL ORDER BY p.post_title ASC", $vendor_id, $vendor_id), ARRAY_A) ?: [];

// Get bookings with payment data
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom table with prepared WHERE clauses
$bookings = $wpdb->get_results(
    "SELECT b.*, p.post_title as product_name, ps.total_amount as ps_total
     FROM {$db->table('bookings')} b
     LEFT JOIN {$wpdb->posts} p ON b.product_id = p.ID
     LEFT JOIN {$db->table('payment_schedule')} ps ON b.booking_id = ps.booking_id
     WHERE {$where_sql}
     ORDER BY b.created_at DESC
     LIMIT {$per_page} OFFSET {$offset}",
    ARRAY_A
) ?: [];

// Count per status for tabs (global counts, unaffected by extra filters)
$count_where = $where_base . ' AND b.deleted_at IS NULL';
// phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.NotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Custom table with prepared WHERE clauses
$counts = $wpdb->get_results(
    "SELECT b.status, COUNT(*) as cnt 
     FROM {$db->table('bookings')} b
     LEFT JOIN {$wpdb->posts} p ON b.product_id = p.ID
     WHERE {$count_where}
     GROUP BY b.status",
    ARRAY_A
);
$status_counts = ['total' => 0];
foreach ($counts as $row) {
    $status_counts[$row['status']] = (int) $row['cnt'];
    $status_counts['total'] += (int) $row['cnt'];
}

// Check if extra filters active
$has_extra_filters = $filter_product || $filter_date_from || $filter_date_to || ($filter_amount_min !== '') || ($filter_amount_max !== '');

// Build tab URLs that preserve current filters
$tabs_base_url = wahrb_get_dashboard_url('bookings');
$preserved_args = [];
if ($filter_product) {
    $preserved_args['product_id'] = $filter_product;
}
if ($filter_date_from) {
    $preserved_args['date_from'] = $filter_date_from;
}
if ($filter_date_to) {
    $preserved_args['date_to'] = $filter_date_to;
}
if ($filter_amount_min !== '') {
    $preserved_args['amount_min'] = $filter_amount_min;
}
if ($filter_amount_max !== '') {
    $preserved_args['amount_max'] = $filter_amount_max;
}

// Status filters configuration
$status_filters = [
    '' => [
        'label' => __('All', 'wahra-rentals-bookings'),
        'icon' => '📋',
        'count' => $status_counts['total'] ?? 0
    ],
    'pending' => [
        'label' => __('Pending', 'wahra-rentals-bookings'),
        'icon' => '⏳',
        'count' => $status_counts['pending'] ?? 0
    ],
    'confirmed' => [
        'label' => __('Confirmed', 'wahra-rentals-bookings'),
        'icon' => '✅',
        'count' => $status_counts['confirmed'] ?? 0
    ],
    'checked_in' => [
        'label' => __('In progress', 'wahra-rentals-bookings'),
        'icon' => '▶️',
        'count' => $status_counts['checked_in'] ?? 0
    ],
    'checked_out' => [
        'label' => __('Returned', 'wahra-rentals-bookings'),
        'icon' => '🔄',
        'count' => $status_counts['checked_out'] ?? 0
    ],
    'completed' => [
        'label' => __('Completed', 'wahra-rentals-bookings'),
        'icon' => '🏁',
        'count' => $status_counts['completed'] ?? 0
    ],
    'cancelled' => [
        'label' => __('Cancelled', 'wahra-rentals-bookings'),
        'icon' => '❌',
        'count' => $status_counts['cancelled'] ?? 0
    ],
];

$status_labels = [
    'pending' => __('Pending', 'wahra-rentals-bookings'),
    'confirmed' => __('Confirmed', 'wahra-rentals-bookings'),
    'checked_in' => __('In progress', 'wahra-rentals-bookings'),
    'checked_out' => __('Returned', 'wahra-rentals-bookings'),
    'completed' => __('Completed', 'wahra-rentals-bookings'),
    'cancelled' => __('Cancelled', 'wahra-rentals-bookings'),
];
?>

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

    <div class="dokan-dashboard-content dokan-product-listing">
        <article class="dokan-product-listing-area wahrb-bookings-page">
            
            <!-- Page Header -->
            <header class="wahrb-page-header">
                <div class="wahrb-page-header-content">
                    <h1 class="wahrb-page-title">
                        <span class="wahrb-page-icon">📅</span>
                        <?php esc_html_e('My Bookings', 'wahra-rentals-bookings'); ?>
                    </h1>
                </div>
                <div class="wahrb-page-actions">
                    <a href="<?php echo esc_url(WAHRB_CSV_Exporter::get_export_url()); ?>" class="wahrb-btn wahrb-btn-secondary" style="margin-right: 10px;">
                        <span class="wahrb-btn-icon">📥</span>
                        <?php esc_html_e('Export CSV', 'wahra-rentals-bookings'); ?>
                    </a>
                    <button type="button" class="wahrb-btn wahrb-btn-secondary" id="wahrb-manual-booking-btn" style="margin-right: 10px;">
                        <span class="wahrb-btn-icon">✚</span>
                        <?php esc_html_e('Create booking', 'wahra-rentals-bookings'); ?>
                    </button>
                    <a href="<?php echo esc_url(wahrb_get_dashboard_url('wizard')); ?>" class="wahrb-btn wahrb-btn-primary">
                        <span class="wahrb-btn-icon">+</span>
                        <?php esc_html_e('New rental item', 'wahra-rentals-bookings'); ?>
                    </a>
                </div>
            </header>

            <!-- Status Tabs -->
            <div class="wahrb-bookings-wrapper">
                <nav class="wahrb-tabs" role="tablist">
                    <?php foreach ($status_filters as $filter_key => $filter):
                        $tab_args = $preserved_args;
                        if ($filter_key) {
                            $tab_args['status'] = $filter_key;
                        }
                        $tab_url = $tab_args ? add_query_arg($tab_args, $tabs_base_url) : $tabs_base_url;
                    ?>
                        <a href="<?php echo esc_url($tab_url); ?>"
                           class="wahrb-tab <?php echo esc_attr( ($status === $filter_key) ? 'active' : '' ); ?>"
                           role="tab"
                           aria-selected="<?php echo esc_attr( ($status === $filter_key) ? 'true' : 'false' ); ?>">
                            <span class="wahrb-tab-icon"><?php echo esc_html($filter['icon']); ?></span>
                            <span class="wahrb-tab-label"><?php echo esc_html($filter['label']); ?></span>
                            <?php if ($filter['count'] > 0): ?>
                                <span class="wahrb-tab-count"><?php echo esc_html($filter['count']); ?></span>
                            <?php endif; ?>
                        </a>
                    <?php endforeach; ?>
                </nav>

                <!-- ─── Filter bar ─── -->
                <div class="wahrb-filter-bar" id="wahrb-vendor-filters">
                    <?php if (count($products_with_bookings) > 0) : ?>
                    <div class="wahrb-filter-group">
                        <label><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></label>
                        <select id="wahrb-vf-product">
                            <option value=""><?php esc_html_e('All products', 'wahra-rentals-bookings'); ?></option>
                            <?php foreach ($products_with_bookings as $pw) : ?>
                                <option value="<?php echo esc_attr($pw['product_id']); ?>" <?php selected($filter_product, (int) $pw['product_id']); ?>>
                                    <?php echo esc_html($pw['product_name']); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <?php endif; ?>
                    <div class="wahrb-filter-group">
                        <label><?php esc_html_e('From', 'wahra-rentals-bookings'); ?></label>
                        <input type="date" id="wahrb-vf-date-from" value="<?php echo esc_attr($filter_date_from); ?>">
                    </div>
                    <div class="wahrb-filter-group">
                        <label><?php esc_html_e('To', 'wahra-rentals-bookings'); ?></label>
                        <input type="date" id="wahrb-vf-date-to" value="<?php echo esc_attr($filter_date_to); ?>">
                    </div>
                    <div class="wahrb-filter-group">
                        <label><?php esc_html_e('Min', 'wahra-rentals-bookings'); ?></label>
                        <input type="number" id="wahrb-vf-amount-min" step="0.01" min="0" value="<?php echo esc_attr($filter_amount_min); ?>" placeholder="0">
                    </div>
                    <div class="wahrb-filter-group">
                        <label><?php esc_html_e('Max', 'wahra-rentals-bookings'); ?></label>
                        <input type="number" id="wahrb-vf-amount-max" step="0.01" min="0" value="<?php echo esc_attr($filter_amount_max); ?>" placeholder="∞">
                    </div>
                    <div class="wahrb-filter-actions">
                        <button type="button" class="wahrb-btn wahrb-btn-primary wahrb-btn-sm" id="wahrb-apply-filters"><?php esc_html_e('Filter', 'wahra-rentals-bookings'); ?></button>
                        <?php if ($has_extra_filters) : ?>
                            <a href="<?php echo esc_url($status ? add_query_arg('status', $status, $tabs_base_url) : $tabs_base_url); ?>" class="wahrb-btn wahrb-btn-secondary wahrb-btn-sm"><?php esc_html_e('Reset', 'wahra-rentals-bookings'); ?></a>
                        <?php endif; ?>
                    </div>
                </div>
                <?php if ($has_extra_filters) : ?>
                    <div class="wahrb-filter-indicator">
                        <?php
                        printf(
                            /* translators: %d: number of bookings found */
                            esc_html__('%d booking(s) found with current filters', 'wahra-rentals-bookings'),
                            count($bookings)
                        );
                        ?>
                    </div>
                <?php endif; ?>

                <!-- Bookings Table -->
                <div class="wahrb-table-container">
                    <table class="wahrb-bookings-table">
                        <thead>
                            <tr>
                                <th class="wahrb-col-id"><?php esc_html_e('N°', 'wahra-rentals-bookings'); ?></th>
                                <th class="wahrb-col-product"><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></th>
                                <th class="wahrb-col-customer"><?php esc_html_e('Customer', 'wahra-rentals-bookings'); ?></th>
                                <th class="wahrb-col-dates"><?php esc_html_e('Dates', 'wahra-rentals-bookings'); ?></th>
                                <th class="wahrb-col-amount"><?php esc_html_e('Amount', 'wahra-rentals-bookings'); ?></th>
                                <th class="wahrb-col-status"><?php esc_html_e('Status', 'wahra-rentals-bookings'); ?></th>
                                <th class="wahrb-col-actions"><?php esc_html_e('Actions', 'wahra-rentals-bookings'); ?></th>
                            </tr>
                        </thead>
                        <tbody id="wahrb-bookings-list">
                            <?php if (empty($bookings)): ?>
                                <!-- Empty State -->
                                <tr class="wahrb-empty-row">
                                    <td colspan="7">
                                        <div class="wahrb-empty-state">
                                            <div class="wahrb-empty-state-icon">📅</div>
                                            <h3><?php esc_html_e('No bookings', 'wahra-rentals-bookings'); ?></h3>
                                            <p><?php esc_html_e('You don\'t have any reservations for this category yet.', 'wahra-rentals-bookings'); ?></p>
                                        </div>
                                    </td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($bookings as $booking): 
                                    $booking_status = $booking['status'] ?? 'pending';
                                    $status_label = $status_labels[$booking_status] ?? ucfirst($booking_status);
                                ?>
                                    <tr data-booking-id="<?php echo esc_attr($booking['booking_id']); ?>">
                                        <td class="wahrb-col-id"><?php echo esc_html($booking['booking_number'] ?? '#' . $booking['booking_id']); ?></td>
                                        <td class="wahrb-col-product"><?php echo esc_html($booking['product_name'] ?? 'Product #' . $booking['product_id']); ?></td>
                                        <td class="wahrb-col-customer">
                                            <?php echo esc_html($booking['customer_name'] ?? 'Customer'); ?>
                                            <?php if (!empty($booking['customer_email'])): ?>
                                                <br><small style="color: #666;"><?php echo esc_html($booking['customer_email']); ?></small>
                                            <?php endif; ?>
                                        </td>
                                        <td class="wahrb-col-dates">
                                            <?php 
                                            echo esc_html(date_i18n('d/m/Y', strtotime($booking['start_dt']))); 
                                            echo ' &rarr; '; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe HTML entity
                                            echo esc_html(date_i18n('d/m/Y', strtotime($booking['end_dt'])));
                                            ?>
                                        </td>
                                        <td class="wahrb-col-amount"><?php echo wp_kses_post(wc_price($booking['ps_total'] ?? $booking['total_amount'] ?? 0)); ?></td>
                                        <td class="wahrb-col-status">
                                            <span class="wahrb-status wahrb-status-<?php echo esc_attr($booking_status); ?>">
                                                <?php echo esc_html($status_label); ?>
                                            </span>
                                        </td>
                                        <td class="wahrb-col-actions">
                                            <div class="wahrb-actions">
                                                <?php if ($booking_status === 'pending'): ?>
                                                    <button class="wahrb-action-btn wahrb-confirm-btn" data-id="<?php echo esc_attr($booking['booking_id']); ?>" title="<?php esc_attr_e('Confirm', 'wahra-rentals-bookings'); ?>">✓</button>
                                                    <button class="wahrb-action-btn wahrb-cancel-btn" data-id="<?php echo esc_attr($booking['booking_id']); ?>" title="<?php esc_attr_e('Cancel', 'wahra-rentals-bookings'); ?>">✕</button>
                                                <?php elseif ($booking_status === 'confirmed'): ?>
                                                    <button class="wahrb-action-btn wahrb-start-btn" data-id="<?php echo esc_attr($booking['booking_id']); ?>" title="<?php esc_attr_e('Start now', 'wahra-rentals-bookings'); ?>">▶</button>
                                                    <button class="wahrb-action-btn wahrb-cancel-btn" data-id="<?php echo esc_attr($booking['booking_id']); ?>" title="<?php esc_attr_e('Cancel', 'wahra-rentals-bookings'); ?>">✕</button>
                                                <?php elseif ($booking_status === 'checked_in'): ?>
                                                    <button class="wahrb-action-btn wahrb-return-btn" data-id="<?php echo esc_attr($booking['booking_id']); ?>" title="<?php esc_attr_e('Mark returned', 'wahra-rentals-bookings'); ?>">🔄</button>
                                                    <button class="wahrb-action-btn wahrb-cancel-btn" data-id="<?php echo esc_attr($booking['booking_id']); ?>" title="<?php esc_attr_e('Cancel', 'wahra-rentals-bookings'); ?>">✕</button>
                                                <?php elseif ($booking_status === 'checked_out'): ?>
                                                    <button class="wahrb-action-btn wahrb-complete-btn" data-id="<?php echo esc_attr($booking['booking_id']); ?>" title="<?php esc_attr_e('Complete', 'wahra-rentals-bookings'); ?>">✓</button>
                                                <?php endif; ?>
                                                <a class="wahrb-action-btn wahrb-view-btn" href="<?php echo esc_url(wahrb_get_vendor_dashboard_url('booking-detail', ['booking_id' => $booking['booking_id']])); ?>" title="<?php esc_attr_e('View details', 'wahra-rentals-bookings'); ?>">👁</a>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>

        </article>
    </div>

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

<?php
$bookings_css_1 = '.wahrb-bookings-page{font-family:-apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;}.wahrb-page-header{display:flex;align-items:center;justify-content:space-between;gap:1rem;margin-bottom:1.5rem;flex-wrap:wrap;}.wahrb-page-title{display:flex;align-items:center;gap:0.75rem;margin:0;font-size:1.5rem;font-weight:600;color:var(--wahrb-gray-900, #0f172a);}.wahrb-page-icon{font-size:1.5rem;}.wahrb-btn{display:inline-flex;align-items:center;justify-content:center;gap:0.5rem;padding:0.625rem 1.25rem;font-size:0.875rem;font-weight:500;text-decoration:none;border:none;border-radius:0.5rem;cursor:pointer;}.wahrb-btn-primary{background:var(--wahrb-primary, #2563eb);color:#fff;}.wahrb-btn-primary:hover{background:var(--wahrb-primary-hover, #1d4ed8);color:#fff;}.wahrb-btn-icon{font-weight:600;font-size:1rem;}.wahrb-bookings-wrapper{background:#fff;border:1px solid var(--wahrb-gray-200, #e2e8f0);border-radius:0.75rem;overflow:hidden;}.wahrb-tabs{display:flex;gap:0;padding:0 1rem;background:var(--wahrb-gray-50, #f8fafc);border-bottom:1px solid var(--wahrb-gray-200, #e2e8f0);overflow-x:auto;-webkit-overflow-scrolling:touch;scrollbar-width:none;-ms-overflow-style:none;}.wahrb-tabs::-webkit-scrollbar{display:none;}.wahrb-tab{display:inline-flex;align-items:center;gap:0.375rem;padding:0.875rem 1rem;font-size:0.875rem;font-weight:500;color:var(--wahrb-gray-600, #475569);text-decoration:none;white-space:nowrap;border-bottom:2px solid transparent;margin-bottom:-1px;transition:color 0.15s, border-color 0.15s;}.wahrb-tab:hover{color:var(--wahrb-gray-800, #1e293b);background:rgba(0,0,0,0.02);}.wahrb-tab.active{color:var(--wahrb-primary, #2563eb);border-bottom-color:var(--wahrb-primary, #2563eb);font-weight:600;}.wahrb-tab-icon{font-size:0.9375rem;}.wahrb-tab-count{display:inline-flex;align-items:center;justify-content:center;min-width:1.25rem;height:1.25rem;padding:0 0.375rem;font-size:0.6875rem;font-weight:600;border-radius:9999px;background:var(--wahrb-gray-200, #e2e8f0);color:var(--wahrb-gray-600, #475569);line-height:1;}.wahrb-tab.active .wahrb-tab-count{background:var(--wahrb-primary, #2563eb);color:#fff;}.wahrb-table-container{overflow-x:auto;}.wahrb-bookings-table{width:100%;border-collapse:collapse;font-size:0.875rem;}.wahrb-bookings-table th,.wahrb-bookings-table td{padding:0.875rem 1rem;text-align:left;border-bottom:1px solid var(--wahrb-gray-100, #f1f5f9);}.wahrb-bookings-table th{background:var(--wahrb-gray-50, #f8fafc);font-weight:600;color:var(--wahrb-gray-600, #475569);text-transform:uppercase;font-size:0.6875rem;letter-spacing:0.05em;position:sticky;top:0;z-index:1;}.wahrb-bookings-table tbody tr:hover{background:var(--wahrb-gray-50, #f8fafc);}.wahrb-bookings-table tbody tr:last-child td{border-bottom:none;}.wahrb-col-id{width:80px;}.wahrb-col-status{width:120px;}.wahrb-col-actions{width:100px;text-align:right;}.wahrb-empty-row td{padding:0 !important;border:none !important;}.wahrb-empty-state{display:flex;flex-direction:column;align-items:center;padding:4rem 2rem;text-align:center;}.wahrb-empty-state-icon{font-size:3rem;margin-bottom:1rem;opacity:0.8;}.wahrb-empty-state h3{margin:0 0 0.5rem;font-size:1.125rem;font-weight:600;color:var(--wahrb-gray-700, #334155);}.wahrb-empty-state p{margin:0 0 1.5rem;color:var(--wahrb-gray-500, #64748b);max-width:360px;}.wahrb-status{display:inline-flex;align-items:center;padding:0.25rem 0.625rem;border-radius:9999px;font-size:0.6875rem;font-weight:600;text-transform:uppercase;letter-spacing:0.025em;}.wahrb-status-pending{background:#fffbeb;color:#b45309;}.wahrb-status-confirmed{background:#ecfdf5;color:#047857;}.wahrb-status-active{background:#f0f9ff;color:#0369a1;}.wahrb-status-completed{background:#eff6ff;color:#2563eb;}.wahrb-status-cancelled{background:#fef2f2;color:#b91c1c;}.wahrb-actions{display:flex;justify-content:flex-end;gap:0.375rem;}.wahrb-action-btn{display:inline-flex;align-items:center;justify-content:center;width:32px;height:32px;padding:0;background:var(--wahrb-gray-100, #f1f5f9);color:var(--wahrb-gray-600, #475569);border:none;border-radius:0.375rem;cursor:pointer;font-size:0.875rem;text-decoration:none;}.wahrb-action-btn:hover{background:var(--wahrb-gray-200, #e2e8f0);color:var(--wahrb-gray-800, #1e293b);}@media (max-width:768px){.wahrb-page-header{flex-direction:column;align-items:flex-start;}.wahrb-bookings-table{min-width:700px;}.wahrb-tabs{padding:0 0.75rem;scrollbar-width:thin;-ms-overflow-style:auto;}.wahrb-tabs::-webkit-scrollbar{display:block;height:3px;}.wahrb-tabs::-webkit-scrollbar-thumb{background:#cbd5e1;border-radius:3px;}.wahrb-tab{padding:0.75rem;}.wahrb-tab-label{display:none;}.wahrb-tab-count{font-size:0.625rem;min-width:1rem;height:1rem;padding:0 0.25rem;}}';
wp_add_inline_style('wahrb-vendor-styles', $bookings_css_1);

$bookings_css_fix = '
.wahrb-tab,.wahrb-tab:visited,.wahrb-tab:link,.wahrb-tab:active{background:transparent !important;text-decoration:none !important;}
.wahrb-tab.active,.wahrb-tab.active:visited,.wahrb-tab.active:link{color:var(--wahrb-primary, #2563eb) !important;background:transparent !important;}
.wahrb-filter-bar{display:flex;flex-wrap:wrap;align-items:flex-end;gap:12px;padding:12px 16px;background:var(--wahrb-gray-50, #f8fafc);border-bottom:1px solid var(--wahrb-gray-200, #e2e8f0);}
.wahrb-filter-group{display:flex;flex-direction:column;gap:3px;}
.wahrb-filter-group label{font-size:0.6875rem;font-weight:600;color:var(--wahrb-gray-500, #64748b);text-transform:uppercase;letter-spacing:0.03em;}
.wahrb-filter-group select,.wahrb-filter-group input{height:34px;min-width:120px;padding:0 8px;font-size:0.8125rem;border:1px solid var(--wahrb-gray-300, #cbd5e1);border-radius:6px;background:#fff;color:var(--wahrb-gray-800, #1e293b);}
.wahrb-filter-group select{min-width:150px;padding-right:28px;appearance:none;background-image:url("data:image/svg+xml,%3csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' viewBox=\'0 0 20 20\'%3e%3cpath stroke=\'%236b7280\' stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'1.5\' d=\'M6 8l4 4 4-4\'/%3e%3c/svg%3e");background-repeat:no-repeat;background-position:right 6px center;background-size:14px;}
.wahrb-filter-group input[type="number"]{min-width:80px;max-width:100px;}
.wahrb-filter-group input[type="date"]{min-width:130px;}
.wahrb-filter-actions{display:flex;gap:8px;align-items:flex-end;padding-bottom:1px;}
.wahrb-btn-sm{padding:0.4rem 0.875rem !important;font-size:0.8125rem !important;height:34px;}
.wahrb-filter-indicator{padding:8px 16px;font-size:0.8125rem;color:var(--wahrb-primary, #2563eb);background:#eff6ff;border-bottom:1px solid var(--wahrb-gray-200, #e2e8f0);}
@media(max-width:768px){.wahrb-filter-bar{flex-direction:column;align-items:stretch;}.wahrb-filter-group select,.wahrb-filter-group input{min-width:100%;}}
';
wp_add_inline_style('wahrb-vendor-styles', $bookings_css_fix);
?>

<!-- Manual Booking Modal -->
<div id="wahrb-manual-booking-modal" class="wahrb-modal" style="display:none;">
    <div class="wahrb-modal-content">
        <div class="wahrb-modal-header">
            <h3><?php esc_html_e('New manual booking', 'wahra-rentals-bookings'); ?></h3>
            <span class="wahrb-close">&times;</span>
        </div>
        <div class="wahrb-modal-body">
            <form id="wahrb-manual-booking-form">
                <div class="wahrb-form-group">
                    <label><?php esc_html_e('Product', 'wahra-rentals-bookings'); ?></label>
                    <select name="product_id" id="wahrb_mb_product" required class="wahrb-form-control">
                        <option value=""><?php esc_html_e('Loading...', 'wahra-rentals-bookings'); ?></option>
                    </select>
                </div>
                
                <div class="wahrb-form-row">
                    <div class="wahrb-form-group">
                        <label><?php esc_html_e('Start date', 'wahra-rentals-bookings'); ?></label>
                        <input type="text" name="start_date" id="wahrb-mb-start" required class="wahrb-form-control" placeholder="<?php esc_attr_e('Select a product first', 'wahra-rentals-bookings'); ?>" readonly>
                    </div>
                    <div class="wahrb-form-group">
                        <label><?php esc_html_e('End date', 'wahra-rentals-bookings'); ?></label>
                        <input type="text" name="end_date" id="wahrb-mb-end" required class="wahrb-form-control" placeholder="<?php esc_attr_e('Select a product first', 'wahra-rentals-bookings'); ?>" readonly>
                    </div>
                </div>
                <div id="wahrb-mb-dates-hint" class="wahrb-mb-dates-hint" style="display:none;"></div>

                <div class="wahrb-form-group">
                    <label><?php esc_html_e('Quantity', 'wahra-rentals-bookings'); ?></label>
                    <input type="number" name="qty" value="1" min="1" required class="wahrb-form-control">
                </div>

                <hr>

                <div class="wahrb-form-group">
                    <label><?php esc_html_e('Customer name (Optional)', 'wahra-rentals-bookings'); ?></label>
                    <input type="text" name="customer_name" class="wahrb-form-control">
                </div>
                <div class="wahrb-form-group">
                    <label><?php esc_html_e('Customer email (Optional)', 'wahra-rentals-bookings'); ?></label>
                    <input type="email" name="customer_email" class="wahrb-form-control">
                </div>

                <div class="wahrb-form-group">
                    <label><?php esc_html_e('Status', 'wahra-rentals-bookings'); ?></label>
                    <select name="status" class="wahrb-form-control">
                        <option value="confirmed"><?php esc_html_e('Confirmed', 'wahra-rentals-bookings'); ?></option>
                        <option value="pending"><?php esc_html_e('Pending', 'wahra-rentals-bookings'); ?></option>
                    </select>
                </div>
                
                <div class="wahrb-modal-footer">
                    <button type="submit" class="wahrb-btn wahrb-btn-primary"><?php esc_html_e('Create', 'wahra-rentals-bookings'); ?></button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    const manualModal = $('#wahrb-manual-booking-modal');
    const manualBtn = $('#wahrb-manual-booking-btn');
    const form = $('#wahrb-manual-booking-form');
    const apiBase = '<?php echo esc_url(rest_url('wahrb/v1')); ?>';
    const nonce = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    const currency = '<?php echo esc_js(html_entity_decode(get_woocommerce_currency_symbol(), ENT_QUOTES, "UTF-8")); ?>';

    // Status labels
    const statusLabels = {
        'pending': '<?php echo esc_js(__('Pending', 'wahra-rentals-bookings')); ?>',
        'confirmed': '<?php echo esc_js(__('Confirmed', 'wahra-rentals-bookings')); ?>',
        'checked_in': '<?php echo esc_js(__('In progress', 'wahra-rentals-bookings')); ?>',
        'checked_out': '<?php echo esc_js(__('Returned', 'wahra-rentals-bookings')); ?>',
        'completed': '<?php echo esc_js(__('Completed', 'wahra-rentals-bookings')); ?>',
        'cancelled': '<?php echo esc_js(__('Cancelled', 'wahra-rentals-bookings')); ?>'
    };

    const paymentStatusLabels = {
        'not_due': '<?php echo esc_js(__('Not due', 'wahra-rentals-bookings')); ?>',
        'pending': '<?php echo esc_js(__('Pending', 'wahra-rentals-bookings')); ?>',
        'paid': '<?php echo esc_js(__('Paid', 'wahra-rentals-bookings')); ?>',
        'failed': '<?php echo esc_js(__('Failed', 'wahra-rentals-bookings')); ?>',
        'refunded': '<?php echo esc_js(__('Refunded', 'wahra-rentals-bookings')); ?>',
        'partial': '<?php echo esc_js(__('Partial', 'wahra-rentals-bookings')); ?>',
        'authorized': '<?php echo esc_js(__('Authorized', 'wahra-rentals-bookings')); ?>',
        'captured': '<?php echo esc_js(__('Captured', 'wahra-rentals-bookings')); ?>',
        'released': '<?php echo esc_js(__('Released', 'wahra-rentals-bookings')); ?>',
        'forfeited': '<?php echo esc_js(__('Forfeited', 'wahra-rentals-bookings')); ?>',
        'partial_forfeited': '<?php echo esc_js(__('Partial forfeited', 'wahra-rentals-bookings')); ?>'
    };

    // Escape HTML to prevent XSS
    function esc(str) {
        if (str === null || str === undefined) return '';
        var div = document.createElement('div');
        div.appendChild(document.createTextNode(String(str)));
        return div.innerHTML;
    }

    function formatDate(dt) {
        if (!dt) return '-';
        return new Date(dt).toLocaleDateString('fr-FR', {day:'2-digit', month:'2-digit', year:'numeric'});
    }

    function formatDateTime(dt) {
        if (!dt) return '-';
        return new Date(dt).toLocaleString('fr-FR', {day:'2-digit', month:'2-digit', year:'numeric', hour:'2-digit', minute:'2-digit'});
    }

    function formatAmount(val) {
        return parseFloat(val || 0).toFixed(2) + ' ' + currency;
    }

    function payBadge(status) {
        const cls = {
            'not_due':'wahrb-pay-muted','pending':'wahrb-pay-warn','paid':'wahrb-pay-ok',
            'failed':'wahrb-pay-err','refunded':'wahrb-pay-info','partial':'wahrb-pay-warn',
            'authorized':'wahrb-pay-info','captured':'wahrb-pay-ok','released':'wahrb-pay-ok',
            'forfeited':'wahrb-pay-err','partial_forfeited':'wahrb-pay-warn'
        };
        return `<span class="wahrb-pay-badge ${cls[status]||'wahrb-pay-muted'}">${paymentStatusLabels[status]||esc(status)}</span>`;
    }

    // ========== ACTION BUTTON HANDLERS ==========
    
    // Confirm booking (pending → confirmed)
    $(document).on('click', '.wahrb-confirm-btn', function(e) {
        e.preventDefault();
        const id = $(this).attr('data-id');
        if (!id) return;
        if (confirm('<?php echo esc_js(__('Confirm this booking?', 'wahra-rentals-bookings')); ?>')) {
            updateBookingStatus(id, 'confirmed');
        }
    });

    // Start now (confirmed → checked_in)
    $(document).on('click', '.wahrb-start-btn', function(e) {
        e.preventDefault();
        const id = $(this).attr('data-id');
        if (!id) return;
        if (confirm('<?php echo esc_js(__('Start this rental now?', 'wahra-rentals-bookings')); ?>')) {
            doLifecycleAction(id, 'checkin', {notes: ''});
        }
    });

    // Return / Check-out (checked_in → checked_out)
    $(document).on('click', '.wahrb-return-btn', function(e) {
        e.preventDefault();
        const id = $(this).attr('data-id');
        if (!id) return;
        if (confirm('<?php echo esc_js(__('Mark this rental as returned?', 'wahra-rentals-bookings')); ?>')) {
            doLifecycleAction(id, 'checkout', {damage_amount: 0, damage_notes: ''});
        }
    });

    // Complete (checked_out → completed) — restitution validation
    $(document).on('click', '.wahrb-complete-btn', function(e) {
        e.preventDefault();
        const id = $(this).attr('data-id');
        if (!id) return;
        if (confirm('<?php echo esc_js(__('Complete this booking? Confirm that restitution has been validated.', 'wahra-rentals-bookings')); ?>')) {
            doLifecycleAction(id, 'complete', {notes: ''});
        }
    });

    // Cancel booking
    $(document).on('click', '.wahrb-cancel-btn', function(e) {
        e.preventDefault();
        const id = $(this).attr('data-id');
        if (!id) return;
        if (confirm('<?php echo esc_js(__('Are you sure you want to cancel this booking?', 'wahra-rentals-bookings')); ?>')) {
            updateBookingStatus(id, 'cancelled');
        }
    });

    // View booking details — navigates to dedicated booking-detail page (link in <a> tag)

    function updateBookingStatus(id, status) {
        $.ajax({
            url: apiBase + '/vendor/bookings/' + id,
            method: 'PUT',
            data: JSON.stringify({ status: status }),
            contentType: 'application/json',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', nonce); },
            success: function() { location.reload(); },
            error: function(xhr) {
                const msg = xhr.responseJSON ? xhr.responseJSON.message : 'Error';
                alert(msg);
            }
        });
    }

    function doLifecycleAction(id, action, data) {
        $.ajax({
            url: apiBase + '/vendor/bookings/' + id + '/' + action,
            method: 'POST',
            data: JSON.stringify(data || {}),
            contentType: 'application/json',
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', nonce); },
            success: function() { location.reload(); },
            error: function(xhr) {
                const msg = xhr.responseJSON ? xhr.responseJSON.message : 'Error';
                alert(msg);
            }
        });
    }

    // ========== MANUAL BOOKING MODAL ==========
    
    var mbBlockedDates = [];
    var fpStart = null;
    var fpEnd = null;
    var mbProductSelected = false;

    function destroyFlatpickrs() {
        if (fpStart) { fpStart.destroy(); fpStart = null; }
        if (fpEnd) { fpEnd.destroy(); fpEnd = null; }
    }

    function initFlatpickrs(blocked) {
        destroyFlatpickrs();
        var startEl = document.getElementById('wahrb-mb-start');
        var endEl = document.getElementById('wahrb-mb-end');
        if (!startEl || !endEl) return;

        fpStart = flatpickr(startEl, {
            dateFormat: 'Y-m-d',
            minDate: 'today',
            disable: blocked,
            locale: typeof flatpickr !== 'undefined' && flatpickr.l10ns && flatpickr.l10ns.fr ? 'fr' : 'default',
            allowInput: false,
            onChange: function(selectedDates) {
                if (selectedDates.length > 0) {
                    var nextDay = new Date(selectedDates[0]);
                    nextDay.setDate(nextDay.getDate() + 1);
                    fpEnd.set('minDate', nextDay);
                    // Clear end date if it's before the new start
                    var currentEnd = fpEnd.selectedDates[0];
                    if (currentEnd && currentEnd <= selectedDates[0]) {
                        fpEnd.clear();
                    }
                }
            },
            onDayCreate: function(dObj, dStr, fp, dayElem) {
                var dateStr = dayElem.dateObj.getFullYear() + '-' +
                    String(dayElem.dateObj.getMonth() + 1).padStart(2, '0') + '-' +
                    String(dayElem.dateObj.getDate()).padStart(2, '0');
                if (blocked.indexOf(dateStr) !== -1) {
                    dayElem.classList.add('wahrb-blocked-date');
                    dayElem.setAttribute('title', '<?php echo esc_js(__('Fully booked', 'wahra-rentals-bookings')); ?>');
                }
            }
        });

        fpEnd = flatpickr(endEl, {
            dateFormat: 'Y-m-d',
            minDate: 'today',
            disable: blocked,
            locale: typeof flatpickr !== 'undefined' && flatpickr.l10ns && flatpickr.l10ns.fr ? 'fr' : 'default',
            allowInput: false,
            onDayCreate: function(dObj, dStr, fp, dayElem) {
                var dateStr = dayElem.dateObj.getFullYear() + '-' +
                    String(dayElem.dateObj.getMonth() + 1).padStart(2, '0') + '-' +
                    String(dayElem.dateObj.getDate()).padStart(2, '0');
                if (blocked.indexOf(dateStr) !== -1) {
                    dayElem.classList.add('wahrb-blocked-date');
                    dayElem.setAttribute('title', '<?php echo esc_js(__('Fully booked', 'wahra-rentals-bookings')); ?>');
                }
            }
        });
    }

    function fetchBlockedDates(productId) {
        var hint = $('#wahrb-mb-dates-hint');
        if (!productId) {
            mbBlockedDates = [];
            mbProductSelected = false;
            destroyFlatpickrs();
            $('#wahrb-mb-start, #wahrb-mb-end').val('').attr('placeholder', '<?php echo esc_js(__('Select a product first', 'wahra-rentals-bookings')); ?>');
            hint.hide();
            return;
        }
        mbProductSelected = true;
        hint.html('<span class="wahrb-loading-spinner"></span> <?php echo esc_js(__('Loading availability...', 'wahra-rentals-bookings')); ?>').show();
        $('#wahrb-mb-start, #wahrb-mb-end').val('').attr('placeholder', '<?php echo esc_js(__('Loading...', 'wahra-rentals-bookings')); ?>');
        $.ajax({
            url: apiBase + '/blocked-dates',
            method: 'GET',
            dataType: 'json',
            data: { product_id: productId, months: 6 },
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', nonce); },
            success: function(response) {
                mbBlockedDates = response.blocked_dates || [];
                $('#wahrb-mb-start, #wahrb-mb-end').attr('placeholder', '<?php echo esc_js(__('Pick a date', 'wahra-rentals-bookings')); ?>');
                initFlatpickrs(mbBlockedDates);
                if (mbBlockedDates.length > 0) {
                    hint.html('⚠️ <?php echo esc_js(__('Red dates are fully booked and cannot be selected.', 'wahra-rentals-bookings')); ?>').show();
                } else {
                    hint.html('✅ <?php echo esc_js(__('All dates are available for this product.', 'wahra-rentals-bookings')); ?>').show();
                }
            },
            error: function() {
                mbBlockedDates = [];
                $('#wahrb-mb-start, #wahrb-mb-end').attr('placeholder', '<?php echo esc_js(__('Pick a date', 'wahra-rentals-bookings')); ?>');
                initFlatpickrs([]);
                hint.html('<?php echo esc_js(__('Could not load availability. Dates may still be validated on submission.', 'wahra-rentals-bookings')); ?>').show();
            }
        });
    }

    // When product changes, fetch blocked dates and re-init pickers
    $(document).on('change', '#wahrb_mb_product', function() {
        var productId = $(this).val();
        fetchBlockedDates(productId);
    });

    function loadProducts() {
        $.ajax({
            url: '<?php echo esc_url(rest_url('wahrb/v1/vendor/wizard/products')); ?>',
            method: 'GET',
            dataType: 'json',
            data: { rental_only: true },
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', nonce); },
            success: function(response) {
                const select = $('#wahrb_mb_product');
                select.empty();
                const products = Array.isArray(response) ? response : [];
                if (products.length === 0) {
                    select.append('<option value=""><?php esc_html_e('No rental products found', 'wahra-rentals-bookings'); ?></option>');
                    return;
                }
                select.append('<option value=""><?php esc_html_e('Select a product', 'wahra-rentals-bookings'); ?></option>');
                products.forEach(function(p) {
                    select.append(`<option value="${p.id}">${p.name}</option>`);
                });
            },
            error: function() {
                const select = $('#wahrb_mb_product');
                select.empty();
                select.append('<option value=""><?php esc_html_e('Error loading products', 'wahra-rentals-bookings'); ?></option>');
            }
        });
    }

    manualBtn.on('click', function() {
        manualModal.show();
        loadProducts();
        // Reset state
        mbBlockedDates = [];
        mbProductSelected = false;
        destroyFlatpickrs();
        $('#wahrb-mb-start, #wahrb-mb-end').val('').attr('placeholder', '<?php echo esc_js(__('Select a product first', 'wahra-rentals-bookings')); ?>');
        $('#wahrb-mb-dates-hint').hide();
    });

    $('.wahrb-close').on('click', function() {
        manualModal.hide();
    });

    $(window).on('click', function(event) {
        if ($(event.target).is(manualModal)) manualModal.hide();
    });

    // Validate date range doesn't span blocked dates
    function rangeHasBlockedDates(start, end, blocked) {
        if (!start || !end || blocked.length === 0) return false;
        var s = new Date(start + 'T00:00:00');
        var e = new Date(end + 'T00:00:00');
        for (var i = 0; i < blocked.length; i++) {
            var bd = new Date(blocked[i] + 'T00:00:00');
            if (bd >= s && bd <= e) return true;
        }
        return false;
    }

    form.on('submit', function(e) {
        e.preventDefault();
        var startVal = $('#wahrb-mb-start').val();
        var endVal = $('#wahrb-mb-end').val();
        // Front-end range validation
        if (rangeHasBlockedDates(startVal, endVal, mbBlockedDates)) {
            alert('<?php echo esc_js(__('The selected date range includes fully booked dates. Please choose different dates.', 'wahra-rentals-bookings')); ?>');
            return;
        }
        const data = {
            product_id: $('#wahrb_mb_product').val(),
            start_date: startVal,
            end_date: endVal,
            qty: $('input[name="qty"]').val(),
            status: $('select[name="status"]').val(),
            customer_data: {
                name: $('input[name="customer_name"]').val(),
                email: $('input[name="customer_email"]').val()
            }
        };
        $.ajax({
            url: apiBase + '/vendor/bookings',
            method: 'POST',
            data: data,
            beforeSend: function(xhr) { xhr.setRequestHeader('X-WP-Nonce', nonce); },
            success: function() {
                alert('<?php esc_html_e('Booking created!', 'wahra-rentals-bookings'); ?>');
                location.reload();
            },
            error: function(xhr) {
                const msg = xhr.responseJSON ? xhr.responseJSON.message : 'Error';
                alert(msg);
            }
        });
    });

    // ═══ Filter bar handler ═══
    $('#wahrb-apply-filters').on('click', function() {
        var base = '<?php echo esc_js($tabs_base_url); ?>';
        var params = {};
        var currentStatus = '<?php echo esc_js($status); ?>';
        if (currentStatus) params.status = currentStatus;
        var pv = $('#wahrb-vf-product').val();
        if (pv) params.product_id = pv;
        var df = $('#wahrb-vf-date-from').val();
        if (df) params.date_from = df;
        var dt = $('#wahrb-vf-date-to').val();
        if (dt) params.date_to = dt;
        var amin = $('#wahrb-vf-amount-min').val();
        if (amin !== '' && amin !== undefined) params.amount_min = amin;
        var amax = $('#wahrb-vf-amount-max').val();
        if (amax !== '' && amax !== undefined) params.amount_max = amax;
        var qs = Object.keys(params).map(function(k) {
            return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]);
        }).join('&');
        window.location.href = base + (qs ? '?' + qs : '');
    });
});
</script>

<?php
$bookings_css_2 = '
.wahrb-modal{display:none;position:fixed;z-index:99999;left:0;top:0;width:100%;height:100%;overflow:auto;background-color:rgba(0,0,0,0.4);}
.wahrb-modal-content{background-color:#fefefe;margin:5% auto;padding:0;border:none;width:500px;border-radius:12px;box-shadow:0 20px 60px rgba(0,0,0,0.15);}
.wahrb-detail-modal-content{width:680px;max-width:95vw;max-height:90vh;display:flex;flex-direction:column;}
.wahrb-detail-modal-content .wahrb-modal-body{overflow-y:auto;max-height:calc(90vh - 60px);}
.wahrb-modal-header{padding:1rem 1.25rem;border-bottom:1px solid #e2e8f0;display:flex;justify-content:space-between;align-items:center;}
.wahrb-modal-header h3{margin:0;font-size:1.125rem;font-weight:600;}
.wahrb-close{color:#94a3b8;font-size:24px;font-weight:bold;cursor:pointer;line-height:1;}
.wahrb-close:hover{color:#334155;}
.wahrb-modal-body{padding:1.25rem;}
.wahrb-form-group{margin-bottom:1rem;}
.wahrb-form-group label{display:block;margin-bottom:0.375rem;font-weight:500;font-size:0.8125rem;color:#475569;}
.wahrb-form-control{width:100%;padding:0.5rem 0.75rem;border:1px solid #cbd5e1;border-radius:0.375rem;font-size:0.875rem;color:#1e293b;}
textarea.wahrb-form-control{resize:vertical;}
.wahrb-form-row{display:flex;gap:1rem;}
.wahrb-form-row .wahrb-form-group{flex:1;}
.wahrb-modal-footer{margin-top:1.5rem;text-align:right;}
.wahrb-btn-secondary{background:#f1f5f9;color:#334155;border:1px solid #e2e8f0;}
.wahrb-btn-secondary:hover{background:#e2e8f0;}
.wahrb-btn-danger{background:#fef2f2;color:#b91c1c;border:1px solid #fecaca;}
.wahrb-btn-danger:hover{background:#fee2e2;}

/* Lifecycle timeline */
.wahrb-lifecycle-timeline{display:flex;align-items:center;justify-content:center;gap:0;padding:1rem 0.5rem 1.25rem;margin-bottom:0.75rem;border-bottom:1px solid #f1f5f9;}
.wahrb-timeline-step{display:flex;flex-direction:column;align-items:center;gap:0.25rem;min-width:60px;}
.wahrb-timeline-dot{width:36px;height:36px;border-radius:50%;background:#f1f5f9;display:flex;align-items:center;justify-content:center;font-size:1rem;border:2px solid #e2e8f0;transition:all 0.2s;}
.wahrb-timeline-step.done .wahrb-timeline-dot{background:#ecfdf5;border-color:#10b981;}
.wahrb-timeline-step.current .wahrb-timeline-dot{background:#eff6ff;border-color:#2563eb;box-shadow:0 0 0 3px rgba(37,99,235,0.15);}
.wahrb-timeline-label{font-size:0.625rem;font-weight:500;color:#94a3b8;text-align:center;white-space:nowrap;}
.wahrb-timeline-step.done .wahrb-timeline-label{color:#059669;}
.wahrb-timeline-step.current .wahrb-timeline-label{color:#2563eb;font-weight:600;}
.wahrb-timeline-line{flex:1;height:2px;background:#e2e8f0;min-width:12px;margin:0 -2px;margin-bottom:18px;}
.wahrb-timeline-line.done{background:#10b981;}
.wahrb-timeline-cancelled{text-align:center;font-size:1rem;font-weight:600;color:#b91c1c;padding:0.5rem;}

/* Detail grid */
.wahrb-detail-grid{display:grid;grid-template-columns:1fr 1fr;gap:1rem;}
.wahrb-detail-section{background:#f8fafc;border-radius:8px;padding:0.875rem;border:1px solid #f1f5f9;}
.wahrb-detail-section h4{margin:0 0 0.625rem;font-size:0.8125rem;font-weight:600;color:#334155;}
.wahrb-detail-row{display:flex;justify-content:space-between;align-items:center;padding:0.25rem 0;font-size:0.8125rem;}
.wahrb-detail-row span{color:#64748b;}
.wahrb-detail-row strong{color:#1e293b;font-weight:500;}
.wahrb-detail-full{grid-column:1/-1;margin-top:0.5rem;}

/* Events */
.wahrb-events-list{display:flex;flex-direction:column;gap:0.375rem;}
.wahrb-event-item{display:flex;align-items:center;gap:0.5rem;font-size:0.8125rem;color:#475569;}
.wahrb-event-icon{font-size:0.875rem;width:20px;text-align:center;}
.wahrb-event-date{margin-left:auto;color:#94a3b8;font-size:0.75rem;}
.wahrb-event-note{font-size:0.75rem;color:#64748b;background:#fff;padding:0.375rem 0.625rem;border-radius:4px;margin-left:1.75rem;font-style:italic;border-left:2px solid #e2e8f0;}

/* Payment tracking */
.wahrb-payment-section{background:#fffbeb;border-color:#fef3c7;}
.wahrb-pay-row{display:grid;grid-template-columns:1fr auto auto auto;gap:0.625rem;align-items:center;padding:0.5rem 0;border-bottom:1px solid rgba(0,0,0,0.05);}
.wahrb-pay-row:last-of-type{border-bottom:none;}
.wahrb-pay-label{font-size:0.8125rem;font-weight:500;color:#1e293b;}
.wahrb-pay-amount{font-size:0.8125rem;font-weight:600;color:#334155;white-space:nowrap;}
.wahrb-pay-badge{display:inline-flex;padding:0.125rem 0.5rem;border-radius:9999px;font-size:0.6875rem;font-weight:600;text-transform:uppercase;letter-spacing:0.025em;}
.wahrb-pay-ok{background:#dcfce7;color:#166534;}
.wahrb-pay-warn{background:#fef3c7;color:#92400e;}
.wahrb-pay-err{background:#fee2e2;color:#991b1b;}
.wahrb-pay-info{background:#dbeafe;color:#1e40af;}
.wahrb-pay-muted{background:#f1f5f9;color:#64748b;}
.wahrb-pay-select{padding:0.25rem 0.375rem;font-size:0.75rem;border:1px solid #cbd5e1;border-radius:4px;background:#fff;color:#1e293b;cursor:pointer;}
.wahrb-pay-meta{font-size:0.6875rem;color:#78716c;padding:0.125rem 0;}
.wahrb-pay-notes{background:#fff;padding:0.375rem 0.625rem;border-radius:4px;border-left:2px solid #f59e0b;margin-top:0.25rem;}
.wahrb-pay-total{display:flex;justify-content:space-between;align-items:center;padding:0.75rem 0 0;margin-top:0.5rem;border-top:2px solid rgba(0,0,0,0.1);font-size:0.875rem;}

/* Restitution */
.wahrb-restitution-section{background:#f0fdf4;border-color:#bbf7d0;}
.wahrb-restitution-info{font-size:0.8125rem;color:#166534;margin:0 0 0.75rem;line-height:1.4;}
.wahrb-restitution-actions{text-align:right;margin-top:0.75rem;}

/* Status pill additions */
.wahrb-status-checked_in{background:#dbeafe;color:#1e40af;}
.wahrb-status-checked_out{background:#fef3c7;color:#92400e;}

/* Modal action buttons */
.wahrb-modal-actions{display:flex;gap:0.75rem;justify-content:flex-end;padding-top:1rem;margin-top:0.75rem;border-top:1px solid #e2e8f0;}

/* Start button color */
.wahrb-start-btn{background:#dbeafe !important;color:#1e40af !important;}
.wahrb-start-btn:hover{background:#bfdbfe !important;}
.wahrb-return-btn{background:#fef3c7 !important;color:#92400e !important;}
.wahrb-return-btn:hover{background:#fde68a !important;}
.wahrb-complete-btn{background:#dcfce7 !important;color:#166534 !important;}
.wahrb-complete-btn:hover{background:#bbf7d0 !important;}

/* Spinner */
.wahrb-spinner{display:inline-block;width:24px;height:24px;border:3px solid #e2e8f0;border-top:3px solid #2563eb;border-radius:50%;animation:wahrb-spin 0.8s linear infinite;}
@keyframes wahrb-spin{to{transform:rotate(360deg);}}

/* Flatpickr blocked dates in manual booking */
.wahrb-blocked-date{background:#fee2e2 !important;border-color:#fca5a5 !important;}
.wahrb-blocked-date span{color:#991b1b !important;}
.wahrb-blocked-date:hover{background:#fecaca !important;}
.wahrb-blocked-date.flatpickr-disabled{text-decoration:line-through;opacity:0.7;}
.wahrb-mb-dates-hint{font-size:0.8125rem;padding:0.5rem 0.75rem;margin:-0.5rem 0 0.75rem;border-radius:6px;background:#fffbeb;border:1px solid #fde68a;color:#92400e;display:flex;align-items:center;gap:0.375rem;}
.wahrb-loading-spinner{display:inline-block;width:14px;height:14px;border:2px solid #e2e8f0;border-top:2px solid #2563eb;border-radius:50%;animation:wahrb-spin 0.8s linear infinite;vertical-align:middle;}
#wahrb-mb-start.flatpickr-input,#wahrb-mb-end.flatpickr-input{background:#fff;cursor:pointer;}
#wahrb-mb-start[readonly]:not(.flatpickr-input),#wahrb-mb-end[readonly]:not(.flatpickr-input){background:#f8fafc;color:#94a3b8;cursor:not-allowed;}
.wahrb-modal .flatpickr-calendar{z-index:100000 !important;}

@media(max-width:768px){
    .wahrb-detail-modal-content{width:100%;margin:0;border-radius:0;max-height:100vh;}
    .wahrb-detail-grid{grid-template-columns:1fr;}
    .wahrb-pay-row{grid-template-columns:1fr;gap:0.25rem;}
    .wahrb-lifecycle-timeline{flex-wrap:wrap;gap:0.25rem;}
    .wahrb-timeline-line{display:none;}
    .wahrb-modal-actions{flex-direction:column;}
}
';
wp_add_inline_style('wahrb-vendor-styles', $bookings_css_2);
?>
