<?php
/**
 * Bookings List View
 *
 * @package Freelance_Studio
 */

if (!defined('ABSPATH')) {
    exit;
}

$bookings = $data['bookings'];
$meeting_types = $data['meeting_types'];
$current_view = $data['current_view'];
$upcoming_bookings = isset($data['upcoming_bookings']) ? $data['upcoming_bookings'] : array();
$calendar_data = isset($data['calendar_data']) ? $data['calendar_data'] : array();

// Calendar data
$cal_year = isset($calendar_data['year']) ? $calendar_data['year'] : gmdate('Y');
$cal_month = isset($calendar_data['month']) ? $calendar_data['month'] : gmdate('n');
$cal_events = isset($calendar_data['events']) ? $calendar_data['events'] : array();
$today = gmdate('Y-m-d');

// Group events by date
$events_by_date = array();
foreach ($cal_events as $event) {
    $date = $event['date'];
    if (!isset($events_by_date[$date])) {
        $events_by_date[$date] = array();
    }
    $events_by_date[$date][] = $event;
}

// Calculate calendar grid
$first_day_of_month = mktime(0, 0, 0, $cal_month, 1, $cal_year);
$days_in_month = gmdate('t', $first_day_of_month);
$day_of_week = gmdate('N', $first_day_of_month);
$month_name = gmdate('F', $first_day_of_month);

// Navigation
$prev_month = $cal_month - 1;
$prev_year = $cal_year;
if ($prev_month < 1) { $prev_month = 12; $prev_year--; }
$next_month = $cal_month + 1;
$next_year = $cal_year;
if ($next_month > 12) { $next_month = 1; $next_year++; }
?>

