<?php
/**
 * Dokan Vendor Calendar Template - Modern UI v2
 *
 * @package WahraRentalsBookings
 */

defined('ABSPATH') || exit;

$vendor_id = get_current_user_id();

// Fetch vendor products for filter (include all statuses for better filtering)
$products = wc_get_products([
    'author' => $vendor_id,
    'limit'  => -1,
    'status' => 'publish',
]);
?>

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

    <div class="dokan-dashboard-content">
        <article class="dokan-product-listing-area wahrb-calendar-page">
            
            <!-- Compact Header + Toolbar -->
            <div class="wahrb-cal-toolbar">
                <div class="wahrb-cal-toolbar-left">
                    <h1 class="wahrb-cal-title">
                        <svg class="wahrb-cal-icon" width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                        <?php esc_html_e('Bookings Calendar', 'wahra-rentals-bookings'); ?>
                    </h1>
                </div>
                <div class="wahrb-cal-toolbar-right">
                    <div class="wahrb-cal-filter">
                        <label class="wahrb-cal-filter-label">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polygon points="22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3"/></svg>
                        </label>
                        <select id="wahrb_calendar_product_filter" class="wahrb-cal-select">
                            <option value="all"><?php esc_html_e('All products', 'wahra-rentals-bookings'); ?></option>
                            <?php foreach ($products as $product) : ?>
                                <option value="<?php echo esc_attr($product->get_id()); ?>"><?php echo esc_html($product->get_name()); ?></option>
                            <?php endforeach; ?>
                        </select>
                        <select id="wahrb_calendar_status_filter" class="wahrb-cal-select">
                            <option value="all"><?php esc_html_e('All statuses', 'wahra-rentals-bookings'); ?></option>
                            <option value="pending"><?php esc_html_e('Pending', 'wahra-rentals-bookings'); ?></option>
                            <option value="confirmed"><?php esc_html_e('Confirmed', 'wahra-rentals-bookings'); ?></option>
                            <option value="checked_in"><?php esc_html_e('Active', 'wahra-rentals-bookings'); ?></option>
                            <option value="checked_out"><?php esc_html_e('Returned', 'wahra-rentals-bookings'); ?></option>
                            <option value="completed"><?php esc_html_e('Completed', 'wahra-rentals-bookings'); ?></option>
                            <option value="cancelled"><?php esc_html_e('Cancelled', 'wahra-rentals-bookings'); ?></option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- Calendar Card -->
            <div class="wahrb-cal-card">
                <!-- Calendar Container -->
                <div id="wahrb-calendar-container">
                    <div id="wahrb-fullcalendar"></div>
                    <!-- Empty state (hidden by default, shown via JS) -->
                    <div id="wahrb-calendar-empty" class="wahrb-cal-empty" style="display:none;">
                        <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="color:var(--wahrb-gray-300,#cbd5e1)"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/><line x1="9" y1="16" x2="15" y2="16"/></svg>
                        <p><?php esc_html_e('No bookings found for this period.', 'wahra-rentals-bookings'); ?></p>
                    </div>
                </div>

                <!-- Legend Footer -->
                <div class="wahrb-cal-legend">
                    <span class="wahrb-cal-legend-item wahrb-legend-pending">
                        <span class="wahrb-cal-legend-dot"></span>
                        <?php esc_html_e('Pending', 'wahra-rentals-bookings'); ?>
                    </span>
                    <span class="wahrb-cal-legend-item wahrb-legend-confirmed">
                        <span class="wahrb-cal-legend-dot"></span>
                        <?php esc_html_e('Confirmed', 'wahra-rentals-bookings'); ?>
                    </span>
                    <span class="wahrb-cal-legend-item wahrb-legend-active">
                        <span class="wahrb-cal-legend-dot"></span>
                        <?php esc_html_e('Active', 'wahra-rentals-bookings'); ?>
                    </span>
                    <span class="wahrb-cal-legend-item wahrb-legend-checkout">
                        <span class="wahrb-cal-legend-dot"></span>
                        <?php esc_html_e('Returned', 'wahra-rentals-bookings'); ?>
                    </span>
                    <span class="wahrb-cal-legend-item wahrb-legend-completed">
                        <span class="wahrb-cal-legend-dot"></span>
                        <?php esc_html_e('Completed', 'wahra-rentals-bookings'); ?>
                    </span>
                    <span class="wahrb-cal-legend-item wahrb-legend-cancelled">
                        <span class="wahrb-cal-legend-dot"></span>
                        <?php esc_html_e('Cancelled', 'wahra-rentals-bookings'); ?>
                    </span>
                </div>
            </div>

        </article>
    </div>

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

