<?php

/**
 * Dashboard Controller V1
 *
 * @package Licenzo\Http\Controller\Api\V1
 */

namespace Licenzo\Http\Controller\Api\V1;

use Licenzo\Framework\Http\Request;
use Licenzo\Modules\WooCommerce\WooCommerceHelper;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Product API controller for managing products and related operations
 */
class ProviderController
{
    public function getWooProducts(Request $request)
    {

        if (!function_exists('wc_get_products')) {
            return [
                'success' => false,
                'message' => 'WooCommerce is not installed or activated.'
            ];
        }

        $search = $request->getSafe('search', 'sanitize_text_field');

        $args = [
            'status' => 'publish',
            's'      => $search,
        ];

        $products = wc_get_products($args);

        $results = [];

        /** @var \WC_Product $product */
        foreach ($products as $product) {
            $hasVariations  = $product->is_type('variable') ? true : false;
            $variations = [];

            if ($hasVariations) {
                $productVariations = $product->get_children();
                foreach ($productVariations as $variationId) {
                    $variation = wc_get_product($variationId);
                    if ($variation) {
                        $variations[] = [
                            'id'    => $variation->get_id(),
                            'name'  => $variation->get_name(),
                            'regular_price' => (float) $variation->get_regular_price(),
                            'sale_price'    => (float) $variation->get_sale_price(),
                        ];
                    }
                }
            }

            $results[] = [
                'id'              => $product->get_id(),
                'name'            => $product->get_name(),
                'status'          => $product->get_status(),
                'regular_price'  => (float) $product->get_regular_price(),
                'sale_price'     => (float) $product->get_sale_price(),
                'description' => wp_strip_all_tags($product->get_description()),
                'image'          => wp_get_attachment_image_url($product->get_image_id(), 'thumbnail') ?: '',
                'has_variations'  => $hasVariations,
                'variations'      => $variations,
            ];
        }

        return [
            'success' => true,
            'products' => $results
        ];
    }

    public function getEddProducts(Request $request)
    {
        if (!post_type_exists('download')) {
            return [
                'success' => false,
                'message' => 'Easy Digital Downloads is not installed or activated.',
            ];
        }

        $search = $request->getSafe('search', 'sanitize_text_field');

        $args = [
            'post_type'      => 'download',
            'post_status'    => 'publish',
            'posts_per_page' => 30,
            'orderby'        => 'title',
            'order'          => 'ASC',
        ];

        if (!empty($search)) {
            $args['s'] = $search;
        }

        $query = new \WP_Query($args);
        $results = [];

        foreach ($query->posts as $post) {
            $downloadId = (int) $post->ID;
            $hasVariablePricing = function_exists('edd_has_variable_prices') && edd_has_variable_prices($downloadId);
            $variations = [];

            if ($hasVariablePricing && function_exists('edd_get_variable_prices')) {
                $prices = edd_get_variable_prices($downloadId);
                if (is_array($prices)) {
                    foreach ($prices as $priceId => $price) {
                        $variations[] = [
                            'id'            => (string) $priceId,
                            'name'          => sanitize_text_field((string) ($price['name'] ?? '')),
                            'regular_price' => (float) ($price['amount'] ?? 0),
                            'sale_price'    => 0.0,
                        ];
                    }
                }
            }

            $regularPrice = 0.0;
            if (!$hasVariablePricing && function_exists('edd_get_download_price')) {
                $regularPrice = (float) edd_get_download_price($downloadId);
            }

            $thumbnail = get_the_post_thumbnail_url($downloadId, 'thumbnail');

            $results[] = [
                'id'             => (string) $downloadId,
                'name'           => $post->post_title,
                'status'         => $post->post_status,
                'regular_price'  => $regularPrice,
                'sale_price'     => 0.0,
                'description'    => wp_strip_all_tags((string) $post->post_excerpt ?: (string) $post->post_content),
                'image'          => $thumbnail ?: '',
                'has_variations' => $hasVariablePricing,
                'variations'     => $variations,
            ];
        }

        return [
            'success'  => true,
            'products' => $results,
        ];
    }

    public function getWooUsers(Request $request)
    {

        // if(!function_exists('wc_get_products')) {
        //     return [
        //         'success' => false,
        //         'message' => 'WooCommerce is not installed or activated.'
        //     ];
        // }

        $search = $request->getSafe('search', 'sanitize_text_field');
        $page = $request->getSafe('page', 'absint', 1);
        $per_page = $request->getSafe('per_page', 'absint', 20);

        $args = [
            'number' => $per_page,
            'offset' => ($page - 1) * $per_page,
            'orderby' => 'display_name',
            'order' => 'ASC',
            'fields' => 'all_with_meta'
        ];

        if (!empty($search)) {
            $args['search'] = '*' . $search . '*';
            $args['search_columns'] = ['user_login', 'user_email', 'display_name', 'user_nicename'];
        }

        $user_query = new \WP_User_Query($args);
        $users = $user_query->get_results();

        $results = [];

        foreach ($users as $user) {
            $results[] = [
                'id' => $user->ID,
                'name' => $user->display_name,
                'email' => $user->user_email,
                'username' => $user->user_login,
                'registered_date' => $user->user_registered,
            ];
        }

        return [
            'success' => true,
            'users' => $results
        ];
    }


    public function getWooOrders(Request $request)
    {

        if (!function_exists('wc_get_order')) {
            return [
                'success' => false,
                'message' => 'WooCommerce is not installed or activated.'
            ];
        }

        $search = $request->getSafe('search', 'sanitize_text_field');
        $order = wc_get_order(absint($search));
        $results = [];

        $products = WooCommerceHelper::getOrderProducts($order);

        $results[] = [
            'id'           => $order->get_id(),
            'number'       => $order->get_order_number(),
            'status'       => wc_get_order_status_name($order->get_status()),
            'total'        => $order->get_total(),
            'currency'     => $order->get_currency(),
            'date_created' => $order->get_date_created()
                ? $order->get_date_created()->date_i18n('Y-m-d H:i:s')
                : '',
            'customer'     => WooCommerceHelper::getCustomerData($order),
            'products'     => $products,
        ];


        return [
            'success' => true,
            'orders'  => $results,
        ];
    }
}
