<?php

namespace Lknwp\CrowdfundingExtension\Includes\elementorFields\helpers;

if (! defined('ABSPATH')) {
    exit;
}

class LknwpCrowdfundingListingFunctions
{
    /**
     * Obtem a localização da campanha.
     */
    public static function campaign_location()
    {
        global $post;

        $country = get_post_meta($post->ID, 'wpneo_country', true);
        $location = get_post_meta($post->ID, '_nf_location', true);
        $country_name = '';

        if (class_exists('WC_Countries')) {
            $countries_obj = new \WC_Countries();
            $countries = $countries_obj->__get('countries');
            if ($country) {
                $country_name = $countries[$country];
                $location = $location . ', ' . $country_name;
            }
        }

        return $location ?: __('Unknown', 'link-nacional-wp-crowdfunding-extension');
    }

    /**
     * Obtem a porcentagem arrecadada.
     *
     * @param int $campaign_id ID da campanha.
     * @return float Porcentagem arrecadada.
     */
    public function get_raised_percent($campaign_id = 0)
    {
        if ($campaign_id == 0) {
            return 0;
        }

        $total = $this->get_total_fund($campaign_id);
        $goal = $this->get_total_goal($campaign_id);

        if ($total > 0 && $goal > 0) {
            return ($goal < $total) ? 100 : round($total / $goal * 100, 2);
        }

        return 0;
    }

    /**
     * Obtem o total arrecadado.
     *
     * @param int $campaign_id ID da campanha.
     * @return float Total arrecadado.
     */
    public function get_total_fund($campaign_id)
    {
        global $wpdb;

        $result = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT
                SUM(ltoim.meta_value) as total_sales_amount
            FROM
                {$wpdb->prefix}woocommerce_order_itemmeta woim
            LEFT JOIN
                {$wpdb->prefix}woocommerce_order_items oi ON woim.order_item_id = oi.order_item_id
            LEFT JOIN
                {$wpdb->prefix}posts wpposts ON order_id = wpposts.ID
            LEFT JOIN
                {$wpdb->prefix}woocommerce_order_itemmeta ltoim ON ltoim.order_item_id = oi.order_item_id AND ltoim.meta_key = '_line_total'
            WHERE
                woim.meta_key = '_product_id'
                AND woim.meta_value = %d
                AND wpposts.post_status = 'wc-completed';",
                $campaign_id
            )
        );
        return $result ? (float) $result->total_sales_amount : 0;
    }

    /**
     * Obtem a meta de arrecadação.
     *
     * @param int $campaign_id ID da campanha.
     * @return float Meta de arrecadação.
     */
    public function get_total_goal($campaign_id)
    {
        return (float) get_post_meta($campaign_id, '_nf_funding_goal', true);
    }

    /**
     * Calcula os dias restantes.
     *
     * @param int $campaign_id ID da campanha.
     * @return int Dias restantes.
     */
    public function get_date_remaining($campaign_id)
    {
        $enddate = get_post_meta($campaign_id, '_nf_duration_end', true);
        $time_remaining = strtotime($enddate) - time();

        if ($time_remaining > 0) {
            return max(1, ceil($time_remaining / 86400)); // Retorna pelo menos 1 dia.
        }

        return 0; // Expirado.
    }

    /**
     * Obtém a URL do autor.
     *
     * @param string $user_login Login do usuário.
     * @return string URL do autor.
     */
    public function get_author_url($user_login)
    {
        $user = get_user_by('login', $user_login);
        if ($user) {
            return esc_url(get_author_posts_url($user->ID));
        }

        return '';
    }

    /**
     * Obtém o nome do autor.
     *
     * @param int $user_id ID do autor (opcional).
     * @return string Nome do autor.
     */
    public function get_author_name($user_id = '')
    {
        if (!$user_id) {
            global $post;
            $user_id = $post->post_author;
        }

        $author_name = '';
        $author = get_userdata($user_id);
        if (isset($author->user_login)) {
            $author_name = isset($author->display_name) ? $author->display_name : $author->user_login;
            if (!empty($author->first_name)) {
                $author_name = $author->first_name . ' ' . $author->last_name;
            }
        }
        return $author_name;
    }
}
