<?php

namespace Salesloo\Rest_Api;

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

use \Salesloo\Abstracts\Rest_Api;


/**
 * Coupon
 */
class Coupon extends Rest_Api
{
    protected $version = 'v1';

    protected $route = 'coupon';

    /**
     * register new route
     * 
     */
    public function register_routes()
    {
        register_rest_route(
            $this->namespace,
            '/' . $this->version . '/' . $this->route . '/apply',
            [
                'methods'             => \WP_REST_Server::CREATABLE,
                'callback'            => [$this, 'apply'],
                'permission_callback' => [$this, 'permissions_apply'],
            ],
        );
    }

    /**
     * apply coupon permissions
     */
    public function permissions_apply(\WP_REST_Request $request)
    {
        $params = $request->get_params();

        if (isset($params['nonce']) && salesloo_verify_nonce($params['nonce'])) {
            return true;
        }

        return false;
    }

    /**
     * apply coupon
     */
    public function apply(\WP_REST_Request $request)
    {
        $params = $request->get_params();

        $respons = [
            'message' => __('Bad or Invalid Request', 'salesloo')
        ];

        if (!isset($params['code']) || !$params['code'] || !isset($_COOKIE['wp_salesloo_cart'])) {
            return new \WP_REST_Response($respons, 400);
        }

        $cart_key = sanitize_text_field($_COOKIE['wp_salesloo_cart']);
        $cookie   = json_decode(salesloo_decrypt($cart_key), true);

        if (!isset($cookie[0]) || !isset($cookie[1])) {
            return new \WP_REST_Response($respons, 400);
        }

        $cart_id      = intval($cookie[0]);
        $product_slug = sanitize_text_field($cookie[1]);
        $cart_id      = intval($cookie[0]);
        $cart         = salesloo_get_cart($cart_id);

        if (false == $cart || !isset($cart->products[$product_slug])) {
            return new \WP_REST_Response($respons, 400);
        }

        $product_id = $cart->products[$product_slug]->ID;
        $code       = sanitize_text_field($params['code']);
        $coupon     = \Salesloo\Models\Coupon::join('right', 'salesloo_coupon_code', ['ID', 'coupon_id', '='])
            ->query('WHERE status = "active" AND code = %s AND products LIKE %s', $code, '%"' . $product_id . '"%')->first();

        if ($coupon->ID <= 0) {
            $respons['message'] = __('Coupon code not found, expired or has exceeded usage, Please try with another code', 'salesloo');
            return new \WP_REST_Response($respons, 404);
        }

        $cart_args = [
            'ID' => $cart_id,
            'coupon' => $coupon
        ];

        $affiliated_by = '';

        if ($coupon->user_id) {
            $affiliate = get_userdata($coupon->user_id);
            if ($affiliate) {

                $cart_args['affiliate'] = $affiliate;
                salesloo_set_affiliate_cookie($affiliate->user_login);
                $affiliated_by = salesloo_affiliated_by($affiliate->user_login);
            }
        }

        salesloo_update_cart($cart_args);

        $summary = salesloo_summary($cart_id, $product_id);
        $summary = salesloo_checkout_print_summary($summary);

        $respons = [
            'message' => __('Congratulations your coupon code is valid'),
            'affiliated_by' => $affiliated_by,
            'coupon' => [
                'code'    => sanitize_text_field($params['code']),
                'nonce'   => salesloo_create_nonce(),
            ]
        ];

        $respons['summary'] = $summary['summary'];
        $respons['total'] = $summary['total'];

        return new \WP_REST_Response($respons, 200);
    }



    /**
     * Settings Constructor
     */
    public function __construct()
    {

        add_action('salesloo/rest_api/init', [$this, 'register_route']);
    }
}
