<?php
namespace BooklyOutlookCalendar\Backend\Modules\Settings\ProxyProviders;

use Bookly\Lib as BooklyLib;
use Bookly\Backend\Components\Settings\Menu;
use Bookly\Backend\Modules\Settings\Proxy;
use BooklyOutlookCalendar\Lib;

/**
 * Class Shared
 * @package BooklyOutlookCalendar\Backend\Modules\Settings\ProxyProviders
 */
class Shared extends Proxy\Shared
{
    /**
     * @inheritdoc
     */
    public static function renderMenuItem()
    {
        Menu::renderItem( esc_html__( 'Outlook Calendar', 'bookly' ), 'outlook_calendar' );
    }

    /**
     * @inheritdoc
     */
    public static function renderTab()
    {
        $fetch_limits = array(
            array( '0', esc_html__( 'Disabled', 'bookly' ) ),
            array( 25, 25 ),
            array( 50, 50 ),
            array( 100, 100 ),
            array( 250, 250 ),
            array( 500, 500 ),
            array( 999, 999 ),
        );

        self::renderTemplate( 'settings_tab', compact( 'fetch_limits' ) );
    }

    /**
     * @inheritdoc
     */
    public static function saveSettings( array $alert, $tab, array $params )
    {
        if ( $tab == 'outlook_calendar' ) {
            update_option( 'bookly_oc_app_id', $params['bookly_oc_app_id'] );
            update_option( 'bookly_oc_app_secret', $params['bookly_oc_app_secret'] );
            update_option( 'bookly_oc_sync_mode', $params['bookly_oc_sync_mode'] );
            update_option( 'bookly_oc_limit_events', $params['bookly_oc_limit_events'] );
            update_option( 'bookly_oc_full_sync_offset_days', $params['bookly_oc_full_sync_offset_days'] );
            update_option( 'bookly_oc_full_sync_titles', $params['bookly_oc_full_sync_titles'] );
            update_option( 'bookly_oc_event_title', $params['bookly_oc_event_title'] );
            update_option( 'bookly_oc_event_client_info', $params['bookly_oc_event_client_info'] );
            update_option( 'bookly_oc_event_appointment_info', $params['bookly_oc_event_appointment_info'] );

            $app_id     = $params['bookly_oc_app_id'];
            $app_secret = $params['bookly_oc_app_secret'];
            $sync_mode  = $params['bookly_oc_sync_mode'];
            $ms         = new Lib\Microsoft\Client();
            if ( $sync_mode == '2-way' && $app_id != '' && $app_secret != '' ) {
                foreach ( BooklyLib\Entities\Staff::query()->find() as $staff ) {
                    if ( $ms->auth( $staff ) ) {
                        $ms->calendar()->sync();
                        // Create new notification subscriptions.
                        if ( ! $ms->calendar()->createSubscription() ) {
                            $alert['error'] = $ms->getErrors();
                            break;
                        }
                    }
                }
            }
            $alert['success'][] = esc_html__( 'Settings saved.', 'bookly' );
        }

        return $alert;
    }
}