<?php
/**
 * Availability Settings View
 *
 * @package Freelance_Studio
 */

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

$schedule_by_day = $data['schedule_by_day'];
$day_names = $data['day_names'];
$date_overrides = $data['date_overrides'];
?>

<div class="wrap fs-wrap">
    <h1 class="fs-page-title"><?php esc_html_e('Bookings', 'freelance-studio'); ?></h1>
    
    <?php if (isset($_GET['saved'])): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e('Availability saved successfully.', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_GET['deleted'])): ?>
        <div class="notice notice-success is-dismissible">
            <p><?php esc_html_e('Date override removed.', 'freelance-studio'); ?></p>
        </div>
    <?php endif; ?>
    
    <!-- Mobile Tab Dropdown Navigation -->
    <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 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 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 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 esc_html_e('Settings', 'freelance-studio'); ?></a>
    </div>
    
    <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">
                <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">
                <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 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">
                <span class="dashicons dashicons-admin-generic"></span> <?php esc_html_e('Settings', 'freelance-studio'); ?>
            </a>
        </nav>
        
        <div class="fs-settings-content">
    
    <!-- Timezone Confirmation Notice -->
    <?php 
    $current_timezone = get_option('fs_booking_timezone', wp_timezone_string());
    $tz_object = new DateTimeZone($current_timezone);
    $now = new DateTime('now', $tz_object);
    $offset = $tz_object->getOffset($now) / 3600;
    $offset_str = ($offset >= 0 ? '+' : '') . $offset;
    ?>
    <div class="fs-timezone-notice" style="background: #f0f6fc; border-left: 4px solid #2271b1; padding: 12px 16px; margin: 20px 0; display: flex; align-items: flex-start; gap: 12px;">
        <span class="dashicons dashicons-clock" style="color: #2271b1; margin-top: 2px;"></span>
        <div>
            <strong style="display: block; margin-bottom: 4px;"><?php esc_html_e('Confirm Your Time Zone', 'freelance-studio'); ?></strong>
            <p style="margin: 0 0 8px 0; color: #50575e;">
                <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    /* translators: 1. date/time, 2. date/time, 3. date/time */
                    __('Your availability schedule is set to <strong>%1$s</strong> (UTC%2$s). Current time: <strong>%3$s</strong>', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    esc_html($current_timezone),
                    esc_html($offset_str),
                    esc_html($now->format(get_option('time_format') . ', ' . get_option('date_format')))
                ); ?>
            </p>
            <p style="margin: 0; font-size: 13px; color: #646970;">
                <?php printf( // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    /* translators: 1. recipient name */
                    __('If this is incorrect, <a href="%s">update your time zone in Settings</a>. Your clients will see available times converted to their local time zone.', 'freelance-studio'), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                    admin_url('admin.php?page=fs-bookings&tab=settings') // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                ); ?>
            </p>
        </div>
    </div>
    
    <div class="fs-availability-layout">
        <!-- Weekly Schedule -->
        <div class="fs-card fs-weekly-schedule">
            <h3><?php esc_html_e('Weekly Schedule', 'freelance-studio'); ?></h3>
            <p class="description"><?php esc_html_e('Set your regular available hours for each day of the week.', 'freelance-studio'); ?></p>
            
            <form method="post" id="fs-weekly-schedule-form">
                <?php wp_nonce_field('fs_save_availability', 'fs_availability_nonce'); ?>
                
                <div class="fs-schedule-days">
                    <?php foreach ($day_names as $day_num => $day_name): ?>
                        <div class="fs-schedule-day" data-day="<?php echo  intval( $day_num ); ?>">
                            <div class="fs-day-header">
                                <strong><?php echo esc_html($day_name); ?></strong>
                            </div>
                            
                            <div class="fs-day-blocks">
                                <?php 
                                $blocks = $schedule_by_day[$day_num];
                                if (empty($blocks)):
                                ?>
                                    <div class="fs-unavailable"><?php esc_html_e('Unavailable', 'freelance-studio'); ?></div>
                                <?php else: ?>
                                    <?php foreach ($blocks as $i => $block): ?>
                                        <div class="fs-time-block">
                                            <input type="time" name="weekly[<?php echo  intval( $day_num ); ?>][start][]" 
                                                   value="<?php echo esc_attr(substr($block->start_time, 0, 5)); ?>">
                                            <span>-</span>
                                            <input type="time" name="weekly[<?php echo  intval( $day_num ); ?>][end][]" 
                                                   value="<?php echo esc_attr(substr($block->end_time, 0, 5)); ?>">
                                            <button type="button" class="button-link fs-remove-block" title="<?php esc_attr_e('Remove', 'freelance-studio'); ?>">
                                                <span class="dashicons dashicons-no-alt"></span>
                                            </button>
                                        </div>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>
                            
                            <button type="button" class="button button-small fs-add-block" data-day="<?php echo  intval( $day_num ); ?>">
                                <span class="dashicons dashicons-plus-alt2" style="margin-top: 3px;"></span>
                                <?php esc_html_e('Add Hours', 'freelance-studio'); ?>
                            </button>
                        </div>
                    <?php endforeach; ?>
                </div>
                
                <div class="fs-form-actions">
                    <button type="submit" class="button button-primary">
                        <?php esc_html_e('Save Weekly Schedule', 'freelance-studio'); ?>
                    </button>
                </div>
            </form>
        </div>
        
        <!-- Date Overrides -->
        <div class="fs-card fs-date-overrides">
            <h3><?php esc_html_e('Date Overrides', 'freelance-studio'); ?></h3>
            <p class="description"><?php esc_html_e('Set custom hours or block specific dates.', 'freelance-studio'); ?></p>
            
            <form method="post" id="fs-date-override-form">
                <?php wp_nonce_field('fs_add_date_override', 'fs_date_override_nonce'); ?>
                
                <div class="fs-override-form">
                    <div class="fs-form-row">
                        <div class="fs-form-group">
                            <label for="override_date"><?php esc_html_e('Date', 'freelance-studio'); ?></label>
                            <input type="date" name="override_date" id="override_date" required 
                                   min="<?php echo  esc_html( gmdate('Y-m-d') ); ?>">
                        </div>
                        
                        <div class="fs-form-group">
                            <label for="override_type"><?php esc_html_e('Type', 'freelance-studio'); ?></label>
                            <select name="override_type" id="override_type">
                                <option value="custom"><?php esc_html_e('Custom Hours', 'freelance-studio'); ?></option>
                                <option value="blocked"><?php esc_html_e('Block Entire Day', 'freelance-studio'); ?></option>
                            </select>
                        </div>
                    </div>
                    
                    <div id="fs-custom-hours" class="fs-form-group">
                        <label><?php esc_html_e('Available Hours', 'freelance-studio'); ?></label>
                        <div class="fs-override-blocks">
                            <div class="fs-time-block">
                                <input type="time" name="override_start[]" value="09:00">
                                <span>-</span>
                                <input type="time" name="override_end[]" value="17:00">
                                <button type="button" class="button-link fs-remove-override-block">
                                    <span class="dashicons dashicons-no-alt"></span>
                                </button>
                            </div>
                        </div>
                        <button type="button" class="button button-small fs-add-override-block">
                            <span class="dashicons dashicons-plus-alt2" style="margin-top: 3px;"></span>
                            <?php esc_html_e('Add Time Block', 'freelance-studio'); ?>
                        </button>
                    </div>
                    
                    <div class="fs-form-group">
                        <label for="override_note"><?php esc_html_e('Note (optional)', 'freelance-studio'); ?></label>
                        <input type="text" name="override_note" id="override_note" class="regular-text"
                               placeholder="<?php esc_attr_e('e.g., Holiday, Vacation', 'freelance-studio'); ?>">
                    </div>
                    
                    <button type="submit" name="add_date_override" class="button button-primary">
                        <?php esc_html_e('Add Override', 'freelance-studio'); ?>
                    </button>
                </div>
            </form>
            
            <?php if (!empty($date_overrides)): ?>
                <h4 style="margin-top: 30px;"><?php esc_html_e('Upcoming Overrides', 'freelance-studio'); ?></h4>
                <table class="widefat striped">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Date', 'freelance-studio'); ?></th>
                            <th><?php esc_html_e('Hours', 'freelance-studio'); ?></th>
                            <th><?php esc_html_e('Note', 'freelance-studio'); ?></th>
                            <th></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php 
                        $grouped_overrides = array();
                        foreach ($date_overrides as $override) {
                            $date = $override->specific_date;
                            if (!isset($grouped_overrides[$date])) {
                                $grouped_overrides[$date] = array(
                                    'type' => $override->type,
                                    'note' => $override->note,
                                    'blocks' => array(),
                                    'ids' => array(),
                                );
                            }
                            $grouped_overrides[$date]['ids'][] = $override->id;
                            if ($override->start_time) {
                                $grouped_overrides[$date]['blocks'][] = substr($override->start_time, 0, 5) . ' - ' . substr($override->end_time, 0, 5);
                            }
                        }
                        
                        foreach ($grouped_overrides as $date => $override):
                        ?>
                            <tr>
                                <td>
                                    <strong><?php echo  esc_html( gmdate('D, M j, Y', strtotime($date)) ); ?></strong>
                                </td>
                                <td>
                                    <?php if ($override['type'] === 'blocked'): ?>
                                        <span class="fs-badge fs-badge-danger"><?php esc_html_e('Blocked', 'freelance-studio'); ?></span>
                                    <?php else: ?>
                                        <?php echo  esc_html( implode('<br>', $override['blocks']) ); ?>
                                    <?php endif; ?>
                                </td>
                                <td><?php echo esc_html($override['note']); ?></td>
                                <td>
                                    <a href="<?php echo esc_url( wp_nonce_url( admin_url('admin.php?page=fs-bookings&tab=availability&delete_override=' . $override['ids'][0]), 'fs_delete_override') ); ?>" 
                                       class="button button-small button-link-delete">
                                        <?php esc_html_e('Remove', 'freelance-studio'); ?>
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php endif; ?>
        </div><!-- /.fs-settings-content -->
    </div><!-- /.fs-settings-layout -->
</div>

<script>
jQuery(document).ready(function($) {
    // Toggle custom hours visibility
    $('#override_type').on('change', function() {
        if ($(this).val() === 'blocked') {
            $('#fs-custom-hours').hide();
        } else {
            $('#fs-custom-hours').show();
        }
    });
    
    // Add time block to weekly schedule
    $('.fs-add-block').on('click', function() {
        var day = $(this).data('day');
        var $container = $(this).siblings('.fs-day-blocks');
        
        // Remove "Unavailable" text if present
        $container.find('.fs-unavailable').remove();
        
        var html = '<div class="fs-time-block">' +
            '<input type="time" name="weekly[' + day + '][start][]" value="09:00">' +
            '<span>-</span>' +
            '<input type="time" name="weekly[' + day + '][end][]" value="17:00">' +
            '<button type="button" class="button-link fs-remove-block"><span class="dashicons dashicons-no-alt"></span></button>' +
            '</div>';
        
        $container.append(html);
    });
    
    // Remove time block
    $(document).on('click', '.fs-remove-block', function() {
        var $day = $(this).closest('.fs-schedule-day');
        $(this).closest('.fs-time-block').remove();
        
        // Show "Unavailable" if no blocks left
        if ($day.find('.fs-time-block').length === 0) {
            $day.find('.fs-day-blocks').html('<div class="fs-unavailable"><?php esc_html_e('Unavailable', 'freelance-studio'); ?></div>');
        }
    });
    
    // Add override time block
    $('.fs-add-override-block').on('click', function() {
        var html = '<div class="fs-time-block">' +
            '<input type="time" name="override_start[]" value="09:00">' +
            '<span>-</span>' +
            '<input type="time" name="override_end[]" value="17:00">' +
            '<button type="button" class="button-link fs-remove-override-block"><span class="dashicons dashicons-no-alt"></span></button>' +
            '</div>';
        
        $('.fs-override-blocks').append(html);
    });
    
    // Remove override time block
    $(document).on('click', '.fs-remove-override-block', function() {
        if ($('.fs-override-blocks .fs-time-block').length > 1) {
            $(this).closest('.fs-time-block').remove();
        }
    });
});
</script>
