<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;
use \Salesloo\User;

/**
 * Salesloo Checkout
 */
class Checkout extends Frontend
{

    /**
     * construction
     */
    public function __construct()
    {

        $this->id       = 'checkout';
        $this->template = 'checkout.php';
        $this->target   = 'both';
        $this->title    = 'Checkout';

        \Salesloo\Checkout::instance()->prepare();

        $product_slug = salesloo_get_current_product_slug();

        if ($product_slug) {
            $product = salesloo_get_product_by('slug', $product_slug);

            /**
             * is invalid product ? go away
             */
            if (false == $product) {
                wp_die('Invalid products');
                exit;
            };

            if ('active' != $product->status) {
                $this->template = 'checkout/product-inactive.php';
            }
        } else {
            $redirect = site_url() . '/product/';
            wp_redirect($redirect);
            exit;

            if (!is_user_logged_in()) {
                wp_die('Please loggedin first');
                exit;
            }
        }
    }


    /**
     * process_action
     *
     * @return void
     */
    public function process_action($req)
    {

        if ($req->action == 'check_username') {
            if (strlen($req->username) <= 5) {
                wp_send_json(['message' => __('To short username')], 404);
            }

            $response = User::username_exists($req->username);
            if (is_wp_error($response)) {
                wp_send_json(['message' => $response->get_error_message()], 404);
            } else {
                wp_send_json(['message' => __('Username available', 'salesloo')], 200);
            }
        }

        if ($req->action == 'check_email') {
            $response = User::email_exists($req->email);
            if (is_wp_error($response)) {
                wp_send_json(['message' => $response->get_error_message()], 400);
            } else {
                wp_send_json(['message' => __('Email available', 'salesloo')], 200);
            }
        }

        if ($req->action == 'summary') {
            $summary = \Salesloo\Checkout::instance()->summary();
            $filtered_summary = $summary;
            unset($filtered_summary['products']);
            unset($filtered_summary['total']);

            $res = [
                'summaries' => $filtered_summary,
                'total' => $summary['total']
            ];
            wp_send_json($res);
        }

        if ($req->action == 'affiliated_by') {
            $affiliate_username = \Salesloo\Checkout::instance()->affiliate_id;
            $affiliate = get_userdata($affiliate_username);
            if ($affiliate) {
                $response = [
                    'username' => $affiliate->user_login,
                    'fullname' => salesloo_user_get_name($affiliate)
                ];
            } else {
                $response = [
                    'username' => '',
                    'fullname' => ''
                ];
            }

            wp_send_json($response, 200);
        }

        if ($req->action == 'apply_coupon') {
            $apply = \Salesloo\Checkout::instance()->apply_coupon($req->code);
            if (is_wp_error($apply)) {
                wp_send_json(['message' => $apply->get_error_message()], 400);
            } else {
                wp_send_json(['message' => 'OK'], 200);
            }
        }

        if ($req->action == 'choose_payment_method') {
            $updated = \Salesloo\Checkout::instance()->choose_payment_method($req->method);
            if (is_wp_error($updated)) {
                wp_send_json(['message' => $updated->get_error_message()], 400);
            } else {
                wp_send_json(['message' => 'OK'], 200);
            }
        }

        \Salesloo\Checkout::instance()->order();
    }



    /**
     * handle load
     */
    public function load()
    {
        global $___salesloo;

        if (empty(\Salesloo\Plugin::instance()->payment_method->active())) {
            wp_die('No Payments methods enabled, Please contact admin');
        }
    }
}
