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

use Bookly\Lib as BooklyLib;

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

    /**
     * Check if future appointments exists to deny delete account
     */
    public static function checkFutureAppointments()
    {
        /** @var BooklyLib\Entities\Customer $customer */
        $customer    = BooklyLib\Entities\Customer::query()->where( 'wp_user_id', get_current_user_id() )->findOne();
        $customer_id = $customer->getId();

        if ( $customer_id && ! self::_checkFutureAppointments( $customer_id ) ) {
            wp_send_json_success();
        }

        wp_send_json_error();
    }

    /**
     * Delete profile
     */
    public static function deleteProfile()
    {
        /** @var BooklyLib\Entities\Customer $customer */
        $customer    = BooklyLib\Entities\Customer::query()->where( 'wp_user_id', get_current_user_id() )->findOne();
        $customer_id = $customer->getId();

        if ( $customer_id && ! self::_checkFutureAppointments( $customer_id ) ) {
            $customer->deleteWithWPUser( false );
            wp_delete_user( get_current_user_id() );
        }

        wp_send_json_success();
    }

    /**
     * @param $customer_id
     * @return bool
     */
    private static function _checkFutureAppointments( $customer_id )
    {
        return BooklyLib\Entities\CustomerAppointment::query( 'ca' )
            ->leftJoin( 'Appointment', 'a', 'a.id = ca.appointment_id' )
            ->where( 'ca.customer_id', $customer_id )
            ->whereRaw( 'a.start_date >= %s OR a.start_date IS NULL', array( current_time( 'mysql' ) ) )
            ->whereIn( 'ca.status', BooklyLib\Proxy\CustomStatuses::prepareBusyStatuses( array(
                BooklyLib\Entities\CustomerAppointment::STATUS_APPROVED,
                BooklyLib\Entities\CustomerAppointment::STATUS_PENDING
            ) ) )
            ->count() > 0;
    }
}