<?php
namespace WTC_CHECKOUT\Modules\Dashboard\Services;
defined('ABSPATH') || exit;
class DashboardDataService {
    private static $instance = null;
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    public function get_stats($user_id) {
        $total_spent = wc_get_customer_total_spent($user_id);
        $order_count = wc_get_customer_order_count($user_id);
        $points_balance = 0;
        if (class_exists('\WTC_CHECKOUT\Modules\Points\Services\PointsTransactionManager')) {
            $points_balance = \WTC_CHECKOUT\Modules\Points\Services\PointsTransactionManager::get_instance()->get_user_balance($user_id);
        }
        $coupon_count = 0;
        if (class_exists('\WTC_CHECKOUT\Modules\Coupons\Services\CouponManager')) {
            $coupon_count = \WTC_CHECKOUT\Modules\Coupons\Services\CouponManager::get_instance()->get_user_special_coupons_count($user_id);
        }
        return [
            'total_spent' => $total_spent,
            'order_count' => $order_count,
            'points'      => $points_balance,
            'coupons'     => $coupon_count
        ];
    }
    public function get_filtered_orders($user_id, $status = 'all', $date_range = 'all', $paged = 1) {
        $args = array(
            'customer' => $user_id,
            'limit' => 5,
            'page' => $paged,
            'paginate' => true,
            'orderby' => 'date',
            'order' => 'DESC',
        );
        if ($status !== 'all') {
            switch ($status) {
                case 'active':
                    $args['status'] = array('pending', 'processing', 'on-hold', 'shipped');
                    break;
                case 'cancelled':
                    $args['status'] = array('cancelled', 'failed', 'trash');
                    break;
                case 'refunded':
                    $args['status'] = array('refunded', 'refund-requested');
                    break;
                case 'completed':
                    $args['status'] = array('completed');
                    break;
            }
        }
        if ($date_range !== 'all') {
            $date_query = array();
            switch ($date_range) {
                case '30_days':
                    $date_query['after'] = wp_date('Y-m-d', strtotime('-30 days'));
                    break;
                case '6_months':
                    $date_query['after'] = wp_date('Y-m-d', strtotime('-6 months'));
                    break;
                case '1_year':
                    $date_query['after'] = wp_date('Y-m-d', strtotime('-1 year'));
                    break;
            }
            if (!empty($date_query)) {
                $args['date_created'] = '>' . $date_query['after'];
            }
        }
        return wc_get_orders($args);
    }
    public function get_spending_chart_data($user_id, $period = '1_year') {
        $days = ($period === '1_month') ? 30 : (($period === '6_months') ? 180 : 365);
        $interval = ($period === '1_month') ? 'day' : 'month';
        $timezone = wp_timezone();
        $start_date = new \DateTime("-{$days} days", $timezone);
        $end_date = new \DateTime('now', $timezone);
        if ($interval === 'month') {
            $start_date->modify('first day of this month');
        }
        $args = [
            'customer' => $user_id,
            'status' => ['completed', 'processing'],
            'date_created' => $start_date->format('Y-m-d') . '...' . $end_date->format('Y-m-d'),
            'limit' => -1,
            'orderby' => 'date',
            'order' => 'ASC',
        ];
        $orders = wc_get_orders($args);
        $chart_data = [];
        $current = clone $start_date;
        $label_format = ($interval === 'day') ? 'd M' : 'M Y';
        while ($current <= $end_date) {
            $label = date_i18n($label_format, $current->getTimestamp());
            $chart_data[$label] = 0;
            $current->modify("+1 $interval");
        }
        $final_label = date_i18n($label_format, $end_date->getTimestamp());
        if (!isset($chart_data[$final_label])) {
            $chart_data[$final_label] = 0;
        }
        foreach ($orders as $order) {
            $date = $order->get_date_created();
            $label = date_i18n($label_format, $date->getTimestamp());
            if (isset($chart_data[$label])) {
                $chart_data[$label] += (float) $order->get_total();
            }
        }
        return [
            'labels' => array_keys($chart_data),
            'values' => array_values($chart_data)
        ];
    }
}