<?php
// phpcs:ignoreFile WordPress.WP.I18n.TextDomainMismatch
class SLN_PaymentMethod_Paypal extends SLN_PaymentMethod_Abstract
{

    public function getFields(){
        return array(
            'pay_paypal_email',
            'pay_paypal_test'
        );
    }

    public function dispatchThankYou(SLN_Shortcode_Salon_Step $shortcode, SLN_Wrapper_Booking $booking = null){
        if (isset($_GET['op'])) {
            $op = explode('-', sanitize_text_field($_GET['op']));
            $action = $op[0];
            if ($action == 'success') {
                $booking->markPaid($_GET['PayerID']);
                return;
            } elseif ($action == 'notify') {
                $this->processIpn($op[1]);
            } elseif ($action == 'cancel') {
                return __('Your payment has not been completed', 'salon-booking-system');
            } else {
                throw new Exception('payment method operation not managed');
            }
        } elseif ($_GET['mode'] == 'paypal') {
            if ($shortcode->isAjax()) {
                    $bookUrl = str_replace(str_replace($_SERVER['REQUEST_URI'], '', SLN_Func::currPageUrl()), '', get_permalink($this->plugin->getSettings()->get('pay')));
                    $_SERVER['REQUEST_URI'] = $bookUrl.'?sln_step_page='.$shortcode->getStep(). '&submit_'.$shortcode->getStep(). '=next&mode=paypal';
                    if ($this->isPayRemainingAmount()) {
                        $_SERVER['REQUEST_URI'] = $_SERVER['REQUEST_URI'].'&pay_remaining_amount=1';
                    }
            }
            $ppl = new SLN_Payment_Paypal($this->plugin);
            $settings = $this->plugin->getSettings();
            if($settings->isPaymentDepositFixedAmount()) {
                $amount = $booking->getDeposit() > 0 ? $booking->getDeposit() : $booking->getToPayAmount(false);
            } else {
                $amount = $booking->getDeposit($booking->getToPayAmount(false)) > 0 ? $booking->getDeposit($booking->getToPayAmount(false)) : $booking->getToPayAmount(false);
            }
            $amount = $this->isPayRemainingAmount() ? $booking->getRemaingAmountAfterPay(false) : $amount;
            $url = $ppl->getUrl($booking->getId(), $amount, $booking->getTitle());
            $shortcode->redirect($url);
        } else {
            throw new Exception('payment method mode not managed');
        }
    }

    private function processIpn($id){
        $booking = $this->plugin->createBooking($id);
        $ppl = new SLN_Payment_Paypal($this->plugin);
        update_post_meta($booking->getId(), '_sln_paypal_ipn_' . uniqid(), $_POST);
        ob_end_clean();
        if ($ppl->reverseCheckIpn() && $ppl->isCompleted($this->isPayRemainingAmount() ? $booking->getRemaingAmountAfterPay(false) : $booking->getToPayAmount(false))) {
            $booking->markPaid($this->isTest() ? 'test' : $ppl->getTransactionId(), $this->isPayRemainingAmount() ? $booking->getRemaingAmountAfterPay(false) : 0);
            echo('ipn success');
        } else {
            echo('ipn_failed');
        }
    }

    private function isTest(){
        return $this->plugin->getSettings()->isPaypalTest();
    }

    private function isPayRemainingAmount(){
        return isset($_GET['pay_remaining_amount']) && $_GET['pay_remaining_amount'];
    }
}
