<?php

namespace Bookify\Controllers\REST;

use WP_Error;
use WP_REST_Response;
use WP_Query;
use Bookify\Models\Bookify_Category_Models;
use Bookify\Models\Bookify_Service_Models;
use Bookify\Controllers\Bookify_Helper;

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

if ( ! class_exists( 'Bookify_Onboarding_Rest_API' ) ) {

    class Bookify_Onboarding_Rest_API {

        public function __construct() {
            add_action( 'rest_api_init', array( $this, 'register_routes' ) );
        }

        public function register_routes() {
            register_rest_route('bookify/v1/onboarding', '/ensure-defaults', array(
                'methods'               => 'POST',
                'callback'              => array( $this, 'ensure_defaults_callback' ),
                'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
            ));

            register_rest_route('bookify/v1/onboarding', '/complete', array(
                'methods'               => 'POST',
                'callback'              => array( $this, 'complete_callback' ),
                'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
            ));

            register_rest_route('bookify/v1/onboarding', '/skip-wizard', array(
                'methods'               => 'POST',
                'callback'              => array( $this, 'bookify_skip_wizard_callback' ),
                'permission_callback'   => array( $this, 'verify_nonce_and_permissions' )
            ));
        }

        public function verify_nonce_and_permissions( $request ) {
            $nonce = $request->get_header('X-WP-Nonce');

            if ( ! is_user_logged_in() ) {
                return new WP_Error( 'rest_forbidden', __('You are not logged in.', 'bookify'), array( 'status' => 401 ) );
            }

            if ( ! current_user_can( 'manage_options' ) ) {
                return new WP_Error( 'rest_forbidden', __('You do not have permission to access this resource.', 'bookify'), array( 'status' => 403 ) );
            }

            if ( ! $nonce || ! wp_verify_nonce( $nonce, 'wp_rest' ) ) {
                return new WP_Error( 'rest_forbidden', __('Invalid nonce.', 'bookify'), array( 'status' => 403 ) );
            }

            return true;
        }

        public function bookify_skip_wizard_callback( $request ) {
            update_option( 'bookify_onboarding_completed', true );
            return new WP_REST_Response(array(
                'success' => true,
            ), 200);
        }
        
        public function ensure_defaults_callback( $request ) {
            $existing = Bookify_Category_Models::bookify_get_all_service_categories();
            $uncat_id = 0;
            if ( is_array( $existing ) ) {
                foreach ( $existing as $cat ) {
                    if ( strtolower( $cat['category_name'] ) === 'uncategorized' ) {
                        $uncat_id = (int) $cat['id'];
                        break;
                    }
                }
            }

            if ( ! $uncat_id ) {
                $uncat_id = Bookify_Category_Models::bookify_add_service_category( array(
                    'category_name' => 'Uncategorized',
                    'category_slug' => 'uncategorized',
                ) );
            }

            return new WP_REST_Response(array(
                'success' => true,
                'category_id' => $uncat_id,
            ), 200);
        }

        public function create_pages_callback( $params ) {
            $form_page = $this->maybe_create_page( 'Appointment Bookings', '[bookify_bookings theme="' . $params['theme'] . '"]' );
            $apt_page = $this->maybe_create_page( 'My Appointments', '[bookify_appointments]' );

            return new WP_REST_Response(array(
                'success' => true,
                'form' => array(
                    'id' => $form_page['id'],
                    'url' => $form_page['url'],
                    'shortcode' => '[bookify_bookings theme="' . $params['theme'] . '"]'
                ),
                'appointments' => array(
                    'id' => $apt_page['id'],
                    'url' => $apt_page['url'],
                    'shortcode' => '[bookify_appointments]'
                ),
            ), 200);
        }

        private function maybe_create_page( $title, $shortcode ) {
            $page = new WP_Query( array(
                'title' => $title,
                'post_type' => 'page',
                'post_status' => 'publish',
                'posts_per_page' => 1,
            ) );

            if ( ! $page->have_posts() ) {
                $page_id = wp_insert_post( array(
                    'post_title' => $title,
                    'post_status' => 'publish',
                    'post_type' => 'page',
                    'post_content' => $shortcode,
                ) );
            } else {
                $page_id = $page->posts[0]->ID;
                if ( false === strpos( $page->posts[0]->post_content, $shortcode ) ) {
                    wp_update_post( array(
                        'ID' => $page_id,
                        'post_content' => $page->posts[0]->post_content . "\n\n" . $shortcode,
                    ) );
                }
            }
            return array(
                'id' => $page_id,
                'url' => get_permalink( $page_id ),
            );
        }

        public function complete_callback( $request ) {

            $params = $request->get_json_params();

            if ( isset( $params['company'] ) ) {
                $company = wp_unslash( $params['company'] );
                $company_sanitized = array(
                    'companyName' => isset($company['companyName']) ? sanitize_text_field($company['companyName']) : '',
                    'address' => isset($company['address']) ? sanitize_text_field($company['address']) : '',
                    'phoneNumber' => isset($company['phoneNumber']) ? sanitize_text_field($company['phoneNumber']) : '',
                    'website' => isset($company['website']) ? sanitize_text_field($company['website']) : '',
                    'image' => isset($company['image']) ? esc_url_raw($company['image']) : '',
                );
                update_option( 'bookify_company_details', $company_sanitized );
            }

            if ( isset( $params['general'] ) ) {
                $g = wp_unslash( $params['general'] );
                $general = array();
                $general['DefaultGlobalSlotTimeDuration'] = isset($g['DefaultGlobalSlotTimeDuration']) ? sanitize_text_field($g['DefaultGlobalSlotTimeDuration']) : '30';
                $general['DefaultGlobalSlotTimeInterval'] = isset($g['DefaultGlobalSlotTimeInterval']) ? sanitize_text_field($g['DefaultGlobalSlotTimeInterval']) : '15';
                $general['DefaultWeekStartOn'] = isset($g['DefaultWeekStartOn']) ? sanitize_text_field($g['DefaultWeekStartOn']) : 'Monday';
                $general['DefaultTimeFormat'] = isset($g['DefaultTimeFormat']) ? sanitize_text_field($g['DefaultTimeFormat']) : '12-hour';
                $general['DefaultDateFormat'] = isset($g['DefaultDateFormat']) ? sanitize_text_field($g['DefaultDateFormat']) : 'DD/MM/YY';
                $general['DefaultGeneralCurrencies'] = isset($g['DefaultGeneralCurrencies']) ? sanitize_text_field($g['DefaultGeneralCurrencies']) : 'USD';
                update_option( 'bookify_general_settings', $general );
            }

            $created_services = array();
            if ( isset( $params['services'] ) && is_array( $params['services'] ) ) {
                $existing = Bookify_Category_Models::bookify_get_all_service_categories();
                $uncat_id = 0;
                if ( is_array( $existing ) ) {
                    foreach ( $existing as $cat ) {
                        if ( strtolower( $cat['category_name'] ) === 'uncategorized' ) {
                            $uncat_id = (int) $cat['id'];
                            break;
                        }
                    }
                }
                if ( ! $uncat_id ) {
                    $uncat_id = Bookify_Category_Models::bookify_add_service_category( array(
                        'category_name' => 'Uncategorized',
                        'category_slug' => 'uncategorized',
                    ) );
                }

                foreach ( $params['services'] as $svc ) {
                    $name = isset($svc['name']) ? sanitize_text_field($svc['name']) : '';
                    $price = isset($svc['price']) ? sanitize_text_field(abs( $svc['price'] )) : '0';
                    if ( empty($name) ) continue;
                    $service_id = Bookify_Service_Models::bookify_add_service( array(
                        'service_name' => $name,
                        'service_price' => $price,
                        'service_category' => $uncat_id,
                        'service_location' => '[]',
                        'service_img' => '',
                        'service_note' => '',
                    ) );
                    if ( $service_id ) {
                        $created_services[ $service_id ] = array(
                            'checked' => true,
                            'price' => $price
                        );
                    }
                }
            }

            if ( isset( $params['staff'] ) ) {
                $current_user = wp_get_current_user();

                if ( in_array( 'administrator', (array) $current_user->roles ) && !in_array( 'bookify-staff', (array) $current_user->roles ) ) {
                    $current_user->add_role( 'bookify-staff' );
                } elseif ( in_array( 'bookify-staff', (array) $current_user->roles ) ) {
                    // already staff, do nothing
                } else {
                    $current_user->add_role( 'bookify-staff' );
                }

                $slot_duration = isset($params['general']['DefaultGlobalSlotTimeDuration']) ? sanitize_text_field($params['general']['DefaultGlobalSlotTimeDuration']) : '30';
                $slot_interval = isset($params['general']['DefaultGlobalSlotTimeInterval']) ? sanitize_text_field($params['general']['DefaultGlobalSlotTimeInterval']) : '15';

                $schedule = isset( $params['staff']['schedule'] ) ? $params['staff']['schedule'] : array();
              
                if ( empty( $schedule ) ) {
                    $days = array('Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday');
                    foreach ( $days as $d ) {
                        $schedule[] = array('day'=>$d,'isOpen'=>true,'from'=>'09:00 AM','to'=>'05:00 PM','breaks'=>array());
                    }
                }
                $timeslots = Bookify_Helper::bookify_split_time( $schedule, $slot_duration, $slot_interval );     
                $staff_services = !empty($params['staff']['services']) ? $params['staff']['services'] : $created_services;
                $formatted_staff_services = array();
                
                foreach ( $staff_services as $service_id => $service_data ) {
                    if ( is_array( $service_data ) && isset( $service_data['checked'] ) ) {
                        $formatted_staff_services[ $service_id ] = array(
                            'checked' => true,
                            'price' => isset( $service_data['price'] ) ? $service_data['price'] : '0'
                        );
                    } elseif ( is_numeric( $service_id ) ) {
                        $formatted_staff_services[ $service_id ] = array(
                            'checked' => true,
                            'price' => isset( $service_data['price'] ) ? $service_data['price'] : '0'
                        );
                    }
                }
                
                update_user_meta( $current_user->ID, 'bookify_staff_services', wp_json_encode( $formatted_staff_services ) );
                update_user_meta( $current_user->ID, 'bookify_staff_slot_duration', $slot_duration );
                update_user_meta( $current_user->ID, 'bookify_staff_slot_interval', $slot_interval );
                update_user_meta( $current_user->ID, 'bookify_staff_schedule', wp_json_encode( $schedule ) );
                update_user_meta( $current_user->ID, 'bookify_staff_timeslots', $timeslots );
            }

            $pages = array();
            if ( isset( $params['createPages'] ) && $params['createPages'] ) {
                $pages = $this->create_pages_callback( $params )->get_data();
            }

            update_option( 'bookify_onboarding_completed', true );
            return new WP_REST_RESPONSE( array(
                'success' => true,
                'pages' => $pages,
            ), 200 );
        }
    }
    
    new Bookify_Onboarding_Rest_API();
}