<?php
namespace BooklyOutlookCalendar\Lib\ProxyProviders;

use Bookly\Lib as BooklyLib;
use Bookly\Lib\Entities\Appointment;
use Bookly\Lib\Entities\Staff;
use Bookly\Lib\Slots\DatePoint;
use BooklyOutlookCalendar\Lib;
use BooklyPro\Lib\Config as ProConfig;

/**
 * Class Local
 * @package BooklyOutlookCalendar\Lib\ProxyProviders
 */
class Local extends BooklyLib\Proxy\OutlookCalendar
{
    /**
     * @inheritdoc
     */
    public static function syncEvent( Appointment $appointment )
    {
        if ( ! ProConfig::graceExpired() ) {
            $ms = new Lib\Microsoft\Client();
            if ( $ms->authWithStaffId( $appointment->getStaffId() ) ) {
                $ms->calendar()->syncAppointment( $appointment );
            }
        }
    }

    /**
     * @inheritdoc
     */
    public static function deleteEvent( Appointment $appointment )
    {
        if ( $appointment->hasOutlookCalendarEvent() ) {
            $ms = new Lib\Microsoft\Client();
            if ( $ms->authWithStaffId( $appointment->getStaffId() ) ) {
                // Delete existing event in Outlook Calendar.
                $ms->calendar()->deleteEvent( $appointment->getOutlookEventId() );
            }
        }
    }

    /**
     * @inheritdoc
     */
    public static function getBookings( array $staff_ids, DatePoint $dp )
    {
        $result = array();

        if ( Lib\Config::getSyncMode() == '1.5-way' ) {
            $query = Staff::query()
                ->whereIn( 'id', $staff_ids )
                ->whereNot( 'outlook_data', null )
            ;
            /** @var Staff $staff */
            foreach ( $query->find() as $staff ) {
                $ms = new Lib\Microsoft\Client();
                if ( $ms->auth( $staff ) ) {
                    $bookings = $ms->calendar()->getBookings( $dp );
                    if ( $bookings ) {
                        $result[ $staff->getId() ] = $bookings;
                    }
                }
            }
        }

        return $result;
    }

    /**
     * @inheritdoc
     */
    public static function reSync()
    {
        if ( Lib\Config::getSyncMode() == '2-way' ) {
            // Re-sync calendars.
            $ms = new Lib\Microsoft\Client();
            foreach ( BooklyLib\Entities\Staff::query()->whereNot( 'visibility', 'archive' )->find() as $staff ) {
                if ( $ms->auth( $staff ) && $ms->calendar()->clearDeltaLink()->sync() ) {
                    $ms->calendar()->createSubscription();
                }
            }
        }
    }
}