<script>
document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('wahrb-fullcalendar');
    var emptyEl = document.getElementById('wahrb-calendar-empty');
    var filterSelect = document.getElementById('wahrb_calendar_product_filter');
    var statusSelect = document.getElementById('wahrb_calendar_status_filter');
    
    if (!calendarEl || typeof FullCalendar === 'undefined') {
        if (emptyEl) emptyEl.style.display = 'flex';
        return;
    }

    var wpNonce = '<?php echo esc_js(wp_create_nonce('wp_rest')); ?>';
    var lastEventCount = -1;
    
    var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        locale: '<?php echo esc_js(substr(get_user_locale(), 0, 2)); ?>',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,timeGridWeek,listWeek'
        },
        buttonText: {
            today: '<?php echo esc_js(__('Today', 'wahra-rentals-bookings')); ?>',
            month: '<?php echo esc_js(__('Month', 'wahra-rentals-bookings')); ?>',
            week: '<?php echo esc_js(__('Week', 'wahra-rentals-bookings')); ?>',
            list: '<?php echo esc_js(__('List', 'wahra-rentals-bookings')); ?>'
        },
        height: 'auto',
        contentHeight: 500,
        dayMaxEvents: 3,
        nowIndicator: true,
        navLinks: true,
        moreLinkContent: function(args) {
            return '+' + args.num;
        },
        events: function(info, successCallback, failureCallback) {
            var selectedVal = filterSelect ? filterSelect.value : 'all';
            var productIds = (selectedVal && selectedVal !== 'all') ? selectedVal : '';
            var selectedStatus = statusSelect ? statusSelect.value : 'all';
            
            jQuery.ajax({
                url: '<?php echo esc_url(rest_url('wahrb/v1/vendor/bookings/calendar')); ?>',
                method: 'GET',
                data: {
                    start: info.startStr,
                    end: info.endStr,
                    vendor_id: <?php echo esc_js($vendor_id); ?>,
                    product_ids: productIds,
                    status: selectedStatus
                },
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', wpNonce);
                },
                success: function(response) {
                    lastEventCount = response.length;
                    if (emptyEl) {
                        emptyEl.style.display = response.length === 0 ? 'flex' : 'none';
                    }
                    successCallback(response);
                },
                error: function(xhr) {
                    console.error('WAHRB Calendar: Failed to load events', xhr.status, xhr.responseText);
                    if (emptyEl) emptyEl.style.display = 'flex';
                    failureCallback(new Error('Failed to load calendar events'));
                }
            });
        },
        eventDidMount: function(info) {
            // Add tooltip with booking details
            if (info.event.extendedProps && info.event.extendedProps.tooltip) {
                info.el.title = info.event.extendedProps.tooltip;
            }
        },
        eventClick: function(info) {
            // Show booking detail in a simple popover
            var props = info.event.extendedProps || {};
            var popup = document.getElementById('wahrb-cal-popup');
            if (!popup) {
                popup = document.createElement('div');
                popup.id = 'wahrb-cal-popup';
                popup.className = 'wahrb-cal-popup';
                document.body.appendChild(popup);
            }
            var 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(__('Active', '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')); ?>'
            };
            var status = props.status || 'pending';
            var statusLabel = statusLabels[status] || status;
            popup.innerHTML = '<div class="wahrb-cal-popup-header">' +
                '<strong>' + (info.event.title || '') + '</strong>' +
                '<button onclick="this.parentNode.parentNode.style.display=\'none\'" class="wahrb-cal-popup-close">&times;</button>' +
                '</div>' +
                '<div class="wahrb-cal-popup-body">' +
                '<div class="wahrb-cal-popup-row"><span class="wahrb-cal-popup-label"><?php echo esc_js(__('Status', 'wahra-rentals-bookings')); ?></span><span class="wahrb-cal-popup-badge wahrb-badge-' + status + '">' + statusLabel + '</span></div>' +
                (props.customer_name ? '<div class="wahrb-cal-popup-row"><span class="wahrb-cal-popup-label"><?php echo esc_js(__('Customer', 'wahra-rentals-bookings')); ?></span><span>' + props.customer_name + '</span></div>' : '') +
                (props.total ? '<div class="wahrb-cal-popup-row"><span class="wahrb-cal-popup-label"><?php echo esc_js(__('Total', 'wahra-rentals-bookings')); ?></span><span class="wahrb-cal-popup-price">' + props.total + ' DT</span></div>' : '') +
                '</div>';
            
            var rect = info.el.getBoundingClientRect();
            popup.style.display = 'block';
            popup.style.top = (rect.bottom + window.scrollY + 8) + 'px';
            popup.style.left = Math.min(rect.left + window.scrollX, window.innerWidth - 280) + 'px';
            
            // Close on outside click
            setTimeout(function() {
                document.addEventListener('click', function closePopup(e) {
                    if (!popup.contains(e.target) && !info.el.contains(e.target)) {
                        popup.style.display = 'none';
                        document.removeEventListener('click', closePopup);
                    }
                });
            }, 10);
        }
    });

    calendar.render();

    // Refetch events when filter changes
    if (filterSelect) {
        filterSelect.addEventListener('change', function() {
            calendar.refetchEvents();
        });
    }
    if (statusSelect) {
        statusSelect.addEventListener('change', function() {
            calendar.refetchEvents();
        });
    }

    // Close popup on view change
    calendar.on('datesSet', function() {
        var popup = document.getElementById('wahrb-cal-popup');
        if (popup) popup.style.display = 'none';
    });
});
</script>

