<?php

namespace Salesloo\Admin;

use \Salesloo\Admin_Ajax;
use \Salesloo\Plugin;

/**
 * Admin Affiliate Payout classes
 */
class Affiliate_Payout
{
    private $admin_ajax;

    /**
     * __construct
     *
     * @return void
     */
    public function __construct()
    {

        $this->admin_ajax = new Admin_Ajax;
    }

    /**
     * return dashboard template
     *
     * @return void
     */
    public static function template()
    {
        salesloo_hidding_wp_admin_notices();

        $x_data = [
            'reload' => '',
            'loader' => '...',
        ];

        include salesloo_get_template('admin/affiliate-payout.php');
        return;
    }


    public function ajax_get_affiliate_payout()
    {
        global $wpdb;

        $this->admin_ajax->verify_nonce($_GET['nonce'], 'salesloo_get_affiliate_payout');

        $per_page  = 5;
        $paged     = isset($_GET['paged']) ? intval($_GET['paged']) : 1;
        $offset    = ($paged - 1) * $per_page;
        $search    = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';


        $commission = $wpdb->prefix . 'salesloo_commission';
        $user = $wpdb->users;


        if ($search) {
            $search = "AND ({$user}.user_login LIKE '%$search%' OR {$user}.user_email LIKE '%$search%' OR {$user}.display_name LIKE '%$search%' OR {$user}.user_nicename LIKE '%$search%')";
        }

        $query =
            "SELECT SQL_CALC_FOUND_ROWS
                {$user}.ID as user_id,
                {$user}.user_login as username,
                SUM(amount) as unpaid

            FROM $commission

            LEFT JOIN $user
                ON {$user}.ID = {$commission}.user_id
            
            WHERE {$commission}.status = 'unpaid'
            
            $search

            GROUP BY {$commission}.user_id

            ORDER BY unpaid DESC

            LIMIT %d OFFSET %d";

        $results = $wpdb->get_results($wpdb->prepare($query, $per_page, $offset));
        $found = $wpdb->get_var('SELECT FOUND_ROWS()');

        $items = [];
        foreach ($results as $item) {
            $item->name = salesloo_user_get_name($item->user_id);

            $avatar = get_user_meta($item->user_id, 'avatar', true);
            if (empty($avatar)) {
                $avatar = get_avatar_url($item->user_id);
            }

            if (empty($avatar)) {
                $avatar = 'https://ui-avatars.com/api/?name=' . urlencode($item->name);
            }

            $methods = Plugin::instance()->affiliate->commission_payout_methods(absint($item->user_id));
            $options = [];
            $i = 0;
            foreach ($methods as $method) {
                $i++;
                $name = str_replace(array("\n", "\r\n", "\r"), ' ', $method['name']);
                $value = str_replace(array("\n", "\r\n", "\r"), ' ', $method['value']);
                $options[] = [
                    'value' => $name . ': ' . $value,
                    'label' => $name . ': ' . $value,
                    'id' => $i
                ];
            }

            $item->avatar = $avatar;
            $item->class = 'hidden';
            $item->payout_methods = $options;
            $item->payout = [
                'affiliate_id' => $item->user_id,
                'amount' => $item->unpaid,
                'method' => '',
                'pop' => [
                    'id' => '',
                    'url' => ''
                ],
                'note' => ''
            ];
            $item->unpaid = salesloo_convert_money($item->unpaid);

            $items[] = $item;
        }

        $data = [
            'items'    => $items,
            'total'    => $found,
            'paged'    => $paged,
            'pages'    => ceil($found / $per_page),
            'per_page' => $per_page,
        ];

        wp_send_json($data);
    }

    public function ajax_mark_commission_paid()
    {
        global $wpdb;

        $this->admin_ajax->verify_nonce($_REQUEST['nonce'], 'salesloo_mark_commission_paid');

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

        $args = [
            'user_id'          => intval($data['affiliate_id']),
            'amount'           => intval($data['amount']),
            'method'           => sanitize_text_field($data['method']),
            'note'             => sanitize_text_field($data['note']),
            'proof_of_payment' => intval($data['pop']['id'])
        ];

        $inserted = salesloo_insert_commission_withdrawal($args);

        if (!is_wp_error($inserted)) {

            $query = "UPDATE
                {$wpdb->prefix}salesloo_commission

                SET status = %s
                
                WHERE user_id = %d

                AND status = 'unpaid'
            ";
            $wpdb->query($wpdb->prepare($query, 'paid', $args['user_id']));

            $data = [
                'withdrawal_id' => $inserted
            ];

            salesloo_add_notification('commission_paid', $data);
            salesloo_add_event('commission_paid', $data);

            wp_send_json(['message' => 'success'], 200);
        } else {
            wp_send_json(['message' => $inserted->get_error_message()], 500);
        }
    }

    public function ajax_get_withdrawals()
    {
        global $wpdb;

        $this->admin_ajax->verify_nonce($_GET['nonce'], 'salesloo_get_withdrawals');

        $per_page  = 10;
        $paged     = isset($_GET['paged']) ? intval($_GET['paged']) : 1;
        $offset    = ($paged - 1) * $per_page;
        $search    = isset($_GET['search']) ? sanitize_text_field($_GET['search']) : '';


        $withdrawal = $wpdb->prefix . 'salesloo_commission_withdrawal';
        $user = $wpdb->users;


        if ($search) {
            $search = "AND ({$user}.user_login LIKE '%$search%' OR {$user}.user_email LIKE '%$search%' OR {$user}.display_name LIKE '%$search%' OR {$user}.user_nicename LIKE '%$search%')";
        }

        $query =
            "SELECT SQL_CALC_FOUND_ROWS
                {$withdrawal}.*,
                {$user}.user_login as username

            FROM $withdrawal

            LEFT JOIN $user
                ON {$user}.ID = {$withdrawal}.user_id
            
            $search

            ORDER BY {$withdrawal}.ID DESC

            LIMIT %d OFFSET %d";

        $results = $wpdb->get_results($wpdb->prepare($query, $per_page, $offset));
        $found = $wpdb->get_var('SELECT FOUND_ROWS()');

        $items = [];
        foreach ($results as $item) {
            $item->name = salesloo_user_get_name($item->user_id);
            $item->proof_of_payment = wp_get_attachment_url(intval($item->proof_of_payment));

            $items[] = $item;
        }

        $data = [
            'items'    => $items,
            'total'    => $found,
            'paged'    => $paged,
            'pages'    => ceil($found / $per_page),
            'per_page' => $per_page,
        ];

        wp_send_json($data);
    }


    public function install_hooks()
    {
        add_action('wp_ajax_salesloo_get_affiliate_payout', [$this, 'ajax_get_affiliate_payout']);
        add_action('wp_ajax_salesloo_get_withdrawals', [$this, 'ajax_get_withdrawals']);
        add_action('wp_ajax_salesloo_mark_commission_paid', [$this, 'ajax_mark_commission_paid']);
    }
}
