<?php
namespace BooklyCustomerCabinet\Frontend\Components\Dialogs\Cancel;

use Bookly\Lib as BooklyLib;

/**
 * Class Ajax
 * @package BooklyCustomerCabinet\Frontend\Components\Dialogs\Cancel
 */
class Ajax extends BooklyLib\Base\Ajax
{
    /**
     * @inheritdoc
     */
    protected static function permissions()
    {
        return array(
            '_default' => 'user',
        );
    }

    /**
     * Cancel appointment
     */
    public static function cancelAppointment()
    {
        $customer    = BooklyLib\Entities\Customer::query()->where( 'wp_user_id', get_current_user_id() )->findOne();
        $customer_id = $customer->getId();

        $ca_id = self::parameter( 'ca_id' );

        $ca = BooklyLib\Entities\CustomerAppointment::find( $ca_id );
        if ( $ca->getCustomerId() == $customer_id ) {
            $appointment = new BooklyLib\Entities\Appointment();
            if ( $appointment->load( $ca->getAppointmentId() ) ) {
                $allow_cancel_time = strtotime( $appointment->getStartDate() ) - (int) BooklyLib\Proxy\Pro::getMinimumTimePriorCancel();
                if ( $appointment->getStartDate() === null || current_time( 'timestamp' ) <= $allow_cancel_time ) {
                    $ca->cancel();

                    wp_send_json_success();
                }
            }
        }

        wp_send_json_error();
    }
}