<?php
/**
 * Booking Controller
 *
 * @package Freelance_Studio
 */

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

class FS_Booking_Controller {

    /**
     * Handle the request
     */
    public function handle_request() {
        $action = isset($_GET['action']) ? sanitize_text_field($_GET['action']) : 'list';
        $tab = isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'bookings';
        
        switch ($action) {
            case 'view':
                $this->view();
                break;
            case 'new-meeting-type':
                $this->meeting_type_form();
                break;
            case 'edit-meeting-type':
                $this->meeting_type_form();
                break;
            default:
                if ($tab === 'meeting-types') {
                    $this->meeting_types_list();
                } elseif ($tab === 'availability') {
                    $this->availability();
                } elseif ($tab === 'settings') {
                    $this->settings();
                } else {
                    $this->bookings_list();
                }
        }
    }

    /**
     * List all bookings
     */
    private function bookings_list() {
        // Handle actions
        if (isset($_POST['action']) && $_POST['action'] === 'cancel' && isset($_POST['booking_id'])) {
            check_admin_referer('fs_cancel_booking');
            $booking_id = intval($_POST['booking_id']);
            FS_Booking::cancel($booking_id, '', 'admin');
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&cancelled=1'));
            exit;
        }
        
        // Get filter parameters
        $status = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : null;
        $meeting_type_id = isset($_GET['meeting_type']) ? intval($_GET['meeting_type']) : null;
        $view = isset($_GET['view']) ? sanitize_text_field($_GET['view']) : 'upcoming';
        
        // Pagination
        $per_page = isset($_GET['per_page']) ? intval($_GET['per_page']) : 25;
        $per_page = in_array($per_page, array(10, 25, 50, 100)) ? $per_page : 25;
        $current_page = isset($_GET['paged']) ? max(1, intval($_GET['paged'])) : 1;
        $offset = ($current_page - 1) * $per_page;
        
        $args = array(
            'status' => $status,
            'meeting_type_id' => $meeting_type_id,
            'limit' => $per_page,
            'offset' => $offset,
        );
        
        $count_args = array(
            'status' => $status,
            'meeting_type_id' => $meeting_type_id,
        );
        
        if ($view === 'upcoming') {
            $args['upcoming_only'] = true;
            $args['status'] = 'confirmed';
            $count_args['status'] = 'confirmed';
            $count_args['upcoming_only'] = true;
        } elseif ($view === 'past') {
            $args['end_date'] = gmdate('Y-m-d');
            $args['order'] = 'DESC';
            $count_args['end_date'] = gmdate('Y-m-d');
        }
        
        $bookings = FS_Booking::get_all($args);
        $total_items = FS_Booking::count($count_args);
        $total_pages = ceil($total_items / $per_page);
        $meeting_types = FS_Meeting_Type::get_all();
        
        // Get upcoming bookings for widget (next 7 days)
        $upcoming_bookings = FS_Booking::get_all(array(
            'upcoming_only' => true,
            'status' => 'confirmed',
            'limit' => 5,
        ));
        
        // Get calendar data for mini calendar
        $cal_year = isset($_GET['cal_year']) ? intval($_GET['cal_year']) : gmdate('Y');
        $cal_month = isset($_GET['cal_month']) ? intval($_GET['cal_month']) : gmdate('n');
        
        // Get bookings for calendar display
        $start_date = gmdate('Y-m-01', mktime(0, 0, 0, $cal_month, 1, $cal_year));
        $end_date = gmdate('Y-m-t', mktime(0, 0, 0, $cal_month, 1, $cal_year));
        
        $calendar_bookings = FS_Booking::get_all(array(
            'start_date' => $start_date,
            'end_date' => $end_date,
            'status' => 'confirmed',
        ));
        
        // Format bookings for calendar
        $calendar_events = array();
        foreach ($calendar_bookings as $booking) {
            $calendar_events[] = array(
                'date' => gmdate('Y-m-d', strtotime($booking->start_datetime)),
                'type' => 'booking',
            );
        }
        
        $data = array(
            'bookings' => $bookings,
            'meeting_types' => $meeting_types,
            'current_status' => $status,
            'current_type' => $meeting_type_id,
            'current_view' => $view,
            'upcoming_bookings' => $upcoming_bookings,
            'calendar_data' => array(
                'year' => $cal_year,
                'month' => $cal_month,
                'events' => $calendar_events,
            ),
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/bookings/list.php';
    }

    /**
     * View single booking
     */
    private function view() {
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        
        if (!$id) {
            wp_die(esc_html__('Invalid booking ID', 'freelance-studio'));
        }
        
        // Handle status updates
        if (isset($_POST['update_status']) && check_admin_referer('fs_update_booking_' . $id)) {
            $new_status = sanitize_text_field(wp_unslash($_POST['new_status']));
            
            switch ($new_status) {
                case 'completed':
                    FS_Booking::complete($id);
                    break;
                case 'no_show':
                    FS_Booking::no_show($id);
                    break;
                case 'cancelled':
                    $reason = isset($_POST['cancel_reason']) ? sanitize_textarea_field(wp_unslash($_POST['cancel_reason'])) : '';
                    FS_Booking::cancel($id, $reason, 'admin');
                    break;
            }
            
            FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&action=view&id=' . $id . '&updated=1'));
            exit;
        }
        
        $booking = FS_Booking::get($id);
        
        if (!$booking) {
            wp_die(esc_html__('Booking not found', 'freelance-studio'));
        }
        
        $meeting_type = FS_Meeting_Type::get($booking->meeting_type_id);
        $client = $booking->client_id ? FS_Client::get($booking->client_id) : null;
        
        $data = array(
            'booking' => $booking,
            'meeting_type' => $meeting_type,
            'client' => $client,
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/bookings/view.php';
    }

    /**
     * List meeting types
     */
    private function meeting_types_list() {
        // Handle delete
        if (isset($_GET['delete']) && isset($_GET['_wpnonce'])) {
            if (wp_verify_nonce($_GET['_wpnonce'], 'fs_delete_meeting_type')) {
                FS_Meeting_Type::delete(intval($_GET['delete']));
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&tab=meeting-types&deleted=1'));
                exit;
            }
        }
        
        $meeting_types = FS_Meeting_Type::get_all();
        
        $data = array(
            'meeting_types' => $meeting_types,
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/bookings/meeting-types.php';
    }

    /**
     * Meeting type form (create/edit)
     */
    private function meeting_type_form() {
        $id = isset($_GET['id']) ? intval($_GET['id']) : 0;
        $meeting_type = $id ? FS_Meeting_Type::get($id) : null;
        
        // Handle form submission
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fs_meeting_type_nonce'])) {
            if (wp_verify_nonce($_POST['fs_meeting_type_nonce'], 'fs_save_meeting_type')) {
                $data = array(
                    'name' => sanitize_text_field(wp_unslash($_POST['name'])),
                    'description' => sanitize_textarea_field(wp_unslash($_POST['description'])),
                    'duration' => intval($_POST['duration']),
                    'color' => sanitize_hex_color($_POST['color']),
                    'price' => !empty($_POST['price']) ? floatval($_POST['price']) : null,
                    'location_type' => sanitize_text_field(wp_unslash($_POST['location_type'])),
                    'location_details' => sanitize_textarea_field(wp_unslash($_POST['location_details'])),
                    'buffer_before' => intval($_POST['buffer_before']),
                    'buffer_after' => intval($_POST['buffer_after']),
                    'min_notice_hours' => intval($_POST['min_notice_hours']),
                    'max_days_advance' => intval($_POST['max_days_advance']),
                    'is_active' => isset($_POST['is_active']) ? 1 : 0,
                    'is_public' => isset($_POST['is_public']) ? 1 : 0,
                );
                
                if ($id) {
                    FS_Meeting_Type::update($id, $data);
                    $redirect_id = $id;
                } else {
                    $redirect_id = FS_Meeting_Type::create($data);
                }
                
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&tab=meeting-types&saved=1'));
                exit;
            }
        }
        
        $data = array(
            'meeting_type' => $meeting_type,
            'is_edit' => (bool) $id,
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/bookings/meeting-type-form.php';
    }

    /**
     * Availability settings
     */
    private function availability() {
        // Handle form submission
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fs_availability_nonce'])) {
            if (wp_verify_nonce($_POST['fs_availability_nonce'], 'fs_save_availability')) {
                // Save weekly schedule
                if (isset($_POST['weekly'])) {
                    foreach ($_POST['weekly'] as $day => $blocks) {
                        $time_blocks = array();
                        if (isset($blocks['start']) && is_array($blocks['start'])) {
                            foreach ($blocks['start'] as $i => $start) {
                                if (!empty($start) && !empty($blocks['end'][$i])) {
                                    $time_blocks[] = array(
                                        'start_time' => sanitize_text_field($start),
                                        'end_time' => sanitize_text_field($blocks['end'][$i]),
                                    );
                                }
                            }
                        }
                        FS_Availability::save_day_schedule(intval($day), $time_blocks);
                    }
                }
                
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&tab=availability&saved=1'));
                exit;
            }
        }
        
        // Handle date override/block
        if (isset($_POST['add_date_override']) && isset($_POST['fs_date_override_nonce'])) {
            if (wp_verify_nonce($_POST['fs_date_override_nonce'], 'fs_add_date_override')) {
                $date = sanitize_text_field(wp_unslash($_POST['override_date']));
                $type = sanitize_text_field(wp_unslash($_POST['override_type']));
                $note = sanitize_text_field(wp_unslash($_POST['override_note']));
                
                if ($type === 'blocked') {
                    FS_Availability::block_date($date, $note);
                } else {
                    $time_blocks = array();
                    if (isset($_POST['override_start']) && is_array($_POST['override_start'])) {
                        foreach ($_POST['override_start'] as $i => $start) {
                            if (!empty($start) && !empty($_POST['override_end'][$i])) {
                                $time_blocks[] = array(
                                    'start_time' => sanitize_text_field($start),
                                    'end_time' => sanitize_text_field(wp_unslash($_POST['override_end'])[$i]),
                                );
                            }
                        }
                    }
                    FS_Availability::add_date_override($date, $time_blocks, $note);
                }
                
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&tab=availability&saved=1'));
                exit;
            }
        }
        
        // Handle date override deletion
        if (isset($_GET['delete_override']) && isset($_GET['_wpnonce'])) {
            if (wp_verify_nonce($_GET['_wpnonce'], 'fs_delete_override')) {
                FS_Availability::remove_date_entry(intval($_GET['delete_override']));
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&tab=availability&deleted=1'));
                exit;
            }
        }
        
        $weekly_schedule = FS_Availability::get_weekly_schedule();
        $day_names = FS_Availability::get_day_names();
        
        // Organize weekly schedule by day
        $schedule_by_day = array();
        for ($i = 0; $i <= 6; $i++) {
            $schedule_by_day[$i] = array();
        }
        foreach ($weekly_schedule as $block) {
            $schedule_by_day[$block->day_of_week][] = $block;
        }
        
        // Get upcoming date overrides
        $start_date = gmdate('Y-m-d');
        $end_date = gmdate('Y-m-d', strtotime('+90 days'));
        $date_overrides = FS_Availability::get_date_overrides($start_date, $end_date);
        
        $data = array(
            'schedule_by_day' => $schedule_by_day,
            'day_names' => $day_names,
            'date_overrides' => $date_overrides,
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/bookings/availability.php';
    }

    /**
     * Booking settings
     */
    private function settings() {
        // Handle form submission
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['fs_booking_settings_nonce'])) {
            if (wp_verify_nonce($_POST['fs_booking_settings_nonce'], 'fs_save_booking_settings')) {
                update_option('fs_booking_enabled', isset($_POST['booking_enabled']) ? '1' : '0');
                update_option('fs_booking_page_title', sanitize_text_field(wp_unslash($_POST['page_title'])));
                update_option('fs_booking_page_description', sanitize_textarea_field(wp_unslash($_POST['page_description'])));
                update_option('fs_booking_timezone', sanitize_text_field(wp_unslash($_POST['timezone'])));
                update_option('fs_booking_confirmation_email', isset($_POST['confirmation_email']) ? '1' : '0');
                update_option('fs_booking_reminder_hours', intval($_POST['reminder_hours']));
                update_option('fs_booking_auto_google_meet', isset($_POST['auto_google_meet']) ? '1' : '0');
                
                FS_Admin::safe_redirect(admin_url('admin.php?page=fs-bookings&tab=settings&saved=1'));
                exit;
            }
        }
        
        // Generate booking URL based on permalink structure
        $permalink_structure = get_option('permalink_structure');
        if (empty($permalink_structure)) {
            // Plain permalinks - use query parameter
            $booking_url = add_query_arg('fs_booking', '1', home_url('/'));
        } else {
            // Pretty permalinks
            $booking_url = home_url('/book/');
        }
        
        $data = array(
            'booking_enabled' => get_option('fs_booking_enabled', '1'),
            'page_title' => get_option('fs_booking_page_title', 'Book a Meeting'),
            'page_description' => get_option('fs_booking_page_description', ''),
            'timezone' => get_option('fs_booking_timezone', wp_timezone_string()),
            'confirmation_email' => get_option('fs_booking_confirmation_email', '1'),
            'reminder_hours' => get_option('fs_booking_reminder_hours', '24'),
            'booking_url' => $booking_url,
        );
        
        include JEEB_FS_PLUGIN_DIR . 'includes/views/bookings/settings.php';
    }
}
