<?php

namespace Salesloo\Admin;

use \Salesloo\Admin_Ajax;

/**
 * Admin Affiliates classes
 */
class Affiliate_Commission
{
    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 = [
            'filter' => [
                'product_id' => 'all',
                'daterange' => date('Y-m-d', strtotime('-30 day')) . ' - ' . date('Y-m-d')
            ],
            'loader' => '...',
        ];

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

    /**
     * split_daterange
     *
     * @param  string $daterange
     * @param  bool $time
     * @return object
     */
    private function split_daterange($daterange, $time = false)
    {
        global $wpdb;

        if ($daterange) {
            $date = explode(' - ', $daterange);
            $date_start = date('Y-m-d', strtotime($date[0]));
            $date_end = isset($date[1]) ? date('Y-m-d', strtotime($date[1])) : date('Y-m-d', strtotime($date[0]));
        } else {
            $first_data = $wpdb->get_row("SELECT ID,created_at FROM {$wpdb->prefix}salesloo_invoice ORDER BY created_at ASC");
            $date_start = $first_data->created_at ? date('Y-m-d', strtotime($first_data->created_at)) : '2000-01-01';
            $date_end = date('Y-m-d');
        }

        return (object)[
            'start' => $time ? date('Y-m-d 00:00:00', strtotime($date_start)) : $date_start,
            'end' => $time ? date('Y-m-d 23:59:59', strtotime($date_end)) : $date_end
        ];
    }

    public function ajax_get_commission_stat()
    {
        global $wpdb;

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

        $daterange     = isset($_GET['date']) ? sanitize_text_field($_GET['date']) : '';
        $products = isset($_GET['product_id']) ? $_GET['product_id'] : 'all';

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

        if ($products == 'all' || empty($products)) {
            $products = "SELECT ID FROM {$wpdb->prefix}salesloo_product";
        } else {
            $products = is_array($products) ? implode('\',\'', array_map('sanitize_text_field', $products)) : sanitize_text_field($products);
            $products = "'$products'";
        }

        $date = $this->split_daterange($daterange);

        $query =
            "SELECT
                SUM(
                    CASE 
                    WHEN {$commission}.status IN ('paid', 'unpaid')
                    AND {$commission}.product_id IN ($products)
                    AND DATE({$commission}.created_at) BETWEEN '$date->start' AND '$date->end'
                    THEN {$commission}.amount ELSE 0 END
                ) AS total,
                SUM(
                    CASE 
                    WHEN {$commission}.status IN ('paid')
                    AND {$commission}.product_id IN ($products)
                    AND DATE({$commission}.created_at) BETWEEN '$date->start' AND '$date->end'
                    THEN {$commission}.amount ELSE 0 END
                ) AS paid,
                SUM(
                    CASE 
                    WHEN {$commission}.status IN ('unpaid')
                    AND {$commission}.product_id IN ($products)
                    AND DATE({$commission}.created_at) BETWEEN '$date->start' AND '$date->end'
                    THEN {$commission}.amount ELSE 0 END
                ) AS unpaid

            FROM $commission
            
            WHERE DATE({$commission}.created_at) BETWEEN '$date->start' AND '$date->end'";

        $commission = $wpdb->get_row($query);

        $result = [
            'total'  => salesloo_convert_money($commission->total),
            'paid'   => salesloo_convert_money($commission->paid),
            'unpaid' => salesloo_convert_money($commission->unpaid)
        ];

        wp_send_json($result);
    }

    public function ajax_get_affiliate_commissions()
    {
        global $wpdb;

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

        $daterange = isset($_GET['date']) ? sanitize_text_field($_GET['date']) : '';
        $products  = isset($_GET['product_id']) ? $_GET['product_id'] : 'all';
        $user_id   = isset($_GET['user_id']) ? $_GET['user_id'] : 'all';
        $short     = isset($_GET['short']) && in_array($_GET['short'], ['total', 'unpaid', 'paid']) ? sanitize_text_field($_GET['short']) : 'total';
        $per_page  = 20;
        $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 ($products == 'all' || empty($products)) {
            $products = "SELECT ID FROM {$wpdb->prefix}salesloo_product";
        } else {
            $products = is_array($products) ? implode('\',\'', array_map('sanitize_text_field', $products)) : sanitize_text_field($products);
            $products = "'$products'";
        }

        if ($user_id == 'all' || empty($user_id)) {
            $user_ids = "SELECT ID FROM $wpdb->users";
        } else {
            $user_ids = is_array($user_id) ? implode('\',\'', array_map('sanitize_text_field', $user_id)) : intval($user_id);
            $user_ids = "'$user_ids'";
        }

        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%')";
        }

        $date = $this->split_daterange($daterange);

        $query =
            "SELECT SQL_CALC_FOUND_ROWS
                {$user}.ID as user_id,
                {$user}.user_login as username,
                SUM(
                    CASE
                    WHEN status IN ('paid', 'unpaid')
                    AND {$commission}.product_id IN ($products)
                    AND DATE({$commission}.created_at) BETWEEN '$date->start' AND '$date->end'
                    THEN amount ELSE 0 END
                ) as total,
                SUM(
                    CASE
                    WHEN status = 'paid'
                    AND {$commission}.product_id IN ($products)
                    AND DATE({$commission}.created_at) BETWEEN '$date->start' AND '$date->end'
                    THEN amount ELSE 0 END
                ) as paid,
                SUM(
                    CASE
                    WHEN status = 'unpaid'
                    AND {$commission}.product_id IN ($products)
                    AND DATE({$commission}.created_at) BETWEEN '$date->start' AND '$date->end'
                    THEN amount ELSE 0 END
                ) as unpaid

            FROM $user

            LEFT JOIN $commission
                ON {$user}.ID = {$commission}.user_id
            
            WHERE {$user}.ID IN($user_ids) $search

            GROUP BY {$user}.ID

            ORDER BY $short 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);
            }

            $item->avatar = $avatar;
            $item->total = salesloo_convert_money($item->total);
            $item->paid = salesloo_convert_money($item->paid);
            $item->unpaid = salesloo_convert_money($item->unpaid);
            $item->link = admin_url('admin.php?page=salesloo-affiliate&affiliate_id=' . $item->user_id);

            $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_commission_stat', [$this, 'ajax_get_commission_stat']);
        add_action('wp_ajax_salesloo_get_affiliate_commissions', [$this, 'ajax_get_affiliate_commissions']);
    }
}
