<?php

namespace Salesloo\Frontend;

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

use \Salesloo\Abstracts\Frontend;

/**
 * Affiliate withdrawal page
 */
class Affiliate_Withdrawal extends Frontend
{

    /**
     * construction
     */
    public function __construct()
    {
        $this->id       = 'affiliate/withdrawal';
        $this->template = 'affiliate-withdrawal.php';
        $this->target   = 'user';
        $this->title    = __('Affiliate Withdrawal', 'salesloo');
    }

    public function process_action($req)
    {
        global $___salesloo, $wpdb;

        $input = file_get_contents("php://input");
        $request = json_decode($input, true);

        if (isset($_POST['add_withdrawal_method']) && salesloo_verify_nonce($_POST['add_withdrawal_method'])) {
            $types = salesloo_commissions_withdrawal_method_types();
            $meta_key = 'salesloo_commissions_withdrawal_methods';

            $type = sanitize_text_field($_POST['type']);
            $new_methods = [
                'name' => $types[$type]['title'],
                'value' => sanitize_textarea_field($_POST['value'])
            ];

            add_user_meta(get_current_user_id(), wp_unslash($meta_key), $new_methods);

            $methods = salesloo_get_commissions_withdrawal_methods();

            $___salesloo['alert'] = [
                'type' => 'success',
                'message' => __('Method added', 'salesloo')
            ];
        }

        if (isset($request['nonce']) && salesloo_verify_nonce($request['nonce'])) {
            if (isset($request['action'])) {

                if ($request['action'] == 'delete_method') {

                    $umeta_id = intval($request['id']);
                    $user_id = get_current_user_id();

                    $is_delete = $wpdb->delete($wpdb->usermeta, ['umeta_id' => $umeta_id, 'user_id' => $user_id]);

                    $methods = salesloo_get_commissions_withdrawal_methods();

                    if ($is_delete) {
                        $respons = [
                            'message' => __('Method deleted', 'salesloo'),
                            'methods' => $methods
                        ];
                        header("HTTP/1.0 200 OK");
                    } else {
                        $respons = [
                            'message' => __('Failed to delete method', 'salesloo'),
                            'methods' => $methods
                        ];
                        header("HTTP/1.0 400 BAD Request");
                    }

                    echo json_encode($respons);
                    exit;
                }
            }
        }
    }

    public function load()
    {
        global $___salesloo;
    }
}