<div class="wrap fs-wrap">
    <h1 class="fs-page-title"><?php esc_html_e('Bookings', 'freelance-studio'); ?></h1>
    
    <?php if (isset($_GET['cancelled'])): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e('Booking cancelled successfully.', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>
    
    <!-- Mobile Tab Dropdown Navigation (auto-converted by JS) -->
    <?php 
    $current_tab = isset($_GET['tab']) ? $_GET['tab'] : 'bookings';
    ?>
    <div class="fs-tab-nav fs-bookings-tab-nav fs-mobile-only">
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'bookings' ? 'active' : '' ); ?>">
            <?php esc_html_e('Bookings', 'freelance-studio'); ?>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&tab=meeting-types') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'meeting-types' ? 'active' : '' ); ?>">
            <?php esc_html_e('Meeting Types', 'freelance-studio'); ?>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&tab=availability') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'availability' ? 'active' : '' ); ?>">
            <?php esc_html_e('Availability', 'freelance-studio'); ?>
        </a>
        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&tab=settings') ); ?>" class="fs-tab <?php echo esc_attr( $current_tab === 'settings' ? 'active' : '' ); ?>">
            <?php esc_html_e('Settings', 'freelance-studio'); ?>
        </a>
    </div>
    
    <!-- Vertical Tab Layout (same as Settings) -->
    <div class="fs-settings-layout">
        <nav class="fs-settings-sidebar">
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings') ); ?>" class="fs-settings-nav-item <?php echo esc_attr( !isset($_GET['tab']) || $_GET['tab'] === 'bookings' ? 'active' : '' ); ?>">
                <span class="dashicons dashicons-calendar-alt"></span> <?php esc_html_e('Bookings', 'freelance-studio'); ?>
            </a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&tab=meeting-types') ); ?>" class="fs-settings-nav-item <?php echo esc_attr( isset($_GET['tab']) && $_GET['tab'] === 'meeting-types' ? 'active' : '' ); ?>">
                <span class="dashicons dashicons-screenoptions"></span> <?php esc_html_e('Meeting Types', 'freelance-studio'); ?>
            </a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&tab=availability') ); ?>" class="fs-settings-nav-item <?php echo esc_attr( isset($_GET['tab']) && $_GET['tab'] === 'availability' ? 'active' : '' ); ?>">
                <span class="dashicons dashicons-clock"></span> <?php esc_html_e('Availability', 'freelance-studio'); ?>
            </a>
            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&tab=settings') ); ?>" class="fs-settings-nav-item <?php echo esc_attr( isset($_GET['tab']) && $_GET['tab'] === 'settings' ? 'active' : '' ); ?>">
                <span class="dashicons dashicons-admin-generic"></span> <?php esc_html_e('Settings', 'freelance-studio'); ?>
            </a>
        </nav>
        
        <div class="fs-settings-content">
            <!-- View Toggle -->
            <div class="fs-list-header" style="margin-top: 20px;">
                <div class="fs-view-toggle">
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&view=upcoming') ); ?>" class="fs-btn <?php echo esc_attr( $current_view === 'upcoming' ? 'fs-btn-primary' : 'fs-btn-secondary' ); ?>">
                        <?php esc_html_e('Upcoming', 'freelance-studio'); ?>
                    </a>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&view=all') ); ?>" class="fs-btn <?php echo esc_attr( $current_view === 'all' ? 'fs-btn-primary' : 'fs-btn-secondary' ); ?>">
                        <?php esc_html_e('All', 'freelance-studio'); ?>
                    </a>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&view=past') ); ?>" class="fs-btn <?php echo esc_attr( $current_view === 'past' ? 'fs-btn-primary' : 'fs-btn-secondary' ); ?>">
                        <?php esc_html_e('Past', 'freelance-studio'); ?>
                    </a>
                </div>
                
                <div class="fs-booking-link">
                    <span><?php esc_html_e('Public Booking Page:', 'freelance-studio'); ?></span>
                    <a href="<?php echo  esc_url( home_url('/book/') ); ?>" target="_blank" class="button">
                        <span class="dashicons dashicons-external" style="margin-top: 3px;"></span>
                        <?php echo  esc_url( home_url('/book/') ); ?>
                    </a>
                </div>
            </div>
            
            <!-- Bookings List -->
            <?php if (empty($bookings)): ?>
                <div class="fs-empty-state">
                    <span class="dashicons dashicons-calendar-alt"></span>
                    <h3><?php esc_html_e('No bookings found', 'freelance-studio'); ?></h3>
                    <p><?php esc_html_e('Bookings will appear here when clients schedule meetings with you.', 'freelance-studio'); ?></p>
                </div>
            <?php else: ?>
                <!-- Mobile Bookings List -->
                <div class="fs-invoice-mobile-list fs-mobile-only">
                    <?php foreach ($bookings as $booking): 
                        $attendee = $booking->client_name ?: $booking->guest_name;
                        $status_map = array(
                            'confirmed' => 'status-active',
                            'completed' => 'status-completed',
                            'cancelled' => 'status-cancelled',
                        );
                        $badge_class = isset($status_map[$booking->status]) ? $status_map[$booking->status] : 'status-pending';
                    ?>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&action=view&id=' . $booking->id) ); ?>" class="fs-invoice-mobile-row">
                        <div class="fs-invoice-mobile-left">
                            <span class="fs-invoice-mobile-client"><?php echo esc_html($booking->meeting_type_name); ?></span>
                            <span class="fs-invoice-mobile-number"><?php echo esc_html($attendee); ?> · <?php echo esc_html(FS_Meeting_Type::get_duration_display($booking->meeting_duration)); ?></span>
                            <span class="fs-status-badge <?php echo  esc_attr( $badge_class ); ?>"><?php echo esc_html(ucfirst($booking->status)); ?></span>
                        </div>
                        <div class="fs-invoice-mobile-right">
                            <span class="fs-invoice-mobile-amount" style="font-size: 14px;"><?php echo  esc_html( gmdate('M j', strtotime($booking->start_datetime)) ); ?></span>
                            <span class="fs-invoice-mobile-date"><?php echo  esc_html( gmdate('g:i A', strtotime($booking->start_datetime)) ); ?></span>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>

                <!-- Desktop Bookings Table -->
                <div class="fs-table-responsive fs-desktop-only">
                    <table class="wp-list-table widefat fixed striped fs-table">
                    <thead>
                        <tr>
                            <th class="column-date"><?php esc_html_e('Date & Time', 'freelance-studio'); ?></th>
                            <th class="column-meeting"><?php esc_html_e('Meeting Type', 'freelance-studio'); ?></th>
                            <th class="column-attendee"><?php esc_html_e('Attendee', 'freelance-studio'); ?></th>
                            <th class="column-status"><?php esc_html_e('Status', 'freelance-studio'); ?></th>
                            <th class="column-actions"></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($bookings as $booking): ?>
                            <tr>
                                <td class="column-date">
                                    <strong><?php echo  esc_html( gmdate('D, M j, Y', strtotime($booking->start_datetime)) ); ?></strong><br>
                                    <span class="fs-time">
                                        <?php echo  esc_html( gmdate('g:i A', strtotime($booking->start_datetime)) ); ?> - 
                                        <?php echo  esc_html( gmdate('g:i A', strtotime($booking->end_datetime)) ); ?>
                                    </span>
                                </td>
                                <td class="column-meeting">
                                    <span class="fs-meeting-type-badge" style="border-left: 3px solid <?php echo esc_attr($booking->meeting_color); ?>;">
                                        <?php echo esc_html($booking->meeting_type_name); ?>
                                    </span>
                                    <br>
                                    <span class="fs-duration"><?php echo  esc_html( FS_Meeting_Type::get_duration_display($booking->meeting_duration) ); ?></span>
                                </td>
                                <td class="column-attendee">
                                    <?php if ($booking->client_id): ?>
                                        <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-clients&action=view&id=' . $booking->client_id) ); ?>">
                                            <?php echo esc_html($booking->client_name); ?>
                                        </a>
                                        <?php if ($booking->client_company): ?>
                                            <br><span class="fs-company"><?php echo esc_html($booking->client_company); ?></span>
                                        <?php endif; ?>
                                    <?php else: ?>
                                        <?php echo esc_html($booking->guest_name); ?>
                                        <?php if ($booking->guest_email): ?>
                                            <br><span class="fs-email"><?php echo esc_html($booking->guest_email); ?></span>
                                        <?php endif; ?>
                                    <?php endif; ?>
                                </td>
                                <td class="column-status">
                                    <?php echo  wp_kses_post( FS_Booking::get_status_badge($booking->status) ); ?>
                                </td>
                                <td class="column-actions">
                                    <div class="fs-row-menu">
                                        <button type="button" class="fs-row-menu-trigger">⋯</button>
                                        <div class="fs-row-menu-dropdown">
                                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&action=view&id=' . $booking->id) ); ?>"><?php esc_html_e('View', 'freelance-studio'); ?></a>
                                            <?php if ($booking->status === 'confirmed'): ?>
                                                <hr>
                                                <a href="#" class="fs-cancel-booking text-danger" data-id="<?php echo esc_attr($booking->id); ?>"><?php esc_html_e('Cancel', 'freelance-studio'); ?></a>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                </div>
            <?php endif; ?>
            
            <?php
            // Pagination
            $base_url = admin_url('admin.php?page=fs-bookings');
            $pg_params = array();
            if (!empty($data['current_view']) && $data['current_view'] !== 'upcoming') $pg_params['view'] = $data['current_view'];
            if (!empty($data['current_status'])) $pg_params['status'] = $data['current_status'];
            if (!empty($data['current_type'])) $pg_params['meeting_type'] = $data['current_type'];
            if ($per_page !== 25) $pg_params['per_page'] = $per_page;
            if (!empty($pg_params)) $base_url = add_query_arg($pg_params, $base_url);
            $item_label = __('bookings', 'freelance-studio');
            include JEEB_FS_PLUGIN_DIR . 'includes/views/partials/pagination.php';
            ?>
        </div>
        
        <!-- Sidebar Widgets -->
        <div class="fs-bookings-sidebar">
            <!-- Mini Calendar Widget -->
            <div class="fs-card fs-widget">
                <div class="fs-sidebar-mini-cal fs-booking-mini-cal" id="fs-booking-mini-calendar" 
                     data-year="<?php echo esc_attr($cal_year); ?>" 
                     data-month="<?php echo esc_attr($cal_month); ?>">
                    <div class="fs-sidebar-mini-cal-header">
                        <span class="fs-sidebar-mini-cal-title"><?php echo esc_html($month_name . ' ' . $cal_year); ?></span>
                        <div class="fs-sidebar-mini-cal-nav">
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&cal_year=' . $prev_year . '&cal_month=' . $prev_month) ); ?>" class="fs-mini-nav-btn" title="<?php esc_attr_e('Previous month', 'freelance-studio'); ?>">
                                <span class="dashicons dashicons-arrow-left-alt2"></span>
                            </a>
                            <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&cal_year=' . $next_year . '&cal_month=' . $next_month) ); ?>" class="fs-mini-nav-btn" title="<?php esc_attr_e('Next month', 'freelance-studio'); ?>">
                                <span class="dashicons dashicons-arrow-right-alt2"></span>
                            </a>
                        </div>
                    </div>
                    <div class="fs-sidebar-mini-cal-grid">
                        <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('M', 'freelance-studio'); ?></span>
                        <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('T', 'freelance-studio'); ?></span>
                        <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('W', 'freelance-studio'); ?></span>
                        <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('T', 'freelance-studio'); ?></span>
                        <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('F', 'freelance-studio'); ?></span>
                        <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('S', 'freelance-studio'); ?></span>
                        <span class="fs-sidebar-mini-cal-weekday"><?php esc_html_e('S', 'freelance-studio'); ?></span>
                        <?php
                        // Empty cells before first day
                        $start_offset = $day_of_week - 1;
                        for ($i = 0; $i < $start_offset; $i++): ?>
                            <span class="fs-sidebar-mini-cal-day fs-other-month"></span>
                        <?php endfor;
                        
                        // Days of month
                        for ($day = 1; $day <= $days_in_month; $day++):
                            $date_str = sprintf('%04d-%02d-%02d', $cal_year, $cal_month, $day);
                            $is_today = $date_str === $today;
                            $has_events = isset($events_by_date[$date_str]);
                            $event_count = $has_events ? count($events_by_date[$date_str]) : 0;
                            
                            $classes = array('fs-sidebar-mini-cal-day');
                            if ($is_today) $classes[] = 'fs-today';
                            if ($has_events) $classes[] = 'fs-has-events';
                        ?>
                            <span class="<?php echo  esc_attr( implode(' ', $classes) ); ?>" title="<?php echo  esc_attr( $has_events ? $event_count . ' booking(s)' : '' ); ?>">
                                <?php echo  esc_html( $day ); ?>
                                <?php if ($has_events): ?>
                                    <span class="fs-mini-cal-dot"></span>
                                <?php endif; ?>
                            </span>
                        <?php endfor;
                        
                        // Empty cells after last day
                        $remaining = (7 - (($start_offset + $days_in_month) % 7)) % 7;
                        for ($i = 0; $i < $remaining; $i++): ?>
                            <span class="fs-sidebar-mini-cal-day fs-other-month"></span>
                        <?php endfor; ?>
                    </div>
                </div>
            </div>
            
            <!-- Upcoming Bookings Widget -->
            <div class="fs-card fs-widget">
                <div class="fs-card-header"><h3><?php esc_html_e('Upcoming Bookings', 'freelance-studio'); ?></h3></div>
                <?php if (!empty($upcoming_bookings)): ?>
                <div class="fs-widget-calendar-list">
                    <?php foreach ($upcoming_bookings as $booking): 
                        $booking_date = gmdate('Y-m-d', strtotime($booking->start_datetime));
                        $is_today = $booking_date === $today;
                        $item_class = 'fs-widget-calendar-item';
                        if ($is_today) $item_class .= ' fs-cal-today';
                        $meeting_type = FS_Meeting_Type::get($booking->meeting_type_id);
                        $color = $meeting_type ? $meeting_type->color : '#81A5DF';
                    ?>
                    <a href="<?php echo  esc_url( admin_url('admin.php?page=fs-bookings&action=view&id=' . $booking->id) ); ?>" class="<?php echo esc_attr( $item_class ); ?>" style="border-left-color: <?php echo esc_attr($color); ?>;">
                        <div class="fs-cal-date">
                            <span class="fs-cal-month"><?php echo  esc_html( gmdate('M', strtotime($booking->start_datetime)) ); ?></span>
                            <span class="fs-cal-day"><?php echo  esc_html( gmdate('j', strtotime($booking->start_datetime)) ); ?></span>
                        </div>
                        <div class="fs-cal-content">
                            <div class="fs-cal-title">
                                <span class="dashicons dashicons-calendar-alt"></span>
                                <?php echo esc_html($meeting_type ? $meeting_type->name : __('Meeting', 'freelance-studio')); ?>
                            </div>
                            <div class="fs-cal-subtitle">
                                <?php echo esc_html($booking->guest_name); ?> · <?php echo  esc_html( gmdate('g:i A', strtotime($booking->start_datetime)) ); ?>
                            </div>
                        </div>
                    </a>
                    <?php endforeach; ?>
                </div>
                <?php else: ?>
                <div class="fs-widget-no-events">
                    <span class="dashicons dashicons-calendar-alt"></span>
                    <p><?php esc_html_e('No upcoming bookings.', 'freelance-studio'); ?></p>
                </div>
                <?php endif; ?>
            </div>
        </div><!-- /.fs-settings-content -->
    </div><!-- /.fs-settings-layout -->
</div><!-- /.wrap -->

<script>
jQuery(document).ready(function($) {
    $('.fs-cancel-booking').on('click', function(e) {
        e.preventDefault();
        if (!confirm('<?php esc_html_e('Are you sure you want to cancel this booking?', 'freelance-studio'); ?>')) {
            return;
        }
        
        var id = $(this).data('id');
        var $row = $(this).closest('tr');
        
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
                action: 'fs_cancel_booking',
                nonce: '<?php echo esc_attr( wp_create_nonce('fs_ajax_nonce') ); ?>',
                booking_id: id
            },
            success: function(response) {
                if (response.success) {
                    location.reload();
                } else {
                    alert(response.data || '<?php esc_html_e('Error cancelling booking', 'freelance-studio'); ?>');
                }
            }
        });
    });
});
</script>