<?php
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- CSS only, no user data
$calendar_page_css = <<<'CALPAGECSS'
/* Calendar Page Layout */
.wahrb-calendar-page{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;}

/* Toolbar */
.wahrb-cal-toolbar{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:0.75rem;margin-bottom:1rem;padding:0;}
.wahrb-cal-toolbar-left{display:flex;align-items:center;gap:0.5rem;}
.wahrb-cal-title{margin:0;font-size:1.25rem;font-weight:600;color:var(--wahrb-gray-900,#0f172a);display:flex;align-items:center;gap:0.5rem;}
.wahrb-cal-icon{color:var(--wahrb-primary,#2563eb);flex-shrink:0;}
.wahrb-cal-toolbar-right{display:flex;align-items:center;gap:0.75rem;}

/* Filter — compact single dropdown */
.wahrb-cal-filter{display:flex;align-items:center;gap:0.5rem;}
.wahrb-cal-filter-label{display:flex;align-items:center;color:var(--wahrb-gray-500,#64748b);}
.wahrb-cal-select{appearance:auto;padding:0.4rem 2rem 0.4rem 0.75rem;font-size:0.8125rem;font-weight:500;color:var(--wahrb-gray-700,#334155);background:var(--wahrb-white,#fff);border:1px solid var(--wahrb-gray-300,#cbd5e1);border-radius:0.375rem;cursor:pointer;max-width:240px;text-overflow:ellipsis;}
.wahrb-cal-select:focus{outline:none;border-color:var(--wahrb-primary,#2563eb);box-shadow:0 0 0 2px rgba(37,99,235,.15);}

/* Calendar Card */
.wahrb-cal-card{background:var(--wahrb-white,#fff);border:1px solid var(--wahrb-gray-200,#e2e8f0);border-radius:0.75rem;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,.04);}
.wahrb-cal-card #wahrb-calendar-container{padding:1rem 1.25rem;min-height:480px;position:relative;}
.wahrb-cal-card #wahrb-fullcalendar{min-height:460px;}

/* Empty state */
.wahrb-cal-empty{display:flex;flex-direction:column;align-items:center;justify-content:center;min-height:300px;gap:0.75rem;color:var(--wahrb-gray-400,#94a3b8);font-size:0.875rem;}

/* Legend Footer */
.wahrb-cal-legend{display:flex;flex-wrap:wrap;gap:1rem;padding:0.625rem 1.25rem;background:var(--wahrb-gray-50,#f8fafc);border-top:1px solid var(--wahrb-gray-200,#e2e8f0);align-items:center;}
.wahrb-cal-legend-item{display:inline-flex;align-items:center;gap:0.375rem;font-size:0.75rem;color:var(--wahrb-gray-600,#475569);white-space:nowrap;}
.wahrb-cal-legend-dot{width:10px;height:10px;border-radius:2px;border-left:3px solid;display:inline-block;}
.wahrb-legend-pending .wahrb-cal-legend-dot{background:#fffbeb;border-left-color:#f59e0b;}
.wahrb-legend-confirmed .wahrb-cal-legend-dot{background:#ecfdf5;border-left-color:#10b981;}
.wahrb-legend-active .wahrb-cal-legend-dot{background:#f0f9ff;border-left-color:#0ea5e9;}
.wahrb-legend-checkout .wahrb-cal-legend-dot{background:#fef3c7;border-left-color:#d97706;}
.wahrb-legend-completed .wahrb-cal-legend-dot{background:#f1f5f9;border-left-color:#64748b;}
.wahrb-legend-cancelled .wahrb-cal-legend-dot{background:#fef2f2;border-left-color:#ef4444;}

/* Popup */
.wahrb-cal-popup{display:none;position:absolute;z-index:10001;width:260px;background:#fff;border:1px solid var(--wahrb-gray-200,#e2e8f0);border-radius:0.5rem;box-shadow:0 10px 25px rgba(0,0,0,.12);overflow:hidden;font-size:0.8125rem;}
.wahrb-cal-popup-header{display:flex;justify-content:space-between;align-items:center;padding:0.75rem 1rem;background:var(--wahrb-gray-50,#f8fafc);border-bottom:1px solid var(--wahrb-gray-200,#e2e8f0);}
.wahrb-cal-popup-header strong{font-size:0.8125rem;color:var(--wahrb-gray-800,#1e293b);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:200px;}
.wahrb-cal-popup-close{border:none;background:none;font-size:1.25rem;color:var(--wahrb-gray-400,#94a3b8);cursor:pointer;padding:0;line-height:1;}
.wahrb-cal-popup-close:hover{color:var(--wahrb-gray-700,#334155);}
.wahrb-cal-popup-body{padding:0.75rem 1rem;}
.wahrb-cal-popup-row{display:flex;justify-content:space-between;align-items:center;padding:0.25rem 0;}
.wahrb-cal-popup-row:not(:last-child){border-bottom:1px dashed var(--wahrb-gray-100,#f1f5f9);}
.wahrb-cal-popup-label{color:var(--wahrb-gray-500,#64748b);}
.wahrb-cal-popup-price{font-weight:600;color:var(--wahrb-primary,#2563eb);}
.wahrb-cal-popup-badge{font-size:0.6875rem;font-weight:600;padding:0.125rem 0.5rem;border-radius:999px;text-transform:uppercase;letter-spacing:0.025em;}
.wahrb-badge-pending{background:#fffbeb;color:#b45309;}
.wahrb-badge-confirmed{background:#ecfdf5;color:#047857;}
.wahrb-badge-checked_in{background:#f0f9ff;color:#0369a1;}
.wahrb-badge-checked_out{background:#fef3c7;color:#92400e;}
.wahrb-badge-completed{background:#f1f5f9;color:#475569;}
.wahrb-badge-cancelled{background:#fef2f2;color:#b91c1c;}

/* Responsive */
@media (max-width:768px){
  .wahrb-cal-toolbar{flex-direction:column;align-items:flex-start;}
  .wahrb-cal-select{max-width:100%;width:100%;}
  .wahrb-cal-card #wahrb-calendar-container{padding:0.75rem;min-height:360px;}
  .wahrb-cal-card #wahrb-fullcalendar{min-height:340px;}
  .wahrb-cal-legend{gap:0.5rem;padding:0.5rem 0.75rem;}
  .wahrb-cal-legend-item{font-size:0.6875rem;}
}
CALPAGECSS;
wp_add_inline_style('wahrb-calendar-styles', wp_strip_all_tags($calendar_page_css));
?>
