<?php
namespace BookWellAB;

defined('ABSPATH') || exit;
// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

if (!class_exists('BookWellAB_Setup')) {

    class BookWellAB_Setup
    {
        private static $instance = null;
        private $bwdb;

        public static function get_instance()
        {
            if (self::$instance === null) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        public function __construct()
        {
            $this->bwdb = new BookWellAB_Database();
            if (is_admin()) {
                add_action('wp_ajax_bookwellab_finish_setup', [$this, 'bookwellab_finish_setup_func']);
                add_action('wp_ajax_bookwellab_skip_setup', [$this, 'bookwellab_skip_setup_func']);
            }
        }

        /**
         * Get initial data for the setup wizard
         */
        public static function get_setup_wizard_data()
        {
            $current_user = wp_get_current_user();
            $defaults = \BookWellAB\BookWellAB_Settings::get_instance()->get_defaults()['general'];
            // Keep setup wizard default date format aligned with requested UX.
            $defaults['date_format'] = 'F j, Y';
            return [
                'admin_name'  => $current_user->display_name,
                'admin_email' => $current_user->user_email,
                'blog_name'   => get_bloginfo('name'),
                'currencies'  => \BookWellAB\BookWellAB_Settings::get_currencies(),
                'countries'   => \BookWellAB\BookWellAB_Settings::get_countries_list(),
                'phone_codes' => \BookWellAB\BookWellAB_Settings::get_phone_codes(),
                'defaults'    => $defaults,
            ];
        }

        /**
         * Translated UI strings for the setup wizard (passed to Vue via JSON).
         *
         * @return array<string, mixed>
         */
        public static function get_setup_wizard_i18n()
        {
            $i18n = [
                'header' => [
                    'title' => __('Quick Setup Wizard', 'bookwellnow-appointment-booking'),
                    'subtitle' => __('Let\'s get your booking system ready in a few easy steps.', 'bookwellnow-appointment-booking'),
                ],
                'steps' => [
                    __('Basic Info', 'bookwellnow-appointment-booking'),
                    __('Service', 'bookwellnow-appointment-booking'),
                    __('Staff', 'bookwellnow-appointment-booking'),
                    __('Finish', 'bookwellnow-appointment-booking'),
                ],
                'labels' => [
                    'company_name' => __('Company Name', 'bookwellnow-appointment-booking'),
                    'company_phone' => __('Company Phone', 'bookwellnow-appointment-booking'),
                    'company_address' => __('Company Address', 'bookwellnow-appointment-booking'),
                    'default_phone_code' => __('Default Phone Code', 'bookwellnow-appointment-booking'),
                    'date_format' => __('Date Format', 'bookwellnow-appointment-booking'),
                    'time_format' => __('Time Format', 'bookwellnow-appointment-booking'),
                    'currency' => __('Currency', 'bookwellnow-appointment-booking'),
                    'currency_position' => __('Currency Position', 'bookwellnow-appointment-booking'),
                    'default_appointment_status' => __('Default Appointment Status', 'bookwellnow-appointment-booking'),
                    'default_payment_status' => __('Default Payment Status', 'bookwellnow-appointment-booking'),
                    'service_name' => __('Service Name', 'bookwellnow-appointment-booking'),
                    'price' => __('Price', 'bookwellnow-appointment-booking'),
                    'duration' => __('Duration', 'bookwellnow-appointment-booking'),
                    'description' => __('Description', 'bookwellnow-appointment-booking'),
                    'full_name' => __('Full Name', 'bookwellnow-appointment-booking'),
                    'email' => __('Email', 'bookwellnow-appointment-booking'),
                    'phone' => __('Phone', 'bookwellnow-appointment-booking'),
                    'working_hours' => __('Working Hours', 'bookwellnow-appointment-booking'),
                    'day_off' => __('Day Off', 'bookwellnow-appointment-booking'),
                    'add_break' => __('+ Break', 'bookwellnow-appointment-booking'),
                    'remove' => __('Remove', 'bookwellnow-appointment-booking'),
                    'ready_title' => __('Ready to launch!', 'bookwellnow-appointment-booking'),
                    'ready_text' => __('We have all the information needed to set up your booking platform.', 'bookwellnow-appointment-booking'),
                    'summary_company' => __('Company:', 'bookwellnow-appointment-booking'),
                    'summary_service' => __('First Service:', 'bookwellnow-appointment-booking'),
                    'summary_staff' => __('Staff Member:', 'bookwellnow-appointment-booking'),
                    'skip_manual' => __('Skip & Configure Manually', 'bookwellnow-appointment-booking'),
                    'previous' => __('Previous', 'bookwellnow-appointment-booking'),
                    'next_step' => __('Next Step', 'bookwellnow-appointment-booking'),
                    'complete_setup' => __('Complete Setup', 'bookwellnow-appointment-booking'),
                    'off' => __('Off', 'bookwellnow-appointment-booking'),
                    'on' => __('On', 'bookwellnow-appointment-booking'),
                ],
                'placeholders' => [
                    'company_name' => __('e.g. My Studio', 'bookwellnow-appointment-booking'),
                    'company_phone' => __('1234567890', 'bookwellnow-appointment-booking'),
                    'company_address' => __('Enter business address...', 'bookwellnow-appointment-booking'),
                    'phone_code' => __('Select Phone Code', 'bookwellnow-appointment-booking'),
                    'service_name' => __('e.g. Consultation', 'bookwellnow-appointment-booking'),
                    'shift_start' => __('Start', 'bookwellnow-appointment-booking'),
                    'shift_end' => __('End', 'bookwellnow-appointment-booking'),
                ],
                'options' => [
                    'date_formats' => [
                        ['label' => __('F j, Y (April 20, 2026)', 'bookwellnow-appointment-booking'), 'value' => 'F j, Y'],
                        ['label' => __('Y-m-d (2026-04-20)', 'bookwellnow-appointment-booking'), 'value' => 'Y-m-d'],
                        ['label' => __('m/d/Y (04/20/2026)', 'bookwellnow-appointment-booking'), 'value' => 'm/d/Y'],
                        ['label' => __('d/m/Y (20/04/2026)', 'bookwellnow-appointment-booking'), 'value' => 'd/m/Y'],
                        ['label' => __('d.m.Y (20.04.2026)', 'bookwellnow-appointment-booking'), 'value' => 'd.m.Y'],
                        ['label' => __('d-m-Y (20-04-2026)', 'bookwellnow-appointment-booking'), 'value' => 'd-m-Y'],
                    ],
                    'time_formats' => [
                        ['label' => __('h:i a (12 hour - 01:30 pm)', 'bookwellnow-appointment-booking'), 'value' => 'h:i a'],
                        ['label' => __('g:i a (12 hour no-zero - 1:30 pm)', 'bookwellnow-appointment-booking'), 'value' => 'g:i a'],
                        ['label' => __('h:i A (12 hour - 01:30 PM)', 'bookwellnow-appointment-booking'), 'value' => 'h:i A'],
                        ['label' => __('g:i A (12 hour no-zero - 1:30 PM)', 'bookwellnow-appointment-booking'), 'value' => 'g:i A'],
                        ['label' => __('H:i (24 hour - 13:30)', 'bookwellnow-appointment-booking'), 'value' => 'H:i'],
                    ],
                    'currency_positions' => [
                        ['label' => __('Before (e.g. $10)', 'bookwellnow-appointment-booking'), 'value' => 'before'],
                        ['label' => __('After (e.g. 10$)', 'bookwellnow-appointment-booking'), 'value' => 'after'],
                    ],
                    'appointment_statuses' => [
                        ['label' => __('Pending', 'bookwellnow-appointment-booking'), 'value' => 'pending'],
                        ['label' => __('Approved', 'bookwellnow-appointment-booking'), 'value' => 'approved'],
                    ],
                    'payment_statuses' => [
                        ['label' => __('Pending', 'bookwellnow-appointment-booking'), 'value' => 'pending'],
                        ['label' => __('Received', 'bookwellnow-appointment-booking'), 'value' => 'received'],
                        ['label' => __('Failed', 'bookwellnow-appointment-booking'), 'value' => 'failed'],
                    ],
                    'duration_units' => [
                        ['label' => __('Mins', 'bookwellnow-appointment-booking'), 'value' => 'm'],
                        ['label' => __('Hours', 'bookwellnow-appointment-booking'), 'value' => 'h'],
                    ],
                ],
            ];

            return bookwellab_ensure_utf8($i18n);
        }

        /**
         * AJAX Handler for completing the setup
         */
        public function bookwellab_finish_setup_func()
        {
            if (!\BookWellAB\BookWellAB_Permissions::has_permission('bookwellab_manage_settings')) {
                wp_send_json_error(['msg' => esc_html__('Unauthorized', 'bookwellnow-appointment-booking')]);
            }

            if (!check_ajax_referer('bw_wp_nonce', '_wpnonce', false)) {
                wp_send_json_error(['msg' => esc_html__('Security token mismatch.', 'bookwellnow-appointment-booking')]);
            }

            // BookWellAB_Input: decoded JSON only; each setup field sanitized below before DB write.
            $data = BookWellAB_Input::get_post_json('setup_data');
            if (empty($data)) {
                wp_send_json_error(['msg' => 'No setup data received']);
            }

            global $wpdb;

            // 1. Save General Settings as typed per-setting rows.
            $settings_class = \BookWellAB\BookWellAB_Settings::get_instance();
            $defaults = $settings_class->get_defaults();
            $general_defaults = isset($defaults['general']) && is_array($defaults['general']) ? $defaults['general'] : [];
            $incoming_general = isset($data['settings']) && is_array($data['settings']) ? $data['settings'] : array();
            $general_merged = array_merge($general_defaults, $incoming_general);
            $general_merged['setup_completed'] = true;

            $sanitized = $settings_class->sanitize_settings_for_save(array('general' => $general_merged));
            $general_settings = isset($sanitized['general']) && is_array($sanitized['general'])
                ? $sanitized['general']
                : $general_merged;
            $general_settings['setup_completed'] = true;

            $this->bwdb->update_settings_by_type('general', $general_settings);

            \BookWellAB\BookWellAB_Frontend::clear_front_booking_cache();

            // 2. Create Service
            $service_id = 0;
            $service_price = 0;
            $service_duration_val = 30;
            $service_duration_unit = 'm';
            if (isset($data['service'])) {
                $service_data = $data['service'];
                $service_price = isset($service_data['bw_service_price']) ? floatval($service_data['bw_service_price']) : 0;
                $service_duration_val = isset($service_data['bw_service_duration_val']) ? intval($service_data['bw_service_duration_val']) : 30;
                $service_duration_unit = isset($service_data['bw_service_duration_unit']) ? sanitize_text_field($service_data['bw_service_duration_unit']) : 'm';
                if ($service_duration_val <= 0) {
                    $service_duration_val = 30;
                }
                if (!in_array($service_duration_unit, ['m', 'h'], true)) {
                    $service_duration_unit = 'm';
                }
                $wpdb->insert(
                    $this->bwdb->get_table_name('services'),
                    [
                        'bw_service_name'          => sanitize_text_field($service_data['bw_service_name']),
                        'bw_service_price'         => $service_price,
                        'bw_service_duration_val'  => $service_duration_val,
                        'bw_service_duration_unit' => $service_duration_unit,
                        'bw_service_description'   => sanitize_textarea_field($service_data['bw_service_description']),
                        'bw_service_status'        => 1,
                        'bw_service_position'      => 1,
                        'bw_category_id'           => 0,
                        'bw_service_image'         => ''
                    ]
                );
                $service_id = $wpdb->insert_id;
            }

            // 3. Create Staff
            if (isset($data['staff'])) {
                $staff_data = $data['staff'];
                $wpdb->insert(
                    $this->bwdb->get_table_name('staffs'),
                    [
                        'bw_staff_name'     => sanitize_text_field($staff_data['bw_staff_name']),
                        'bw_staff_email'    => sanitize_email($staff_data['bw_staff_email']),
                        'bw_staff_phone'    => sanitize_text_field($staff_data['bw_staff_phone']),
                        'bw_staff_position' => sanitize_text_field($staff_data['bw_staff_position']),
                        'bw_staff_is_active' => 1,
                        'bw_wp_user_id'     => get_current_user_id()
                    ]
                );
                $staff_id = $wpdb->insert_id;

                // 4. Link Staff and Service
                if ($service_id > 0 && $staff_id > 0) {
                    $wpdb->insert(
                        $this->bwdb->get_table_name('staff_services'),
                        [
                            'bw_staff_id' => $staff_id,
                            'bw_service_id' => $service_id,
                            'bw_service_price' => $service_price,
                            'bw_service_duration_val' => $service_duration_val,
                            'bw_service_duration_unit' => $service_duration_unit,
                            'bw_is_primary' => 1
                        ]
                    );
                }

                // 5. Create Staff Schedule (Shifts)
                if ($staff_id > 0 && isset($data['staff']['shifts'])) {
                    foreach ($data['staff']['shifts'] as $day => $shift) {
                        $normalized_day = ucfirst(strtolower(sanitize_text_field($day)));
                        $sanitized_breaks = [];
                        if (isset($shift['bw_breaks']) && is_array($shift['bw_breaks'])) {
                            foreach ($shift['bw_breaks'] as $break_item) {
                                $break_start = isset($break_item['start']) ? sanitize_text_field($break_item['start']) : '';
                                $break_end = isset($break_item['end']) ? sanitize_text_field($break_item['end']) : '';
                                if (!empty($break_start) && !empty($break_end)) {
                                    $sanitized_breaks[] = [
                                        'start' => $break_start,
                                        'end' => $break_end,
                                    ];
                                }
                            }
                        }
                        $wpdb->insert(
                            $this->bwdb->get_table_name('staff_working_hours'),
                            [
                                'bw_staff_id'   => $staff_id,
                                'bw_day_name'   => $normalized_day,
                                'bw_start_time' => isset($shift['bw_start_time']) ? sanitize_text_field($shift['bw_start_time']) : '09:00',
                                'bw_end_time'   => isset($shift['bw_end_time']) ? sanitize_text_field($shift['bw_end_time']) : '17:00',
                                'bw_is_off'     => isset($shift['bw_is_off']) ? intval($shift['bw_is_off']) : 0,
                                'bw_breaks'     => wp_json_encode($sanitized_breaks)
                            ]
                        );
                    }
                }
            }

            wp_send_json_success([
                'msg' => esc_html__('Setup completed successfully!', 'bookwellnow-appointment-booking'),
                'redirect' => admin_url('admin.php?page=bookwell-shortcode-generator')
            ]);
        }

        /**
         * AJAX Handler for skipping the setup
         */
        public function bookwellab_skip_setup_func()
        {
            if (!\BookWellAB\BookWellAB_Permissions::has_permission('bookwellab_manage_settings')) {
                wp_send_json_error(['msg' => esc_html__('Unauthorized', 'bookwellnow-appointment-booking')]);
            }

            if (!check_ajax_referer('bw_wp_nonce', '_wpnonce', false)) {
                wp_send_json_error(['msg' => esc_html__('Security token mismatch.', 'bookwellnow-appointment-booking')]);
            }

            $this->bwdb->update_setting_value('general', 'setup_completed', true);

            wp_send_json_success([
                'msg' => esc_html__('Setup skipped. You can configure settings manually later.', 'bookwellnow-appointment-booking'),
                'redirect' => admin_url('admin.php?page=bookwell-shortcode-generator')
            ]);
        }
    }
}
// phpcs:enable
