<?php
/**
 * Manage onboarding
 *
 * @package Booktics/Onboard
 */

namespace Booktics\Onboard;

use Booktics\Services\Schedule_Manager;
use Booktics\Settings\Settings;
use WP_Error;

/**
 * Class Onboarding
 */
class Onboarding {
    /**
     * Store onboarding fields
     *
     * @var []
     */
    protected static $fields = array(
        'business_email'    => '',
        'business_name'     => '',
        'business_type'     => '',
        'business_timezone' => '',
        'schedule'          => '',
        'custom'            => '',
        'holiday'           => '',
        'onboard_setup'     => '',
    );

    /**
     * Setup onboarding profile
     *
     * @param array $data Onboarding data
     *
     * @return  bool | WP_Error
     */
    public static function update( $data = array() ) {
        if ( $data ) {
            foreach ( $data as $key => $value ) {
                if ( ! array_key_exists( $key, self::$fields ) ) {
                    return new WP_Error(
                        'invalid_field',
                        // translators: %s is the name of the invalid field.
                        sprintf( __( 'Invalid field %s', 'booktics' ), $key ),
                        array( 'status' => 422 )
                    );
                }
            }
        }

        if ( isset( $data['schedule'] ) || isset( $data['custom'] ) || isset( $data['holiday'] ) ) {
            $schedule_manager = Schedule_Manager::make( $data );
            $schedule_manager->save();
            unset( $data['schedule'], $data['custom'], $data['holiday'] );
        }

        return Settings::update( $data );
    }

    /**
     * Get onboard field
     *
     * @param string $key Onboarding field
     *
     * @return  mixed
     */
    public static function get( $key ) {
        if ( ! array_key_exists( $key, self::$fields ) ) {
            return new WP_Error(
                'invalid_field',
                // translators: %s is the name of the invalid field.
                sprintf( __( 'Invalid field %s', 'booktics' ), $key ),
                array( 'status' => 422 )
            );
        }

        return Settings::get( $key );
    }
}
